I do not know why i can't add a number to a variable that is equal to a randomly generated number. i have tried a few dumb things like trying to assign a variable to Xplay. Didn't work. all I want to do is just randomly generate a x and y coordinates that will be the position of the rect and after that when ever I press a up, down, left and right key it will move by 10 pixels
import pygame, sys
from pygame.locals import *
import random
pygame.init()
DisplayWidth = 700
DisplayHeight = 400
BoxSize = 10
Black = (0, 0, 0)
DarkGreen = (0, 200, 0 )
Green = (0, 255, 0)
Red = (255, 0, 0)
White = (255, 255, 255)
start = True
DEATH = False
Xplay = random.randrange(2, 68) #error's origin
Yplay = random.randrange(2, 38) #error's origin
Xchange = 0
Ychange = 0
def main():
global FPSClock, Display, Basicfont
pygame.init()
FPSClock = pygame.time.Clock()
Display = pygame.display.set_mode((DisplayWidth, DisplayHeight))
Basicfont = pygame.font.Font('freesansbold.ttf', 30)
while start:
RunGame()
def RunGame():
pygame.draw.rect(Display, DarkGreen, (Xplay, Yplay, 20, 20))
while not DEATH:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or pygame.K_a:
Xchange = -10
Ychange = 0
elif event.key == pygame.K_UP or pygame.K_w:
Xchange = 0
Ychange = -10
elif event.key == pygame.K_DOWN or pygame.K_s:
Xchange = 0
Ychange = 10
elif event.key == pygame.K_RIGHT or pygame.K_d:
Xchange = 10
Ychange = 0
Xplay += Xchange #error
Yplay += Ychange #error
def terminate():
pygame.quit()
sys.exit()