2016-12-26 182 views
0

好吧,所以我14歲,並不知道這麼多,所以這可能會有點愚蠢的問題,但目前我正試圖編寫一個程序,將隨機移動一個小塊在屏幕周圍,我沒有看到我所做的事情。Pygame中的隨機移動

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

是什麼錯誤? – Octo

+0

你需要做'導入隨機' – Octo

回答

2

在你的代碼調用:

create_randomPATH(x, y) 

而且在功能更改的例如在本地x這裏:

x += 2 

然而,這並沒有改變的同名變量的函數之外。變量名稱代碼中的標籤有something called "scope",它會影響Python何時將它們視爲同一條數據。

有辦法讓你的變量全球性的,而是在這裏我會建議你使用一個列表賦值,部分原因是因爲你已經從你的函數做return (x, y)

x, y = create_randomPATH(x, y)