bworley90 bworley90 - 5 months ago 7
Python Question

Moving a drawn rectangle

I have the game come up and the rectangle rendered.
When I press my KEYDOWN it doesn't move the rectangle, it just makes it longer.
I have tried tons of stuff. I am new to Pygame.

Any help would be amazing.

Here is the code:

import pygame
import time
import random
import math
import sys


pygame.init()

display_width = 1200
display_height = 800
white = (255,255,255)
black = (0,0,0)



gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Vertical Pong')
clock = pygame.time.Clock()


def pongBoard(x,y,):
pygame.draw.rect(gameDisplay,white,(x,y,250,25))


def gameLoop():

x = 325
y = 750
xChange = 0



inGame = True

while inGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
xChange = -5
print("Left")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
xChange = 5
print("Right")
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
xChange = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
xChange = 0

pongBoard(x,y)

x += xChange






pygame.display.update()
clock.tick(60)




gameLoop()
pygame.quit()
quit()

Answer

So the problem is this: The rectangle is being constantly redrawn at a different coord, but the screen is not being drawn over the rectangle to cover up the part that is not supposed to be there. In simpler terms, we need to constantly draw the background.

So now the code in the main game loop:

while inGame:
    #This code below draws the background
    pygame.draw.rect(gameDisplay, black, (0, 0, display_width, display_height)) 

That is it! The background will constantly cover up the pong ball, and the pong ball will be constantly blitted to a new position!

P.S, there is a better way to do arrow key movement here: How to get keyboard input in pygame?