Snake in Pygame не включает нажатие клавиш - PullRequest
1 голос
/ 17 февраля 2020

Как новичок ie Я хотел написать игру со змеями в Pygame, используя OOP. Я скопировал учебник на Youtube (как и вы), и я полностью озадачен тем, почему змея просто движется в одном направлении и не включает нажатие клавиш. Я попытался добавить подсказку, вставив текст в функции, чтобы я мог видеть, реагирует ли нажатие клавиши, что они есть, но я просто пытался в течение 2 часов, пытаясь разобраться, и я застрял. Пожалуйста, может кто-то со знанием, быстро проверить код и дать мне подсказку, пожалуйста. Буду признателен.

import pygame
import sys
import random
import time

class Snake():
    def __init__(self):
        self.position = [100,550]
        self.body = [[100,550],[90,550],[80,550]]
        self.direction = "DOWN"
        self.changeDirectionTo = self.direction

    def changeDirectTo(self,dir):
        if dir == "RIGHT" and not self.direction == "LEFT":
            self.direction == "RIGHT"
            print ("In changeDirectTo function right")
        if dir == "LEFT" and not self.direction == "RIGHT":
            self.direction == "LEFT"
        if dir == "UP" and not self.direction == "DOWN":
            self.direction == "UP"
        if dir == "DOWN" and not self.direction == "UP":
            self.direction == "DOWN"

    def move(self, foodPos):
        if self.direction == "RIGHT":
            self.position[0] += 10
            print ("in move function Right")
        if self.direction == "LEFT":
            self.position[0] -= 10
            print ("in move function left")
        if self.direction == "UP":
            self.position[1] += 10
        if self.direction == "DOWN":
            self.position[1] -= 10
            print ("in move function down")
        self.body.insert(0, list(self.position))
        if self.position == foodPos:
            return 1
        else:
            self.body.pop()
            return 0

    def checkCollision(self):
        if self.position[0] > 1490 or self.position[0] <0:
            return 1
        elif self.position[1] > 1490 or self.position[1] < 0:
            return 1
        for bodyPart in self.body[1:]:
            if self.position == bodyPart:
                return 1
        return 0
    def getHeadPos(self):
        return self.position
    def getBody(self):
        return self.body
class FoodSpawer():
    def __init__(self):
        self.position = [random.randrange(1,50*10),random.randrange(1,50*10)]
        self.isFoodOnScreen = True

    def spawnFood(self):
        if self.isFoodOnScreen == False:
            self.position
            self.isFoodOnScreen = True
        return self.position
    def setFoodOnScreen(self, b):
        self.isFoodOnScreen = b
window = pygame.display.set_mode((1200,1200))
pygame.display.set_caption("Snake by Mike")
fps = pygame.time.Clock()

score = 0

snake = Snake()
foodSpawner = FoodSpawer()

def gameOver ():
    pygame.quit()
    sys.exit()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameOver()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                snake.changeDirectTo("RIGHT")
                print("Right Press")
            if event.key == pygame.K_LEFT:
                snake.changeDirectTo("LEFT")
                print("Left Press")
            if event.key == pygame.K_UP:
                snake.changeDirectTo("UP")
                print("Up Press")
            if event.key == pygame.K_DOWN:
                snake.changeDirectTo("DOWN")
                print("Down Press")
    foodPos = foodSpawner.spawnFood()
    if (snake.move(foodPos) ==1):
        score  += 1
        foodSpawner.setFoodOnScreen(False)
    window.fill(pygame.Color(255,255,255))
    for pos in snake.getBody():
        pygame.draw.rect(window, pygame.Color(0, 225, 0), pygame.Rect(pos[0], pos[1], 10,10))
    pygame.draw.rect(window, pygame.Color(225,0, 0), pygame.Rect(foodPos[0], foodPos[1], 10,10))
    if snake.checkCollision() == 1:
        gameOver()
    pygame.display.set_caption("Snake by Mike | score: " + str(score))
    pygame.display.flip()
    fps.tick(14)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...