使用Python写一个贪吃蛇游戏,包括游戏界面
时间: 2023-07-20 18:17:51 浏览: 63
好的,我可以给你提供一个简单的贪吃蛇游戏的代码示例,你可以在此基础上进行修改和完善。
```python
import pygame
import random
# 定义常量
WIDTH = 640
HEIGHT = 480
BLOCK_SIZE = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化 pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 创建时钟
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(8, 8), (7, 8), (6, 8)]
self.direction = 'right'
self.score = 0
def move(self):
head = self.body[0]
if self.direction == 'up':
new_head = (head[0], head[1] - 1)
elif self.direction == 'down':
new_head = (head[0], head[1] + 1)
elif self.direction == 'left':
new_head = (head[0] - 1, head[1])
elif self.direction == 'right':
new_head = (head[0] + 1, head[1])
self.body.insert(0, new_head)
if new_head == food.position:
self.score += 1
food.spawn()
else:
self.body.pop()
def change_direction(self, direction):
if direction == 'up' and self.direction != 'down':
self.direction = 'up'
elif direction == 'down' and self.direction != 'up':
self.direction = 'down'
elif direction == 'left' and self.direction != 'right':
self.direction = 'left'
elif direction == 'right' and self.direction != 'left':
self.direction = 'right'
def is_dead(self):
head = self.body[0]
if head[0] < 0 or head[0] >= WIDTH // BLOCK_SIZE:
return True
if head[1] < 0 or head[1] >= HEIGHT // BLOCK_SIZE:
return True
for i in range(1, len(self.body)):
if head == self.body[i]:
return True
return False
# 定义食物类
class Food:
def __init__(self):
self.position = (0, 0)
self.color = RED
self.spawn()
def spawn(self):
x = random.randint(0, WIDTH // BLOCK_SIZE - 1)
y = random.randint(0, HEIGHT // BLOCK_SIZE - 1)
self.position = (x, y)
def draw(self):
x = self.position[0] * BLOCK_SIZE
y = self.position[1] * BLOCK_SIZE
pygame.draw.rect(screen, self.color, (x, y, BLOCK_SIZE, BLOCK_SIZE))
# 创建贪吃蛇和食物
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction('up')
elif event.key == pygame.K_DOWN:
snake.change_direction('down')
elif event.key == pygame.K_LEFT:
snake.change_direction('left')
elif event.key == pygame.K_RIGHT:
snake.change_direction('right')
# 移动贪吃蛇
snake.move()
# 判断贪吃蛇是否死亡
if snake.is_dead():
pygame.quit()
exit()
# 绘制游戏界面
screen.fill(BLACK)
snake_color = GREEN
for i, block in enumerate(snake.body):
x = block[0] * BLOCK_SIZE
y = block[1] * BLOCK_SIZE
if i == 0:
pygame.draw.rect(screen, BLUE, (x, y, BLOCK_SIZE, BLOCK_SIZE))
else:
pygame.draw.rect(screen, snake_color, (x, y, BLOCK_SIZE, BLOCK_SIZE))
snake_color = (snake_color[0] - 10, snake_color[1] - 10, snake_color[2] - 10)
food.draw()
pygame.display.update()
# 设置帧率
clock.tick(10)
```
这个代码示例包括了游戏界面和基本的游戏逻辑,你可以在此基础上进行修改和完善,实现更丰富的游戏玩法和功能。
阅读全文