Hello there I am trying to create Pong but for some reason I cannot get my rectangles to move up and down. Is it because I converted it into objects and classes because it was working before I converted it. Is there a possible way to fix this? Please tell me where I made a mistake. Thanks!!!!!
Below is my code:
import pygame
pygame.init()
*colours:*
black = ( 0, 0, 0)
white = ( 255, 255, 255)
green = ( 0, 255, 0)
red = ( 255, 0, 0)
*Display*
screen_width = 1000
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Game")
*Rectangles*
class Rectangle():
def __init__(self, screen, x):
self.screen = screen
self.screen_rect= screen.get_rect()
self.x = x
self.y = 250
self.width = 30
self.height = 100
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
self.colour = black
self.velocity = 5
def draw_rectangle(self):
pygame.draw.rect(self.screen, self.colour, self.rect)
rect1 = Rectangle(screen, 50)
rect2 = Rectangle(screen, 920)
game = True
while game:
pygame.time.delay(10)
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
game = False
keys = pygame.key.get_pressed()
**Movements**
if keys[pygame.K_UP] and rect2.y >= 0:
rect2.y -= rect2.velocity
if keys[pygame.K_DOWN] and rect2.y <= 600 - rect2.height:
rect2.y += rect2.velocity
if keys[pygame.K_w] and rect1.y >= 0:
rect1.y -= rect1.velocity
if keys[pygame.K_s] and rect1.y <= 600 - rect1.height:
rect1.x += rect1.velocity
screen.fill(green)
rect1.draw_rectangle()
rect2.draw_rectangle()
# pygame.draw.rect(screen, black, (rect_x2, rect_y2, rect_width2, rect_height2))
pygame.display.update() # Make the most recently drawn screen visible.
pygame.quit()
```