Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
Here is a simple implementation of the classic Snake game in Python using the Pygame library. This code will create a window with a snake that moves in a grid, eating apples and growing in length.
1import pygame
2import random
3import time
4
5# Initialize Pygame
6pygame.init()
7
8# Set the dimensions of the window
9width, height = 640, 480
10screen = pygame.display.set_mode((width, height))
11pygame.display.set_caption('Snake Game')
12
13# Define colors
14white = (255, 255, 255)
15black = (0, 0, 0)
16red = (255, 0, 0)
17green = (0, 255, 0)
18
19# Define the snake
20snake_pos = [20, 20]
21snake_dir = [1, 0]
22snake_size = 16
23snake_length = 1
24
25# Define the apple
26apple_pos = [random.randint(20, 300), randomative(20, 300)
27apple_size = 16
28
29# Define the clock
30clock = pygame.time.Clock()
31
32# Game loop
33running = True
34while running:
35 # Handle events
36 for event in pygame.event.get():
37 if event.type == pygame.QUIT:
38 running = False
39
40 # Move the snake
41 new_pos = [snake_pos[0] + snake_dir[0], snake_pos[1] + snake_dir[1]]
42 if new_pos[0] < 0 or new_pos[0] > width - snake_size:
43 snake_dir[0] *= -1
44 if new_pos[1] < 0 or new_pos[1] > height - snake_size:
45 snake_dir[1] *= -1
46 snake_pos[0] = new_pos[0]
47 snake_pos[1] = new_pos[1]
48
49 # Check for apple collision
50 if snake_pos[0] == apple_pos[0] and snake_pos[1] == apple_pos[1]:
51 apple_pos = [random.randint(20, 300), random.randint(20, 300)]
52 snake_length += 1
53
54 # Draw the screen
55 screen.fill(white)
56 pygame.draw.rect(screen, red, [apple_pos[0], apple_pos[1], apple_size, apple_size])
57 for i in range(snake_length):
58 pygame.draw.rect(screen, green, [snake_pos[0] - i * snake_size, snake_pos[1], snake_size, snake_size])
59 pygame.display.flip()
60
61 # Control the frame rate
62 clock.tick(10)
63
64pygame.quit()
This code will create a window with a snake that moves in a grid, eating apples and growing in length. The snake will bounce off the walls of the window. To play the game, simply run the code and use the arrow keys to control the snake.<|endoftext|>
This mistral model was trained 2x faster with
Unsloth and Huggingface's TRL library.