Let 's use chatGPT now to build this game.
1. Initialization and Constants
import pygame
import sys
import random
pygame.init()
WIDTH, HEIGHT = 600, 400
GRID_SIZE = 20
FPS = 10
SILVER = (192, 192, 192)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
pygame.init()
: Initializes the Pygame library.WIDTH
andHEIGHT
: Define the dimensions of the game window.GRID_SIZE
: Specifies the size of each grid cell.FPS
: Sets the frames per second for the game loop.SILVER
,WHITE
,RED
, andBLUE
: Define color constants using RGB values.
2. Snake Class
class Snake:
def __init__(self):
self.length = 1
self.positions = [((WIDTH // 2), (HEIGHT // 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = RED
__init__
: Initializes the Snake object with default values.self.length
: Tracks the length of the snake.self.positions
: Stores the positions of the snake's body segments.self.direction
: Represents the current direction of the snake.self.color
: Sets the colour of the snake.
3. Fruit Class
class Fruit:
def __init__(self):
self.position = (0, 0)
self.color = BLUE
self.randomize_position()
__init__
: Initializes the Fruit object with default values.self.position
: Stores the position of the fruit on the grid.self.color
: Sets the colour of the fruit.
4. Directions and Grid Drawing
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def draw_grid(surface):
for y in range(0, HEIGHT, GRID_SIZE):
for x in range(0, WIDTH, GRID_SIZE):
rect = pygame.Rect(x, y, GRID_SIZE, GRID_SIZE)
pygame.draw.rect(surface, SILVER, rect)
UP
,DOWN
,LEFT
, andRIGHT
: Represent directional movements.draw_grid
: Draws the grid on the game surface using rectangles.
5. Main Game Loop
def main():
# ... (snip)
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.direction = UP
elif event.key == pygame.K_DOWN:
snake.direction = DOWN
elif event.key == pygame.K_LEFT:
snake.direction = LEFT
elif event.key == pygame.K_RIGHT:
snake.direction = RIGHT
snake.update()
if snake.get_head_position() == fruit.position:
snake.length += 1
fruit.randomize_position()
score += 1
# ... (snip)
if __name__ == "__main__":
main()
main
: The main game loop where user input is handled, and the game state is updated.The loop processes events, such as quitting the game or changing the snake's direction with arrow keys.
snake.update
: Updates the snake's position based on its current direction.Check if the snake has eaten the fruit, update the score, and randomize the fruit's position.
Calls the rendering functions to display the game elements.
The game continues to run in this loop until the user closes the window.
This code provides a basic implementation of the Snake game using the Pygame library.
The Complete Code
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 600, 400
GRID_SIZE = 20
FPS = 10
# Colors
SILVER = (192, 192, 192)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# Snake class
class Snake:
def __init__(self):
self.length = 1
self.positions = [((WIDTH // 2), (HEIGHT // 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = RED
def get_head_position(self):
return self.positions[0]
def update(self):
cur = self.get_head_position()
x, y = self.direction
new = (((cur[0] + (x * GRID_SIZE)) % WIDTH), (cur[1] + (y * GRID_SIZE)) % HEIGHT)
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [((WIDTH // 2), (HEIGHT // 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
def render(self, surface):
for p in self.positions:
pygame.draw.circle(surface, self.color, (p[0] + GRID_SIZE // 2, p[1] + GRID_SIZE // 2), GRID_SIZE // 2)
# Fruit class
class Fruit:
def __init__(self):
self.position = (0, 0)
self.color = WHITE
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, (WIDTH // GRID_SIZE) - 1) * GRID_SIZE,
random.randint(0, (HEIGHT // GRID_SIZE) - 1) * GRID_SIZE)
def render(self, surface):
pygame.draw.circle(surface, self.color, (self.position[0] + GRID_SIZE // 2, self.position[1] + GRID_SIZE // 2), GRID_SIZE // 2)
# Directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def draw_grid(surface):
for y in range(0, HEIGHT, GRID_SIZE):
for x in range(0, WIDTH, GRID_SIZE):
rect = pygame.Rect(x, y, GRID_SIZE, GRID_SIZE)
pygame.draw.rect(surface, SILVER, rect)
def main():
clock = pygame.time.Clock()
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
surface = pygame.Surface(screen.get_size())
surface = surface.convert()
snake = Snake()
fruit = Fruit()
# Fonts
font = pygame.font.SysFont("Arial", 24)
score = 0
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.direction = UP
elif event.key == pygame.K_DOWN:
snake.direction = DOWN
elif event.key == pygame.K_LEFT:
snake.direction = LEFT
elif event.key == pygame.K_RIGHT:
snake.direction = RIGHT
snake.update()
if snake.get_head_position() == fruit.position:
snake.length += 1
fruit.randomize_position()
score += 1
surface.fill(SILVER)
draw_grid(surface)
snake.render(surface)
fruit.render(surface)
# Display score
score_text = font.render("Score: {}".format(score), True, WHITE)
surface.blit(score_text, (10, 10))
screen.blit(surface, (0, 0))
pygame.display.update()
clock.tick(FPS)
if __name__ == "__main__":
main()