2017-06-21 165 views
0

因此,我已經開始從Youtube上的新波士頓學習PyGame,並且我有點卡在boundaries video上。Pygame邊界問題

在錄像中,在1:50,他的類型:

if lead_x > display_width or lead_x < 0 or lead_y > display_height or lead_y < 0: 
     gameExit = True 

這臺遊戲中顯示的邊界。遊戲在蛇經過它後退出。但是,當我做同樣的事情時,它似乎對我的程序沒有影響。蛇不停地播放節目。有什麼我做錯了嗎?源代碼如下。謝謝!

import pygame 

pygame.init() 

display_width = 800 
display_height = 600 

gameDisplay = pygame.display.set_mode((display_width,display_height)) 
pygame.display.set_caption('Snake') 

white = (255,255,255) 
black = (0,0,0) 
red = (255,0,0) 

pygame.display.update() 

gameExit = False 

lead_x = 300 
lead_y = 300 
lead_x_change = 0 
lead_y_change = 0 

clock = pygame.time.Clock() 

while not gameExit: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      gameExit = True 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT: 
       lead_x_change = -10 
       lead_y_change = 0 
      elif event.key == pygame.K_RIGHT: 
       lead_x_change = 10 
       lead_y_change = 0 
      elif event.key == pygame.K_UP: 
       lead_y_change = -10 
       lead_x_change = 0 
      elif event.key == pygame.K_DOWN: 
       lead_y_change = 10 
       lead_x_change = 0 
    if lead_x > display_width or lead_x < 0 or lead_y > display_height or lead_y < 0: 
     gameExit = True 

    lead_x += lead_x_change 
    lead_y += lead_y_change 
    gameDisplay.fill(white) 
    pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10]) 
    pygame.display.update() 
    clock.tick(15) 

pygame.quit() 
quit() 
+0

我複製和粘貼代碼,它的工作方式和預期的一樣。我會使用'Rect'類而不是那種不方便的'if'語句,但是可能你想要一步一步地按照你的視頻..... – sloth

回答

0

其實用pygame測試你的代碼後,它似乎工作正常。然而角色確實離開了屏幕。下面的代碼將防止角色離開屏幕。


你需要檢查lead_x & lead_y加入量移動(例如lead_x + lead_x_changed) 改變的行:

if (lead_x + lead_x_change) > display_width or (lead_x + lead_x_change) < 0 or (lead_y + lead_y_change) > display_height or (lead_y + lead_y_change) < 0: 

完整的示例:

lead_x = 300 
lead_y = 300 
lead_x_change = 0 
lead_y_change = 0 

clock = pygame.time.Clock() 
gameExit = False 

while not gameExit: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      gameExit = True 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT: 
       lead_x_change = -10 
       lead_y_change = 0 
      elif event.key == pygame.K_RIGHT: 
       lead_x_change = 10 
       lead_y_change = 0 
      elif event.key == pygame.K_UP: 
       lead_y_change = -10 
       lead_x_change = 0 
      elif event.key == pygame.K_DOWN: 
       lead_y_change = 10 
       lead_x_change = 0 


    lead_x += lead_x_change 
    lead_y += lead_y_change 
    gameDisplay.fill(white) 
    pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10]) 
    pygame.display.update() 
    clock.tick(15) 
    if (lead_x + lead_x_change) > display_width or (lead_x + lead_x_change) < 0 or (lead_y + lead_y_change) > display_height or (lead_y + lead_y_change) < 0: 
     gameExit = True 

pygame.quit() 
quit()