怎么用python写贪吃蛇
时间: 2023-07-08 18:43:33 浏览: 87
你可以使用 Python 中的 Pygame 模块来编写贪吃蛇游戏。以下是一个简单的贪吃蛇游戏示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口尺寸
window_size = (400, 400)
# 设置游戏窗口
screen = pygame.display.set_mode(window_size)
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的初始位置
snake_position = [100, 50]
# 定义贪吃蛇的初始长度
snake_body = [[100, 50], [90, 50], [80, 50]]
# 定义食物的初始位置
food_position = [random.randrange(1, 40) * 10, random.randrange(1, 40) * 10]
# 定义食物数量
food_count = 1
# 定义初始分数
score = 0
# 定义蛇的移动方向
direction = "RIGHT"
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义分数显示函数
def show_score(score):
score_text = font_style.render("Score: " + str(score), True, white)
screen.blit(score_text, [0, 0])
# 定义蛇的移动函数
def move_snake(direction, snake_position, snake_body):
if direction == "RIGHT":
snake_position[0] += 10
elif direction == "LEFT":
snake_position[0] -= 10
elif direction == "UP":
snake_position[1] -= 10
elif direction == "DOWN":
snake_position[1] += 10
snake_body.insert(0, list(snake_position))
# 定义游戏结束函数
def game_over():
message = font_style.render("Game Over!", True, white)
screen.blit(message, [150, 200])
# 开始游戏循环
game_over_flag = False
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
direction = "RIGHT"
elif event.key == pygame.K_LEFT:
direction = "LEFT"
elif event.key == pygame.K_UP:
direction = "UP"
elif event.key == pygame.K_DOWN:
direction = "DOWN"
# 绘制游戏背景
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, green, [food_position[0], food_position[1], 10, 10])
# 移动蛇
move_snake(direction, snake_position, snake_body)
# 绘制蛇
for position in snake_body:
pygame.draw.rect(screen, white, [position[0], position[1], 10, 10])
# 如果蛇吃到了食物
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
food_position = [random.randrange(1, 40) * 10, random.randrange(1, 40) * 10]
food_count += 1
score += 10
# 显示分数
show_score(score)
# 如果蛇碰到了边界
if snake_position[0] >= 400 or snake_position[0] < 0 or snake_position[1] >= 400 or snake_position[1] < 0:
game_over()
# 如果蛇碰到了自己
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
# 更新屏幕
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(20)
# 退出 Pygame
pygame.quit()
```
这只是一个简单的贪吃蛇游戏示例,你可以根据自己的需求进行修改和完善。
阅读全文