0
因此,我在Pygame中有一個矩形,它隨機且對角地移動。我怎樣才能讓它只向左,向右,向前或向後移動。而且,遇到障礙物時,應該旋轉90度並改變方向。下面的代碼我有:在Python中移動一個矩形
# Main program loop
while not done:
# Loop through any window events
for event in pygame.event.get():
# The user clicked 'close' or hit Alt-F4
if event.type == pygame.QUIT:
done = True
# The user clicked the mouse button
# or pressed a key
elif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.KEYDOWN:
# Is the ball not moving?
if ball.change_y == 0:
# Start in the middle of the screen at a random y location
ball.rect.x = screen_width/2
ball.rect.y = random.randrange(10, screen_height - 0)
# Set a random vector
ball.change_y = random.randrange(-5, 6)
ball.change_x = random.randrange(5, 10)
# Is the ball headed left or right? Select randomly
if(random.randrange(2) == 0):
ball.change_x *= -1
謝謝,但我應該在哪裏放置該代碼? – doens 2014-11-06 18:47:54
這取決於你想要什麼。你會想把它放在遊戲循環的某個地方。如果用戶使用箭頭鍵控制它,您可以將它放在'pygame.keydown' if語句中,並將'if ball_moving_up/down/right/left'更改爲'if pygame.key == K_RIGHT/K_LEFT/K_DOWN/K_UP'。 – Anthony 2014-11-06 20:21:32