如何用python代码实现贪吃蛇小游戏
时间: 2023-07-27 10:24:03 浏览: 44
100行python代码完成的贪吃蛇游戏,简单方便快捷,下载即可运行,可做毕业设计
可以使用Python的Pygame库来实现贪吃蛇小游戏。
以下是示例代码:
```python
import pygame
import random
# 定义常量
WIDTH = 640
HEIGHT = 480
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLOCK_SIZE = 20
# 初始化Pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义蛇类
class Snake:
def __init__(self):
self.body = [(3, 1), (2, 1), (1, 1)]
self.direction = 'right'
def move(self):
head = self.body[0]
if self.direction == 'right':
new_head = (head[0] + 1, head[1])
elif self.direction == 'left':
new_head = (head[0] - 1, head[1])
elif self.direction == 'up':
new_head = (head[0], head[1] - 1)
elif self.direction == 'down':
new_head = (head[0], head[1] + 1)
self.body.insert(0, new_head)
self.body.pop()
def draw(self):
for block in self.body:
rect = pygame.Rect(block[0] * BLOCK_SIZE, block[1] * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(screen, GREEN, rect)
def grow(self):
tail = self.body[-1]
if self.direction == 'right':
new_tail = (tail[0] + 1, tail[1])
elif self.direction == 'left':
new_tail = (tail[0] - 1, tail[1])
elif self.direction == 'up':
new_tail = (tail[0], tail[1] - 1)
elif self.direction == 'down':
new_tail = (tail[0], tail[1] + 1)
self.body.append(new_tail)
# 定义食物类
class Food:
def __init__(self):
self.position = (0, 0)
self.randomize_position()
def draw(self):
rect = pygame.Rect(self.position[0] * BLOCK_SIZE, self.position[1] * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(screen, RED, rect)
def randomize_position(self):
x = random.randint(0, WIDTH // BLOCK_SIZE - 1)
y = random.randint(0, HEIGHT // BLOCK_SIZE - 1)
self.position = (x, y)
# 创建蛇和食物
snake = Snake()
food = Food()
# 定义游戏循环
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.direction = 'right'
elif event.key == pygame.K_LEFT:
snake.direction = 'left'
elif event.key == pygame.K_UP:
snake.direction = 'up'
elif event.key == pygame.K_DOWN:
snake.direction = 'down'
# 移动蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == food.position:
snake.grow()
food.randomize_position()
# 判断是否撞到墙或自己
head = snake.body[0]
if head[0] < 0 or head[0] >= WIDTH // BLOCK_SIZE or head[1] < 0 or head[1] >= HEIGHT // BLOCK_SIZE:
done = True
for block in snake.body[1:]:
if head == block:
done = True
# 绘制游戏界面
screen.fill(WHITE)
snake.draw()
food.draw()
pygame.display.flip()
# 控制游戏速度
clock.tick(10)
# 退出游戏
pygame.quit()
```
运行程序后,按方向键控制蛇的移动,吃到食物会增长身体,撞到墙或自己会游戏结束。注意,本示例中的游戏界面是基于Pygame实现的,如果需要在其他环境中运行,需要根据相应的框架进行调整。
阅读全文