So, im writing some simple code in python pygame, just to learn. I encountered problem, when i want to check collisions of ball whether it is the same as y possition of my pallete. The main problem is that the value of variable of my pallete is updating by the user, and it sits inside class pallete, in function move. How can i get it out and put it outside class, into function holding ball?
import pygame
from pygame.constants import DROPTEXT
pygame.init()
#window
w_width = 1000
w_height = 600
screen = pygame.display.set_mode((w_width, w_height))
clock = pygame.time.Clock()
open = True
#player
x,y = 100,250
#define player action variables
speed = 5
speed_x,speed_y = 5,4
moving_down = False
moving_up = False
#define ball action variables
x_ball,y_ball = 500,250
radius = 30
class palette(pygame.sprite.Sprite):
global x,y
def __init__(self, x, y, speed):
self.speed = speed
pygame.sprite.Sprite.__init__(self)
self.player_rect = pygame.Rect(x,y,30,100)
def draw(self):
pygame.draw.rect(screen, 'White', self.player_rect)
def move(self, moving_up, moving_down):
#reset movement variables
global dy
dy = 0
#assing movement variables if moving up or down
if moving_up:
dy = -self.speed
if moving_down:
dy = self.speed
#update pallete possition
self.player_rect.y += dy
def ball():
global speed_x,speed_y,x_ball,y_ball
#update pos of bal
x_ball += speed_x
y_ball += speed_y
#basic colision with screen
if x_ball>=w_width-(0.5*radius) or x_ball <=0+(0.5*radius):
speed_x*=-1
if y_ball>=w_height-(0.5*radius) or y_ball <=0+(0.5*radius):
speed_y*=-1
#collision with pallettes
pygame.draw.circle(screen, (255,255,255), (x_ball,y_ball), radius, 5)
#build players and enemies
player = palette(x,y, speed)
enemy = palette(x*9,y, speed)
#game
while open:
for event in pygame.event.get():
#quit game
if event.type == pygame.QUIT:
open = False
#keyboard presses
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
moving_up = True
if event.key == pygame.K_s:
moving_down = True
if event.key == pygame.K_ESCAPE:
open = False
#keyboard button released
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
moving_up = False
if event.key == pygame.K_s:
moving_down = False
screen.fill((0,0,0))
clock.tick(60)
pygame.display.flip
#keys
#init players
player.draw()
enemy.draw()
enemy.move(moving_up, moving_down)
player.move(moving_up, moving_down)
ball()
pygame.display.update()