Untitled
unknown
plain_text
a month ago
3.8 kB
4
Indexable
import pygame import random pygame.init() # Colors WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLACK = (0, 0, 0) # Display WIDTH, HEIGHT = 600, 400 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Snake Game') # Snake and Food snake_block = 10 snake_speed = 15 # Fonts font_style = pygame.font.SysFont("bahnschrift", 25) # Clock clock = pygame.time.Clock() # Function to display the score def your_score(score): value = font_style.render(f"Score: {score}", True, BLACK) screen.blit(value, [0, 0]) # Function to draw the snake def draw_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block, snake_block]) # Main Game Loop def gameLoop(): game_over = False game_close = False x1 = WIDTH / 2 y1 = HEIGHT / 2 x1_change = 0 y1_change = 0 snake_List = [] Length_of_snake = 1 # Randomly place food foodx = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0 while not game_over: while game_close: screen.fill(WHITE) message = font_style.render("You Lost! Press Q-Quit or C-Play Again", True, RED) screen.blit(message, [WIDTH / 6, HEIGHT / 3]) your_score(Length_of_snake - 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True game_close = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False if event.key == pygame.K_c: gameLoop() 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: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_RIGHT: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_UP: y1_change = -snake_block x1_change = 0 elif event.key == pygame.K_DOWN: y1_change = snake_block x1_change = 0 # Check if snake hits the wall if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0: game_close = True x1 += x1_change y1 += y1_change screen.fill(WHITE) # Draw food pygame.draw.rect(screen, RED, [foodx, foody, snake_block, snake_block]) # Update snake snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: del snake_List[0] # Check if snake collides with itself for x in snake_List[:-1]: if x == snake_Head: game_close = True draw_snake(snake_block, snake_List) your_score(Length_of_snake - 1) pygame.display.update() # Check if snake eats food if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0 Length_of_snake += 1 clock.tick(snake_speed) pygame.quit() quit() # Start the game gameLoop()
Editor is loading...
Leave a Comment