Reputation: 5
ok so I'm 14 and don't know that much so this is probably going to be a bit of a dumb question but currently I am trying to write a program that will have a small block moving randomly around the screen and I don't see the issue with what I have done.
import pygame,sys,random
from pygame.locals import *
#colours
red =(255,0,0)
white=(255,255,255)
#variables/objects
ship_width = 60
x = 400
y = 520
FPS = 60
clock =pygame.time.Clock()
screen = pygame.display.set_mode((800,600))
def move_rect(x,y):
ship = pygame.draw.rect(screen,red,(x,y,ship_width,ship_width))
def create_randomPATH(x,y):
random_gen = False
if random_gen == False:
randomX = random.randint(1,60)
randomY = random.randint(1,60)
random_gen = True
want_valX = x + randomX
want_valY = y + randomY
if want_valX != x:
x += 2
elif want-valY != y:
y += 2
print (x,y)
return x,y
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x -= 10
if event.key == pygame.K_RIGHT:
x += 10
if event.key == pygame.K_DOWN:
y += 10
if event.key == pygame.K_UP:
y -= 10
screen.fill(white)
create_randomPATH(x, y)
print (x,y)
move_rect(x, y)
pygame.display.update()
Upvotes: 0
Views: 1043
Reputation: 27227
In your code you call:
create_randomPATH(x, y)
And in that function you change the local value of e.g. x
here:
x += 2
However, this does not change the variable with the same name outside of your function. The labels in the code for variable names have something called "scope" which affects when Python will treat them as the same piece of data or not.
There are ways to make your variables global, but instead here I would recommend you use a list assignment, in part because you already do a return (x, y)
from your function:
x, y = create_randomPATH(x, y)
Upvotes: 2