codebasics / python_projects

Repository for python projects
136 stars 322 forks source link

Delaying in eating time of snake #15

Open Niveditasri opened 10 months ago

Niveditasri commented 10 months ago

This game as provided shows delaying in eating time of the apple. The apple disappears lately after been eaten by the snake. To resolve the issue the following code might help.

import pygame import sys import random

Initialize Pygame

pygame.init()

Constants

WIDTH, HEIGHT = 600, 400 GRID_SIZE = 20 SNAKE_SIZE = 20 FPS = 10

Colors

WHITE = (255, 255, 255) RED = (255, 0, 0)

Snake class

class Snake: def init(self): self.body = [(100, 100), (90, 100), (80, 100)] self.direction = (1, 0) # Initial direction (right)

def move(self, food):
    # Check for collisions with the food
    if self.body[0] == food.position:
        self.body.insert(0, food.position)
        food.spawn()
    else:
        # Move the snake
        self.body.pop()
        new_head = (self.body[0][0] + self.direction[0] * SNAKE_SIZE,
                    self.body[0][1] + self.direction[1] * SNAKE_SIZE)
        self.body.insert(0, new_head)

def change_direction(self, new_direction):
    # Prevent the snake from reversing direction
    if (new_direction[0] * -1, new_direction[1] * -1) != self.direction:
        self.direction = new_direction

def draw(self, surface):
    for segment in self.body:
        pygame.draw.rect(surface, WHITE, (segment[0], segment[1], SNAKE_SIZE, SNAKE_SIZE))

Food class

class Food: def init(self): self.position = (0, 0) self.spawn()

def spawn(self):
    # Spawn food at a random position
    x = random.randint(0, (WIDTH - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
    y = random.randint(0, (HEIGHT - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
    self.position = (x, y)

def draw(self, surface):
    pygame.draw.rect(surface, RED, (self.position[0], self.position[1], SNAKE_SIZE, SNAKE_SIZE))

Initialize game window

screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Snake Game') clock = pygame.time.Clock()

snake = Snake() food = Food()

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_UP: snake.change_direction((0, -1)) elif event.key == pygame.K_DOWN: snake.change_direction((0, 1)) elif event.key == pygame.K_LEFT: snake.change_direction((-1, 0)) elif event.key == pygame.K_RIGHT: snake.change_direction((1, 0))

snake.move(food)

# Draw everything
screen.fill((0, 0, 0))
snake.draw(screen)
food.draw(screen)

pygame.display.flip()
clock.tick(FPS)
anushkadhole commented 1 month ago

hi this is great!