what i did today was make snake
import pygame
import random
import sys
# Initialize pygame
pygame.init()
# Game settings
WIDTH, HEIGHT = 600, 400
BLOCK_SIZE = 20
FPS = 10
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
font = pygame.font.SysFont("arial", 24)
def draw_text(text, color, x, y):
surface = font.render(text, True, color)
rect = surface.get_rect(center=(x, y))
screen.blit(surface, rect)
def main():
# Snake initial state
snake = [(WIDTH // 2, HEIGHT // 2)]
direction = (BLOCK_SIZE, 0) # moving right
score = 0
# Food
def random_food():
return (
random.randrange(0, WIDTH, BLOCK_SIZE),
random.randrange(0, HEIGHT, BLOCK_SIZE),
)
food = random_food()
running = True
while running:
clock.tick(FPS)
# Handle events
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 and direction[1] == 0:
direction = (0, -BLOCK_SIZE)
elif event.key == pygame.K_DOWN and direction[1] == 0:
direction = (0, BLOCK_SIZE)
elif event.key == pygame.K_LEFT and direction[0] == 0:
direction = (-BLOCK_SIZE, 0)
elif event.key == pygame.K_RIGHT and direction[0] == 0:
direction = (BLOCK_SIZE, 0)
# Move snake
head_x, head_y = snake[0]
new_head = (head_x + direction[0], head_y + direction[1])
# Check collisions with walls
if (
new_head[0] < 0
or new_head[0] >= WIDTH
or new_head[1] < 0
or new_head[1] >= HEIGHT
):
running = False
# Check collisions with self
if new_head in snake:
running = False
snake.insert(0, new_head)
# Check food
if new_head == food:
score += 1
food = random_food()
else:
snake.pop()
# Draw
screen.fill(BLACK)
# Draw snake
for x, y in snake:
pygame.draw.rect(screen, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE))
# Draw food
pygame.draw.rect(screen, RED, (food[0], food[1], BLOCK_SIZE, BLOCK_SIZE))
# Draw score
draw_text(f"Score: {score}", WHITE, WIDTH // 2, 20)
pygame.display.flip()
# Game over screen
screen.fill(BLACK)
draw_text("Game Over", RED, WIDTH // 2, HEIGHT // 2 - 20)
draw_text(f"Final Score: {score}", WHITE, WIDTH // 2, HEIGHT // 2 + 20)
pygame.display.flip()
pygame.time.wait(2000)
if __name__ == "__main__":
main()
you will have to pip install pygame for it to work but its pretty fun
Leave a Reply