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()
答案 0 :(得分:2)
在您的密码中,您致电:
create_randomPATH(x, y)
在该功能中,您可以更改例如 local 的值。 x
此处:
x += 2
但是,这不会更改函数外部具有相同名称的变量。变量名代码中的标签有something called "scope",这会影响Python何时将它们视为同一条数据。
有多种方法可以让你的变量成为全局变量,但在这里我建议你使用列表赋值,部分原因是你已经从你的函数中做了return (x, y)
:
x, y = create_randomPATH(x, y)