snake game | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

snake game

Hi Everyone, I'm almost finished with my snake game but have a bug when the snake and the apple collide the second time. The first time works; the apple is set to a new location, but the second time it doesn't move. I see in my terminal the values are changing when they do collide, but again, the apple does not move. Also I had to take some lines out. Not all of it would fit Appreciate any help Thank you! #create the screen screen = pygame.display.set_mode((800, 600)) # Tile and Icon pygame.display.set_caption("Snake Game") # snake Head snakeImg = pygame.image.load('snakeHead.png') snakeImgX = 400 snakeImgY = 300 snakeImgX_change = 0 snakeImgY_change = 0 # snake body snakeBody = pygame.image.load('snakeBody.png') #Apple appleImg = pygame.image.load('apple.png') appleX = random.randint(0, 800) appleY = random.randint(50, 150) def apple(x, y): screen.blit(appleImg, (appleX, appleY)) def snake(x, y): screen.blit(snakeImg, (snakeImgX, snakeImgY)) def isCollison(snakeImgX, snakeImgY, appleX, appleY): distance = math.sqrt((math.pow(snakeImgX - appleX, 2)) + (math.pow(snakeImgY - appleY, 2))) if distance < 27: return True else: return False # Game loop running = True while running: screen.fill((0, 150, 0)) for event in pygame.event.get(): # if keystroke is pressed, check if its up, down, left, or right if event.type == pygame.QUIT: running = False # Moving Snake snakeImgX += snakeImgX_change snakeImgY += snakeImgY_change if snakeImgX <=0: snakeImgX = 770 elif snakeImgX >= 770: snakeImgX = 0 if snakeImgY <=0: snakeImgY = 570 elif snakeImgY >= 570: snakeImgY = 0 # Collision collision = isCollison(snakeImgX, snakeImgY, appleX, appleY) if collision: appleY = 480 snake(snakeImgX, snakeImgY) apple(appleX, appleY) pygame.display.update()

14th Sep 2020, 7:08 PM
David
David - avatar
4 Antworten
+ 6
David so I checked the code, you don't update the position. In the if collision statement (line 112), you change appleY to 480, but you never change it again. Also, you don't change appleX. Instead, add these lines (and remove line 113): appleY = random.randint(start, end) appleX = random.randint(start, end) Now it should work fine, let me know if you have more problems.
14th Sep 2020, 7:41 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 5
David can you write the complete script in code playground and then send the link? It's hard to debug the way it is now.
14th Sep 2020, 7:16 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Aymane Boukrouh it works!! i cant thank you enough. ive been on this for a few hours. your the best!!
14th Sep 2020, 7:49 PM
David
David - avatar
+ 1
Hi Aymane Boukrouh thanks for your message. heres the link https://code.sololearn.com/c9S8Lg5c7NqW/#py
14th Sep 2020, 7:22 PM
David
David - avatar