首页 > 解决方案 > 如何让蛇继续朝那个方向前进,直到按下另一个箭头键

问题描述

我已经尝试了很多想法,比如导入 pynput,但它一直在崩溃,让我的电脑一团糟。我试过把它放在一个循环中,但效果不佳并且一直崩溃

import sys
import pygame
import random
import os
import time

pygame.init()

#assigns thingys to window adjustments
size = width, height = 750, 750
white = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Snake Game")

#The coordinates and size of the snake square thingy
x = 350
y = 350
w  = 25
h = 25
ax = range(30,700)
ay = range(40,700)
aw = 15 
ah = 15
vel = 10
vertical1 = 9000
vertical2 = 0 

score_value = 0 
font = pygame.font.Font('freesansbold.ttf', 32)
textx = 10
testy = 10

def show_score(x, y): 
    score = font.render("Score: "+ str(score_value), True, (255,0,0))
    screen.blit(score, (x, y))


def divisible_random(a,b,n):
    if b-a < n:
      raise Exception('{} is too big'.format(n))
    result = random.randint(a, b)
    while result % n != 0:
      result = random.randint(a, b)
    return result

def apple(x,y):
   pygame.draw.rect(screen, (255, 0, 0),  (arx, ary, aw, ah))



arx = divisible_random(30,700,10)
ary = divisible_random(40,700,10)



    

while 1:
    
    #Delays the movement so you can see snake thingy fps
    pygame.time.delay(25)

    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    #gets the presses to move the snake 
    keys = pygame.key.get_pressed() 
    
    if keys[pygame.K_LEFT]:
        while True:
            x= x - vel
            if keys[pygame.K_RIGHT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
                break

    if keys[pygame.K_RIGHT]:
        while True:
            x= x + vel
            if keys[pygame.K_LEFT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
                break


    if keys[pygame.K_DOWN]:
        while True:
            y = y + vel
            if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_UP]:
                break

    if keys[pygame.K_UP]:
        while True:
            y = y - vel
            if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_DOWN]:
                break

    screen.fill(white)

    #The snake thingy and apple thingy
    apple(arx, ary)
    snake = pygame.draw.rect(screen, (0, 0, 0), (x, y, w, h))
    diffrencex = abs(arx-x)
    diffrencey = abs(ary-y)

    if ((x == arx and y == ary) or ((diffrencex == 10 and x < arx) and (diffrencey == 10 and y < ary)) or ((diffrencex==10 and x< arx) and (y == ary)) or ((x == arx) and (diffrencey==10 and y< ary))):
        score_value += 1
        arx = divisible_random(30,700,10)
        ary = divisible_random(40,700,10)

    #Borders for the frame thingy 
    pygame.draw.line(screen, (0,0,0), (14, 10), (14, 800), 30)
    pygame.draw.line(screen, (0,0,0), (734, 10), (734, 800), 30) 
    pygame.draw.line(screen, (0,0,0), (9000, 734), (0 , 734), 30) 
    pygame.draw.line(screen, (0,0,0), (9000, 24), (0 , 24), 30) 
  
    if x < 30:
        x = 700
    
    if x > 700:
        x = 30
    
    if y > 700:
        y = 40
    
    if y < 40:
        y = 700

    show_score(textx, testy)
    

    print(arx,ary,x,y)

    pygame.display.update()  
pygame.quit

我知道代码不整洁,没有条理,但我一完成游戏就开始工作

    keys = pygame.key.get_pressed() 
    
    if keys[pygame.K_LEFT]:
        while True:
            x= x - vel
            if keys[pygame.K_RIGHT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
                break

    if keys[pygame.K_RIGHT]:
        while True:
            x= x + vel
            if keys[pygame.K_LEFT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
                break


    if keys[pygame.K_DOWN]:
        while True:
            y = y + vel
            if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_UP]:
                break

    if keys[pygame.K_UP]:
        while True:
            y = y - vel
            if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_DOWN]:
                break

确切地说,我在这里遇到问题

标签: pythonpygame2d-games

解决方案


使用键盘事件 ( KEYDOWN, KEYUP-see pygame.event) 而不是pygame.key.get_pressed(). 添加一个变量并在分别按下、、direction时更改变量的状态。根据方向改变玩家的位置:LEFTRIGHTUPDOWN

direction = (0, 0)

while 1:
    
    #Delays the movement so you can see snake thingy fps
    pygame.time.delay(25)

    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                direction = (-1, 0)
            elif event.key == pygame.K_RIGHT:
                direction = (1, 0)
            elif event.key == pygame.K_UP:
                direction = (0, -1)
            elif event.key == pygame.K_DOWN:
                direction = (0, 1)

    x += vel * direction[0]
    y += vel * direction[1]

您想要连续移动,但又不想按住按钮。即使没有按键,你也想移动蛇。因此,您需要将运动方向保存在一个变量中,并在按下某个键时更改一次方向。键盘事件在按键被按下时发生一次,是改变方向的正确选择。


推荐阅读