我最近开始使用pygame,并且正在关注TheNewBostons的youtube教程。这是我的主要游戏循环:
def game_loop():
global direction
global tdirection
lead_x=display_width/2
lead_y=display_height/2
block_size=10
change_x=10
change_y=0
game_exit=False
GameOver=False
main_menu=False
snakelist=[]
snakelength=1
applethickness=20
RandAppleX=round(random.randrange(0, display_width-applethickness )/10.0)*10.0
RandAppleY=round(random.randrange(0, display_height-applethickness )/10.0)*10.0
while not game_exit:
while GameOver==True:
game_display.fill(white)
message_screen('You lost, Press Q to quit or C to retry.', red)
pygame.display.update()
for event in pygame.event.get():
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_q:
loss.play()
game_exit=True
GameOver= False
elif event.key==pygame.K_c:
direction='right'
game_loop()
if event.type==pygame.QUIT:
game_exit=True
GameOver= False
for event in pygame.event.get():
if event.type==pygame.QUIT:
game_exit=True
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_a:
change_x=-block_size
direction='left'
change_x=-block_size
change_y=0
elif event.key==pygame.K_d:
direction='right'
change_x=block_size
change_y=0
elif event.key==pygame.K_w:
direction='up'
change_y=-block_size
change_x=0
elif event.key==pygame.K_s:
direction='down'
change_y=block_size
change_x=0
elif event.key==pygame.K_ESCAPE:
pause()
if lead_x>=display_width or lead_x<0 or lead_y>=display_height or lead_y<0:
loss.play()
GameOver=True
lead_x+=change_x
lead_y+=change_y
clock.tick(FPS)
snakehead=[]
snakehead.append(lead_x)
snakehead.append(lead_y)
snakelist.append(snakehead)
if len(snakelist)>snakelength:
del snakelist[0]
for segment in snakelist[:-1]:
if segment==snakehead:
loss.play()
GameOver=True
game_display.fill(white)
game_display.blit(aimg, (RandAppleX, RandAppleY))
snake(snakelist, block_size)
score(snakelength-1)
if lead_x>= RandAppleX and lead_x<= RandAppleX+applethickness and lead_y<= RandAppleY+applethickness and lead_y>= RandAppleY:
RandAppleX=round(random.randrange(0, display_width-applethickness )/10.0)*10.0
RandAppleY=round(random.randrange(0, display_height-applethickness )/10.0)*10.0
snakelength+=1
effect.play()
pygame.display.update()
pygame.quit()
quit()
现在,当蛇向某个方向移动时,我需要防止它自己进食。例如,然后将其向右移动,按键盘上的A按钮将立即使其自动进食,如果向上移动,请按S按钮将执行相同的操作。有办法防止这种情况发生吗?
答案 0 :(得分:2)
一个简单的解决方案可能是通过检查蛇的移动方向是否与请求的方向相反来防止其退回。这将涉及一些额外的检查。像这样:
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_a and direction != 'right':
change_x=-block_size
direction='left'
change_x=-block_size
change_y=0
elif event.key==pygame.K_d and direction != 'left':
direction='right'
change_x=block_size
change_y=0
elif event.key==pygame.K_w and direction != 'down':
direction='up'
change_y=-block_size
change_x=0
elif event.key==pygame.K_s and direction != 'right':
direction='down'
change_y=block_size
change_x=0
答案 1 :(得分:0)
在更改方向时,您只需检查方向是否与当前方向相反,如果是这样,则不设置新方向。这样可以解决问题。