Python Forum
[PyGame] Snake not changing directions in Snake Game
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Snake not changing directions in Snake Game
#1
I tried making a version of the snake game in python using pygame. I am not receiving any errors, however when i press an arrow key, the snake does not change directions.
Here is my code:
import pygame
import sys
import random
import time

pygame.init()

class Snake():
    def __init__(self):
        self.position = [100,50]
        self.body = [[100,50],[90,50],[80,50]]
        self.direction = "RIGHT"
       
    def changeDirTo(self,dir):
        if dir=="RIGHT" and not self.direction=="LEFT":
            self.direction = "RIGHT"
        elif dir=="LEFT" and not self.direction=="RIGHT":
            self.direction = "LEFT"
        elif dir=="UP" and not self.direction=="DOWN":
            self.direction = "UP"
        elif dir=="DOWN" and not self.direction=="UP":
            self.direction = "DOWN"
        
    def move(self,foodPos):
        if self.direction == "RIGHT":
            self.position[0] = self.position[0] + 10
        elif self.direction == "LEFT":
            self.position[0] = self.position[0] - 10
        elif self.direction == "UP":
            self.position[1] = self.position[1] - 10
        elif self.direction == "DOWN":
            self.position[1] = self.position[1] + 10
        self.body.insert(0,list(self.position))
        
        if self.position == foodPos:
            return 1
        else:
            self.body.pop()
            return 0

    def move_Right(self):
        self.position[0] = self.position[0] + 10
    def move_Left(self):
        self.position[0] = self.position[0] - 10
    def move_Up(self):
        self.position[0] = self.position[1] - 10
    def move_Down(self):
        self.position[0] = self.position[1] + 10
    
    def checkCollision(self):
        if self.position[0] > 490 or self.position[0] < 0:
            return 1 
        elif self.position[1] > 490 or self.position[1] < 0:
            return 1
        for bodyPart in self.body[1:]:
            if self.position == bodyPart:
                return 1
        return 0

    def getHeadPosition(self):
        return self.position
    
    def getBody(self):
        return self.body


class FoodSpawn():
    def __init__(self):
        self.position = [random.randint(1,50)*10,random.randint(1,50)*10]
        self.isFoodOnScreen = True

    def spawnFood(self):
        if self.isFoodOnScreen == False:
            self.position = [random.randrange(1,50)*10,random.randrange(1,50)*10]
            self.isFoodOnScreen == True
        return self.position
    
    def setFoodOnScreen(self,b):
        self.isFoodOnScreen = b


window = pygame.display.set_mode((500,500))
pygame.display.set_caption("Snake Game")
fps = pygame.time.Clock()

score = 0

snake = Snake()
foodSpawner = FoodSpawn()

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.changeDirTo('RIGHT')
               
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake.changeDirTo('UP')
                

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                snake.changeDirTo('DOWN')
                

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                snake.changeDirTo('LEFT')
              


    foodPos = foodSpawner.spawnFood()
    if(snake.move(foodPos)==1):
        score+=1
        foodSpawner.setFoodOnScreen(False)

    window.fill(pygame.Color(225,225,225))

    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 | Score: " + str(score))
    pygame.display.flip()
    fps.tick(10)

pygame.quit()
I've read over similar threads and I can't seem to find a solution. All help is appreciated.
Reply
#2
first keydown well catch all keydown.
elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                snake.changeDirTo('RIGHT')
                
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake.changeDirTo('UP')
                 
 
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                snake.changeDirTo('DOWN')
                 
 
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                snake.changeDirTo('LEFT')
should be
elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                snake.changeDirTo('RIGHT')
                
            elif event.key == pygame.K_UP:
                snake.changeDirTo('UP')
                 
            elif event.key == pygame.K_DOWN:
                snake.changeDirTo('DOWN')                 

            elif event.key == pygame.K_LEFT:
                snake.changeDirTo('LEFT')
99 percent of computer problems exists between chair and keyboard.
Reply
#3
(Aug-10-2018, 05:55 PM)Windspar Wrote: first keydown well catch all keydown.
elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: snake.changeDirTo('RIGHT') elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: snake.changeDirTo('UP') elif event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: snake.changeDirTo('DOWN') elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: snake.changeDirTo('LEFT')
should be
elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: snake.changeDirTo('RIGHT') elif event.key == pygame.K_UP: snake.changeDirTo('UP') elif event.key == pygame.K_DOWN: snake.changeDirTo('DOWN') elif event.key == pygame.K_LEFT: snake.changeDirTo('LEFT')
Good catch. That fixed the problem I was having, however now when the snake eats the food, the food keeps changing locations rapidly.
Reply
#4
You didn't assign isFoodOnScreen to True. You did comparison.
def spawnFood(self):
        if self.isFoodOnScreen == False:
            self.position = [random.randrange(1,50)*10,random.randrange(1,50)*10]
            self.isFoodOnScreen == True # You did comparison
99 percent of computer problems exists between chair and keyboard.
Reply
#5
(Aug-11-2018, 08:20 PM)Windspar Wrote: You didn't assign isFoodOnScreen to True. You did comparison.
def spawnFood(self): if self.isFoodOnScreen == False: self.position = [random.randrange(1,50)*10,random.randrange(1,50)*10] self.isFoodOnScreen == True # You did comparison
Yes I also caught that a few minutes after I made the post. Hopefully somebody here can learn from my mistake.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to add segments to the snake body blacklight 1 2,869 Sep-13-2023, 07:33 AM
Last Post: angelabarrios
  [PyGame] Snake game: how to get an instance for my snake's body multiple times? hajebazil 2 2,139 Jan-30-2022, 04:58 AM
Last Post: hajebazil
  Rocket will only move in two directions djwilson0495 7 3,765 Dec-14-2020, 05:43 PM
Last Post: djwilson0495
  help with snake game blacklight 3 2,590 Jul-30-2020, 01:13 AM
Last Post: nilamo
  Snake Game - obstacle problem Samira 3 5,588 Oct-31-2019, 02:58 PM
Last Post: Samira
  [PyGame] Made my first Python program: Snake. Please help me improve it andrerocha1998 7 6,130 Feb-19-2019, 07:08 PM
Last Post: Windspar
  Creating Snake game in Turtle Shadower 1 8,642 Feb-11-2019, 07:00 PM
Last Post: woooee
  [PyGame] Basic Snake game (using OOP) PyAlex 1 12,524 Sep-10-2018, 09:02 PM
Last Post: Mekire
  [PyGame] Snake controls not working jakegold98 5 6,370 Dec-12-2017, 01:45 AM
Last Post: Windspar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020