Snake Game question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Snake Game question

Hi Everyone, Would someone be able to look at my code below and tell me had I can get the snake image to turn 90 degrees instead of 45 degrees when moving? I think I have to stop it from moving before it turns but I can't figure out how to do that. Appreciate any help. Thank you! import pygame pygame.init() #create the screen screen = pygame.display.set_mode((800, 600)) # Tile and Icon pygame.display.set_caption("Snake Game") #icon = pygame.image.load('snake.png') #pygame.display.set_icon(icon) # snake Head snakeImg = pygame.image.load('snakeHead.png') snakeImgX = 400 snakeImgY = 300 snakeImgX_change = 0 snakeImgY_change = 0 #Apple appleImg = pygame.image.load('apple.png') appleX = 370 appleY = 480 # score #font = pygame.font.SysFont("comicsansms", 72) #score = font.render("Hello, World", True, (0,128, 0)) def apple(): screen.blit(appleImg, (appleX, appleY)) def snake(): screen.blit(snakeImg, (snakeImgX, snakeImgY)) # Game loop running = True while running: #RGB - Red, Green, Blue screen.fill((0, 150, 0)) for event in pygame.event.get(): # Moving Snake # if keystroke is pressed, check if its up, down, left, or right if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: snakeImgX_change = -2 print("Left arrow if pressed") if event.key == pygame.K_RIGHT: snakeImgX_change = 2 print("Right arroq is pressed") if event.key == pygame.K_UP: snakeImgY_change = -2 print("Up arrow is pressed") if event.key == pygame.K_DOWN: snakeImgY_change = 2 print("Down arrow is pressed") if event.type == pygame.QUIT: running = False snakeImgX += snakeImgX_change snakeImgY += snakeImgY_change if snakeImgX <=0: snakeImgX = 770 elif snakeImgX >= 770: sn

13th Sep 2020, 7:48 PM
David
David - avatar
5 Answers
+ 2
The Cobra should move either in X direction or in Y direction. This means you must switch on the corresponding movement and switch off the other one at the same time. For example: if up: snakeImgY_change = -2 snakeImgX_change = 0
13th Sep 2020, 8:09 PM
JaScript
JaScript - avatar
+ 2
Slick thats for answering. ill look at it.
13th Sep 2020, 8:35 PM
David
David - avatar
+ 1
Nah, but you can take what you need from mine https://github.com/slickwatts/pygames
13th Sep 2020, 8:05 PM
Slick
Slick - avatar
+ 1
JaScript THANK YOU!! it worked.
13th Sep 2020, 8:32 PM
David
David - avatar
+ 1
David your welcome.
13th Sep 2020, 8:36 PM
JaScript
JaScript - avatar