2014-11-06 71 views
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 

回答

0

你將要使用的transform模塊,使矩形旋轉。例如,pygame.transform.rotate(ball.rect,90)。至於移動,您需要更改ball.rect.xball.rect.y的值。例如:

if ball_moving_up: 
    ball.rect.y += 5 #The smaller the increment the smoother it will appear 
if ball_moving_down: 
    ball.rect.y -= 5 
if ball_moving_right: 
    ball.rect.x += 5 
if ball_moving_left: 
    ball.rect.x -= 5 

另外,您將要在每次增量後更新背景,否則您的矩形將顯示爲實線。

評論如果您有任何疑問。 希望這有助於。

+0

謝謝,但我應該在哪裏放置該代碼? – doens 2014-11-06 18:47:54

+0

這取決於你想要什麼。你會想把它放在遊戲循環的某個地方。如果用戶使用箭頭鍵控制它,您可以將它放在'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