Reputation: 31
This is my first post! I am trying to make a snake clone in Pygame, but when my snake touches the apple, it won't teleport to another place. Here's my code:
import pygame
import time
import random
pygame.init()
wh = (255,255,255) #white
bk = (0,0,0) #black
ylw = (255,255,0) #yellow
prpl = (127,0,127) #purple
snakeXChange = 0
snakeYChange = 0
dWidth = 800
dHeight = 600
clock = pygame.time.Clock()
fps = 25
blockSize = 15
appleX = round(random.randrange(0, dWidth - blockSize)/ 10.0)* 10.0
appleY = round(random.randrange(0, dHeight - blockSize) / 10.0)* 10.0
snakeX = dWidth / 2
snakeY = dHeight / 2
font = pygame.font.SysFont(None, 25)
def message(msg, color):
screenText = font.render(msg, True, color)
gameDisplay.blit(screenText, [dWidth / 2, dHeight / 2])
gameDisplay = pygame.display.set_mode((dWidth,dHeight))
pygame.display.set_caption('Snek') #shoutout to Hopson
gameExit = False
gameOver = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snakeXChange = -blockSize
snakeYChange = 0
if event.key == pygame.K_RIGHT:
snakeXChange = blockSize
snakeYChange = 0
if event.key == pygame.K_UP:
snakeYChange = -blockSize
snakeXChange = 0
if event.key == pygame.K_DOWN:
snakeYChange = blockSize
snakeXChange = 0
snakeX += snakeXChange
snakeY += snakeYChange
gameDisplay.fill(prpl)
pygame.draw.rect(gameDisplay, wh, [snakeX,snakeY,blockSize,blockSize]) #snake
pygame.draw.rect(gameDisplay, ylw, [appleX,appleY,blockSize,blockSize]) #apple
if snakeX == appleX and snakeY == appleY:
appleX = round(random.randrange(0, dWidth - blockSize)/ 10.0)* 10.0
appleY = round(random.randrange(0, dHeight - blockSize) / 10.0)* 10.0
clock.tick(fps)
pygame.display.update()
message("GAME OVER NIBBA", ylw)
pygame.display.update() #updates the display
time.sleep(5)
pygame.quit()
quit()
Original source: https://paste.ee/p/eSimt
I am following theNewBoston's tutorials as a reference.
Cheers
SalmonSan
Upvotes: 3
Views: 146
Reputation: 20478
You're rounding the appleX
and appleY
coordinates to the nearest multiple of 10, but move in steps of 15 px, and that means it can happen that the snake isn't able to touch the apple. For example the appleX
could be 410 and the snake starts at 400, so it would never be able to reach the apple.
Just round all positions to the nearest multiple of 15 (the blockSize
and speed):
appleX = round(random.randrange(0, dWidth - blockSize) / 15.0) * 15.0
appleY = round(random.randrange(0, dHeight - blockSize) / 15.0) * 15.0
snakeX = round(dWidth / 2. / 15.) * 15
snakeY = round(dHeight / 2. / 15.) * 15
You could also just pass 15
as the step
argument to random.randrange
to get a random multiple of 15.
appleX = random.randrange(0, dWidth-blockSize, 15)
It would also be possible to use pygame.Rect
s for the collision detection and to store the coordinates.
Upvotes: 3