2

I'm new to python and only now the basics, I'm trying to make a snake game but I can't seem to figure out how to make my snake grow 1 extra square each time it eats an apple. My reasoning is that I keep a list of all the old positions but only show the last one on the screen, and each time the snakes eats another apple it shows 1 extra old positions making the snake 1 square longer. This is my code:

import pygame
from random import randint

WIDTH = 400
HEIGHT = 300
dis = pygame.display.set_mode((WIDTH,HEIGHT))
white = (255,255,255)
BACKGROUND = white
blue = [0,0,255]
red = [255,0,0]

class Snake: 
def __init__(self):
  self.image = pygame.image.load("snake.bmp")
  self.rect = self.image.get_rect()
  self.position = (10,10)
  self.direction = [0,0]
  self.positionslist = [self.position]
  self.length = 1
  pygame.display.set_caption('Snake ')

  
def draw_snake(self,screen):
    screen.blit(self.image, self.position)
    


def update(self):
  self.position = (self.position[0] + self.direction[0],self.position[1] + self.direction[1])
  self.rect = (self.position[0],self.position[1],5, 5 )
  self.positionslist.append(self.position)
  if self.position[0]< 0 :
    self.position = (WIDTH,self.position[1]) 
  elif self.position[0] > WIDTH:
    self.position = (0,self.position[1])
  elif self.position[1] > HEIGHT:
    self.position = (self.position[0],0)
  elif self.position[1] < 0 :
    self.position = (self.position[0],HEIGHT)





class Food:
def __init__(self):
self.image = pygame.image.load("appel.png")
self.rect = self.image.get_rect()

apple_width = -self.image.get_width()
apple_height = -self.image.get_height()
self.position = (randint(0,WIDTH+apple_width-50),randint(0,HEIGHT+apple_height-50))
self.rect.x = self.position[0]
self.rect.y = self.position[1]

def draw_appel(self,screen):
screen.blit(self.image, self.position)

def eat_appel (self, snake):

if self.rect.colliderect(snake.rect) == True:

  self.position = (randint(0,WIDTH),randint(0,HEIGHT))
  self.rect.x = self.position[0]
  self.rect.y = self.position[1]
  snake.length += 1



def main():
game_over = False 
while not game_over:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
snake = Snake()
food = Food()

while True:
  screen.fill(BACKGROUND)
  font = pygame.font.Font('freesansbold.ttf', 12)
  text = font.render(str(snake.length), True, red, white)
  textRect = text.get_rect()
  textRect.center = (387, 292)
  screen.blit(text,textRect)
  snake.update()
  
  #snake.update_list()
  snake.draw_snake(screen)
  food.draw_appel(screen)
  food.eat_appel(snake)
  pygame.display.flip()
  
  clock.tick(60)
  

  

  for event in pygame.event.get():
    if event.type == pygame.MOUSEBUTTONDOWN:
      snake.direction = [0,1]
    if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_RIGHT:
         snake.direction = [1,0] 
      if event.key == pygame.K_LEFT:
        snake.direction = [-1,0] 
      if event.key == pygame.K_UP:
        snake.direction = [0,-1]
      if event.key == pygame.K_DOWN:
       snake.direction = [0,1]




 if __name__ == "__main__":
   main()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

2

This can have multiple reasons. Firstly, I saw you tried to increase the length of the snake by typing snake.length += 1, which may work (probably won't because the module pygame allows the snake to hover around, but not like the loop or conditional statements). One of my tips would be, to increase the length of the snake by using the idea of adding the score with your present snake.length every time (because once your score is 1 by eating an apple, your snake.length would be 2. And it increases with the score). This is my code (a few modifications might be needed):

import pygame
import time
import random

pygame.init()

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 165, 0)

width, height = 600, 400

game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Mania")

clock = pygame.time.Clock()

snake_size = 10
snake_speed = 15

message_font = pygame.font.SysFont('ubuntu', 30)
score_font = pygame.font.SysFont('ubuntu', 25)

def print_score(score):
    text = score_font.render("Score: " + str(score), True, orange)
    game_display.blit(text, [0,0])

def draw_snake(snake_size, snake_pixels):
    for pixel in snake_pixels:
        pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])


def run_game():

    game_over = False
    game_close = False

    x = width / 2
    y = height / 2

    x_speed = 0
    y_speed = 0

    snake_pixels = []
    snake_length = 1

    target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
    target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0

    while not game_over:

        while game_close:
            game_display.fill(black)
            game_over_message = message_font.render("Game Over!", True, red)
            game_display.blit(game_over_message, [width / 3, height / 3])
            print_score(snake_length - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_1:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_2:
                        run_game()
                if event.type == pygame.QUIT:
                    game_over = True
                    game_close = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_speed = -snake_size
                    y_speed = 0
                if event.key == pygame.K_RIGHT:
                    x_speed = snake_size
                    y_speed = 0
                if event.key == pygame.K_UP:
                    x_speed = 0
                    y_speed = -snake_size
                if event.key == pygame.K_DOWN:
                    x_speed = 0
                    y_speed = snake_size

        if x >= width or x < 0 or y >= height or y < 0:
            game_close = True

        x += x_speed
        y += y_speed

        game_display.fill(black)
        pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])
        snake_pixels.append([x, y])

        if len(snake_pixels) > snake_length:
            del snake_pixels[0]

        for pixel in snake_pixels[:-1]:
            if pixel == [x, y]:
                game_close = True

        draw_snake(snake_size, snake_pixels)
        print_score(snake_length - 1)

        pygame.display.update()

        if x == target_x and y == target_y:
            target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
            target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
            snake_length += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()

run_game()
Aizen
  • 21
  • 2