Python Forum
[PyGame] Snake controls not working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Snake controls not working
#1
I have been following a class on udemy for pygame and were starting with this snake game. I get no errors but there has to be something I am missing in the code because the snake doesn't move with the controls I made, WASD, or the arrow keys. Hopefully someone can help me figure out why!
import pygame, sys, random, time

pygame.init()

# Play surface
playSurface = pygame.display.set_mode((720, 460))
pygame.display.set_caption('Snake')

# Colors
red   = pygame.Color(255, 0, 0) #gameover
green = pygame.Color(0, 255, 0) #snake
black = pygame.Color(0, 0, 0) #score 
white = pygame.Color(255, 255, 255) #background
gold  = pygame.Color(255, 215, 0) #food

#FPS Controller
fpsController = pygame.time.Clock()

#Important variables
snakePos  = [100, 50]
snakeBody = [[100, 50], [90, 50], [80, 50]]

foodPos   = [random.randrange(1,72)*10, random.randrange(1,46)*10]
foodSpawn = True

direction = 'RIGHT'
changeTo  = direction

#Game Over Function
def gameOver():
	myFont = pygame.font.SysFont('monaco', 72)
	GOsurf = myFont.render('You Suck', True, red)
	GOrect = GOsurf.get_rect()
	GOrect.midtop = ((360, 15))
	playSurface.blit(GOsurf, GOrect)
	pygame.display.update()
	time.sleep(5)
	pygame.QUIT() #pygame exit
	sys.exit() #console exit

#Main Logic
while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			sys.exit()
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_RIGHT or event.key == ord('d'):
				changeto = 'RIGHT'
			if event.key == pygame.K_LEFT or event.key == ord('a'):
				changeto = 'LEFT'
			if event.key == pygame.K_UP or event.key == ord('w'):
				changeto = 'UP'
			if event.key == pygame.K_DOWN or event.key == ord('s'):
				changeto = 'DOWN'
			if event.key == pygame.K_ESCAPE:
				pygame.event.post(pygame.event.event(QUIT))

	# validation of direction
	if changeTo == 'RIGHT' and not direction == 'LEFT':
		direction = 'RIGHT'  
	if changeTo == 'LEFT' and not direction == 'RIGHT':
		direction == 'LEFT'
	if changeTo == 'UP' and not direction == 'DOWN':
		direction == 'UP'        
	if changeTo == 'DOWN' and not direction == 'UP':
		direction == 'DOWN'    

	if direction == 'RIGHT':
		snakePos[0] += 10
	if direction == 'LEFT':
		snakePos[0] -= 10
	if direction == 'UP':
		snakePos[1] -= 10
	if direction == 'DOWN':
		snakePos[1] += 10

	# Snake body mechanics
	snakeBody.insert(0, list(snakePos))
	if snakePos[0] == foodPos[0] and snakePos[1] == foodPos[1]:
		foodSpawn = False
	else:
		snakeBody.pop()
	
	# Food spawn
	if foodSpawn == False:
		foodPos = [random.randrange(1,72)*10, random.randrange(1,46)*10]
	foodSpawn = True

	playSurface.fill(white)
	for pos in snakeBody:
		pygame.draw.rect(playSurface, green, pygame.Rect(pos[0], pos[1], 10, 10))



	pygame.display.update()
	fpsController.tick(25)
Reply
#2
You have a few errors
line 38 should be pygame.quit()
line 49, 51, 53, 55 should be changeTo
line 63, 65, 67 should be = not ==

Just to let you know pygame has builtin colors. all your def colors are builtin.
pygame.Color('red')
Builtin colors describe here
99 percent of computer problems exists between chair and keyboard.
Reply
#3
There is a lot of extra code here that is not needed. First of all
Quote:if event.key == pygame.K_RIGHT or event.key == ord('d'):
pygame has a keys for every possible keyboard input, including WASD movements. Im not sure why you chose to do ord()?
https://www.pygame.org/docs/ref/key.html

You can substitute that for pygame.K_w for 'W' and so on.

You can also just use the in operator and do
if event.key in [pygame.K_RIGHT, pygame.K_d]:
Quote:
if changeTo == 'RIGHT' and not direction == 'LEFT':
If you input the right arrow key than you wouldnt be inputting the left one. This is just redundant code that doesnt need to be there.

So is this
Quote:if direction == 'RIGHT':
You are already checking the event.key for pygame.RIGHT....why do it again?

you can remove all that and just do
if event.key in [pygame.K_RIGHT, pygame.K_d]:
    snakePos[0] += 10
Please save yourself the headache and dont do this
Quote:
#Game Over Function
def gameOver():
    myFont = pygame.font.SysFont('monaco', 72)
    GOsurf = myFont.render('You Suck', True, red)
    GOrect = GOsurf.get_rect()
    GOrect.midtop = ((360, 15))
    playSurface.blit(GOsurf, GOrect)
    pygame.display.update()
    time.sleep(5)
    pygame.QUIT() #pygame exit
    sys.exit() #console exit

A rule of thumb is you should only every have to type this once EVER in your game
pygame.display.update()
If you do it more then you are creating spaghetti code. The proper way would be to use a state machine. Which would be a game over state to handle what happens if a player died etc.

A proper structure would be in the tutorials in how to organize the code.

You also shouldnt be doing this anyways
Quote:
snakePos  = [100, 50]
why bother when pygame has pygame.Rect whihc handles position and collision which you will need anyways. Its also more simple to read player.rect.x rather than snakePos[0]
Recommended Tutorials:
Reply
#4
Thank you so much for all your help! But also as I stated I am just following what the course I am doing says. I do not know a lot of things so learning anything is vital to me for now. Regardless of how useless it is, I do agree though I realized in the tutorials and guides that some of the code didn't really make sense to me and that confused me so I guess it makes sense now. I have been struggling to find a solid book, or course or something in really learning pygame most of the time the tutorials are very general or just don't explain enough into what you are actually writing.
Reply
#5
Well at least you are aware of it is all you need. Some people are not.

Pygame doesnt really have a good book. When i say good book i mean one that uses OOP.
There are some books/tutorials
http://programarcadegames.com/
https://inventwithpython.com/pygame/

but there is no real in depth book that covers everything. A lot of what i learned was more from forums asking question as i came up to the problem i had.
Recommended Tutorials:
Reply
#6
You are learning a very ugly way.
What do you want to know ? I an others will help you.
Here are some example of boiler plates.
# simple pygame boiler plate
import pygame

def main():
	pygame.init()
	pygame.display.set_caption("Simple Pygame Boiler Plate")
	screen = pygame.display.set_mode((720, 460))
	clock = pygame.time.Clock()
	
	running = True
	while running:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				running = False
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_ESCAPE:
					running = False
		
		screen.fill((0,0,40))
		# draw code here
		
		pygame.display.flip()
		clock.tick(30)
		
	pygame.quit()
	
if __name__ == '__main__':
	main()
# class base boiler plate
import pygame

class Game:
	SIZE = None
	
	def __init__(self, caption, size, ):
		Game.SIZE = size
		pygame.display.set_caption(caption)		
		self.screen = pygame.display.set_mode(size)
		self.clock = pygame.time.Clock()
		
	def loop(self):
		self.running = True
		while self.running:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					self.running = False
				elif event.type == pygame.KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						self.running = False
			
			self.screen.fill((0,0,40))
			# draw code here
			
			pygame.display.flip()
			self.clock.tick(30)
			
		pygame.quit()

def main():
	pygame.init()
	game = Game('Class Boiler Plate', (720, 460))
	game.loop()
	
if __name__ == '__main__':
	main()
This is my intense boiler plate.
My Boiler Plate Github
99 percent of computer problems exists between chair and keyboard.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to add segments to the snake body blacklight 1 2,786 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,098 Jan-30-2022, 04:58 AM
Last Post: hajebazil
  help with snake game blacklight 3 2,536 Jul-30-2020, 01:13 AM
Last Post: nilamo
  [PyGame] Terrible Sprite controls, need help. michael1789 16 5,260 Dec-18-2019, 10:32 PM
Last Post: michael1789
  Snake Game - obstacle problem Samira 3 5,382 Oct-31-2019, 02:58 PM
Last Post: Samira
  [PyGame] Made my first Python program: Snake. Please help me improve it andrerocha1998 7 5,998 Feb-19-2019, 07:08 PM
Last Post: Windspar
  Creating Snake game in Turtle Shadower 1 8,604 Feb-11-2019, 07:00 PM
Last Post: woooee
  [PyGame] Basic Snake game (using OOP) PyAlex 1 12,411 Sep-10-2018, 09:02 PM
Last Post: Mekire
  [PyGame] Snake not changing directions in Snake Game Bjdamaster 4 4,840 Aug-13-2018, 05:09 AM
Last Post: Bjdamaster

Forum Jump:

User Panel Messages

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