用代码写一个贪吃蛇游戏小程序
时间: 2023-05-23 11:03:54 浏览: 115
好的,以下是一个简单的贪吃蛇游戏小程序的代码,使用 Python 语言编写:
```python
import pygame
import random
WIDTH = 500
HEIGHT = 500
BLOCK_SIZE = 20
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.body = [(WIDTH/2, HEIGHT/2)]
self.direction = (1, 0)
self.grow = False
def move(self):
head = self.body[0]
dx, dy = self.direction
new_head = (head[0] + dx*BLOCK_SIZE, head[1] + dy*BLOCK_SIZE)
self.body.insert(0, new_head)
if not self.grow:
self.body.pop()
else:
self.grow = False
def grow_snake(self):
self.grow = True
def draw(self, screen):
for block in self.body:
pygame.draw.rect(screen, (0, 255, 0), (block[0], block[1], BLOCK_SIZE, BLOCK_SIZE))
class Food:
def __init__(self):
self.pos = (random.randint(0, WIDTH-BLOCK_SIZE), random.randint(0, HEIGHT-BLOCK_SIZE))
def draw(self, screen):
pygame.draw.rect(screen, (255, 0, 0), (self.pos[0], self.pos[1], BLOCK_SIZE, BLOCK_SIZE))
snake = Snake()
food = Food()
def game_loop():
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake.direction != (0, 1):
snake.direction = (0, -1)
elif event.key == pygame.K_DOWN and snake.direction != (0, -1):
snake.direction = (0, 1)
elif event.key == pygame.K_LEFT and snake.direction != (1, 0):
snake.direction = (-1, 0)
elif event.key == pygame.K_RIGHT and snake.direction != (-1, 0):
snake.direction = (1, 0)
# move and grow snake
snake.move()
if snake.body[0] == food.pos:
snake.grow_snake()
food = Food()
# check for game over
head = snake.body[0]
if head[0] < 0 or head[0] >= WIDTH or head[1] < 0 or head[1] >= HEIGHT:
game_over = True
for block in snake.body[1:]:
if head == block:
game_over = True
# draw everything
screen.fill((0, 0, 0))
snake.draw(screen)
food.draw(screen)
pygame.display.flip()
# update clock
clock.tick(10)
game_loop()
pygame.quit()
```
请注意,这只是一个简单的贪吃蛇游戏小程序,它可能不够完善,需要根据实际需求来完善。如果您有任何问题或意见,请随时提出。
阅读全文