简体   繁体   English

Pygame 事件错误

[英]Pygame event bug

I recently started making Snake in pygame.我最近开始在 pygame 中制作 Snake。 Firstly, I was writing the code without OOP.首先,我在没有面向对象编程的情况下编写代码。 When I noticed that it would look better with classes, I edited the code.当我注意到类会更好看时,我编辑了代码。 Now the first three times, the snake moves normally, but after that when I push the left arrow or the right arrow or the downwards arrow, snake goes down.现在前 3 次,蛇正常移动,但是当我按下向左箭头或向右箭头或向下箭头时,蛇向下移动。 When I didn't have classes, the program worked the way it should.当我没有课时,该程序按其应有的方式运行。 Now it doesn't.现在没有了。 Can you help me?你能帮助我吗?

This is my code:这是我的代码:

import pygame, math, random

pygame.init()

screen = pygame.display.set_mode((640,640))
pygame.display.set_caption('Snake')

class Snake(object):
    def __init__(self):
        self.x, self.y = 320,320
        self.dirUp, self.dirDown = False, False
        self.dirLeft, self.dirRight = False, False
        self.body = [(self.x, self.y)]
        self.snakeImg = [pygame.image.load('snakeblock.png') for i in range(len(self.body))]

snake = Snake()

squares = []
for i in range(640):
    if i % 32 == 0:
        squares.append(i)
food = pygame.image.load('fruit.png')
foodx,foody = random.choice(squares), random.choice(squares)

def isCollision(obsX, obsY, x, y):
#          D   I   S   T   A   N   C   E
    return math.sqrt(math.pow(obsX - x, 2) + math.pow(obsY - y, 2)) <= 0

over_font = pygame.font.Font('freesansbold.ttf',64)
score_font = pygame.font.Font('freesansbold.ttf',32)
score = 0

def show_text():
    score_text = score_font.render('Score: {}'.format(score), True, (255,255,255))
    over_text = over_font.render('GAME OVER', True, (255,255,255))
    screen.blit(score_text, (0,0))

running = True

while running:

    pygame.time.delay(160)
    screen.fill((0,128,0))


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake.dirUp = True
                snake.dirLeft, dirDown, dirRight = False, False, False
            if event.key == pygame.K_DOWN:
                snake.dirDown = True
                snake.dirUp, dirLeft, dirRight = False, False, False
            if event.key == pygame.K_RIGHT:
                snake.dirRight = True
                snake.dirUp, dirDown, dirLeft = False, False, False
            if event.key == pygame.K_LEFT:
                snake.dirLeft = True
                snake.dirUp, dirDown, dirRight = False, False, False
    if snake.dirUp:
        snake.y -= 32
    elif snake.dirDown:
        snake.y += 32
    elif snake.dirRight:
        snake.x += 32
    elif snake.dirLeft:
        snake.x -= 32

    for i in range(len(snake.body)):
        if isCollision(foodx,foody,snake.body[i][0],snake.body[i][1]):
            foodx, foody = random.choice(squares), random.choice(squares)
            score += 1
        screen.blit(food, (foodx, foody))
        screen.blit(snake.snakeImg[i], (snake.x, snake.y))

    show_text()
    pygame.display.update()

the problem is here问题就在这里

snake.dirLeft, dirDown, dirRight = False, False, False

which should have been应该是

snake.dirLeft, snake.dirDown, snake.dirRight = False, False, False

in python it is not recommended to use multiple assigments unless you unpacking values from tuple/list.在 python 中,除非您从元组/列表中解压值,否则不建议使用多个赋值。 As you can see this would be much more readable :)如您所见,这将更具可读性:)

snake.dirLeft = False
snake.dirDown = False
snake.dirRight = False

and there is another problem because snake get his body coords static in a moment Snake instance created, here is possible solution还有另一个问题,因为蛇在创建 Snake 实例的那一刻使他的身体坐标静止,这是可能的解决方案

class Snake(object):
    def __init__(self):
        self.x, self.y = 320, 320
        self.dirUp, self.dirDown = False, False
        self.dirLeft, self.dirRight = False, False
        self.snakeImg = [pygame.image.load('snakeblock.png')
                         for i in range(len(self.body))]

    @property
    def body(self):
        return [(self.x, self.y)]

hovewer you still have to think out a way to increase it's body但是你还是得想办法增加它的体型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM