所以,我已经开始在Youtube上从新闻波士顿学习PyGame了,我有点卡在boundaries video上。
在视频中,在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 :(得分:0)
实际上在用pygame测试你的代码之后,似乎工作正常。然而角色确实离开了屏幕。下面的代码将阻止角色离开屏幕。
您需要检查lead_x
&amp; 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()