Snake
unknown
python
5 months ago
3.8 kB
2
Indexable
import pygame import random import time # Initialize pygame pygame.init() # Set up display WIDTH, HEIGHT = 600, 400 win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Snake Game") # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Set up game clock clock = pygame.time.Clock() SNAKE_SPEED = 15 # Define snake and food settings snake_block = 10 snake_speed = 15 # Font settings font_style = pygame.font.SysFont(None, 50) def display_score(score): value = font_style.render("Score: " + str(score), True, WHITE) win.blit(value, [0, 0]) def game_over_message(): game_over_text = font_style.render("Game Over!", True, RED) win.blit(game_over_text, [WIDTH // 4, HEIGHT // 4]) pygame.display.update() time.sleep(2) def game_loop(): game_over = False game_close = False # Initial position and movement of the snake x, y = WIDTH // 2, HEIGHT // 2 x_change, y_change = 0, 0 snake_list = [] snake_length = 1 # Generate initial food position food_x = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0 food_y = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0 while not game_over: while game_close: win.fill(BLACK) game_over_message() display_score(snake_length - 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False elif event.key == pygame.K_c: game_loop() for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and x_change == 0: x_change = -snake_block y_change = 0 elif event.key == pygame.K_RIGHT and x_change == 0: x_change = snake_block y_change = 0 elif event.key == pygame.K_UP and y_change == 0: y_change = -snake_block x_change = 0 elif event.key == pygame.K_DOWN and y_change == 0: y_change = snake_block x_change = 0 # Update snake's position x += x_change y += y_change # Check for boundary collision if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0: game_close = True win.fill(BLACK) pygame.draw.rect(win, GREEN, [food_x, food_y, snake_block, snake_block]) snake_head = [x, y] snake_list.append(snake_head) if len(snake_list) > snake_length: del snake_list[0] # Check for collision with itself for block in snake_list[:-1]: if block == snake_head: game_close = True # Draw snake for block in snake_list: pygame.draw.rect(win, WHITE, [block[0], block[1], snake_block, snake_block]) display_score(snake_length - 1) pygame.display.update() # Check for collision with food if x == food_x and y == food_y: food_x = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0 food_y = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0 snake_length += 1 clock.tick(snake_speed) pygame.quit() quit() game_loop()
Editor is loading...
Leave a Comment