Untitled
unknown
plain_text
5 days ago
27 kB
2
Indexable
import pygame import time import random # Initialize pygame pygame.init() # Colors white = (255, 255, 255) black = (0, 0, 0) red = (213, 50, 80) green = (0, 255, 0) blue = (50, 153, 213) # Display size width = 600 height = 400 # Create window win = pygame.display.set_mode((width, height)) pygame.display.set_caption("Snake Game") # Snake block size block_size = 10 # Speed speed = 15 # Fonts font = pygame.font.SysFont("bahnschrift", 25) def message(msg, color, x, y): mesg = font.render(msg, True, color) win.blit(mesg, [x, y]) def gameLoop(): game_over = False game_close = False x = width / 2 y = height / 2 x_change = 0 y_change = 0 snake_body = [] length = 1 food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0 clock = pygame.time.Clock() while not game_over: while game_close: win.fill(black) message("Game Over! Press Q-Quit or C-Play Again", red, width / 6, height / 3) 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 if event.key == pygame.K_c: gameLoop() 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: x_change = -block_size y_change = 0 elif event.key == pygame.K_RIGHT: x_change = block_size y_change = 0 elif event.key == pygame.K_UP: y_change = -block_size x_change = 0 elif event.key == pygame.K_DOWN: y_change = block_size x_change = 0 if x >= width or x < 0 or y >= height or y < 0: game_close = True x += x_change y += y_change win.fill(black) pygame.draw.rect(win, green, [food_x, food_y, block_size, block_size]) snake_head = [] snake_head.append(x) snake_head.append(y) snake_body.append(snake_head) if len(snake_body) > length: del snake_body[0] for block in snake_body[:-1]: if block == snake_head: game_close = True for block in snake_body: pygame.draw.rect(win, blue, [block[0], block[1], block_size, block_size]) pygame.display.update() if x == food_x and y == food_y: food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0 length += 1 clock.tick(speed) pygame.quit() quit() gameLoop()
Editor is loading...
Leave a Comment