用python写一个贪吃蛇
时间: 2024-01-06 13:06:03 浏览: 46
好的,下面是一个简单的贪吃蛇游戏的 Python 实现:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义窗口大小和标题
window_width = 640
window_height = 480
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇和食物大小
snake_block_size = 10
food_block_size = 10
# 定义时钟
clock = pygame.time.Clock()
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义函数,用于显示分数
def display_score(score):
score_text = font_style.render(f"Score: {score}", True, black)
game_display.blit(score_text, [0, 0])
# 定义函数,用于画贪吃蛇和食物
def draw_snake_and_food(snake_block_size, snake_list, food_block_size, food_position):
for block in snake_list:
pygame.draw.rect(game_display, black, [block[0], block[1], snake_block_size, snake_block_size])
pygame.draw.rect(game_display, red, [food_position[0], food_position[1], food_block_size, food_block_size])
# 定义函数,用于显示游戏结束信息
def game_over():
game_over_text = font_style.render("Game Over!", True, black)
game_display.blit(game_over_text, [window_width/2 - game_over_text.get_width()/2, window_height/2 - game_over_text.get_height()/2])
pygame.display.update()
pygame.time.delay(2000)
# 定义函数,用于运行游戏
def run_game():
# 初始化贪吃蛇位置
snake_list = []
snake_length = 1
x = window_width/2
y = window_height/2
x_change = 0
y_change = 0
# 初始化食物位置
food_position = [round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0, round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0]
# 初始化分数
score = 0
# 定义游戏是否结束的变量
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_LEFT:
x_change = -snake_block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = snake_block_size
y_change = 0
elif event.key == pygame.K_UP:
x_change = 0
y_change = -snake_block_size
elif event.key == pygame.K_DOWN:
x_change = 0
y_change = snake_block_size
# 移动贪吃蛇
x += x_change
y += y_change
# 判断是否吃到食物
if x == food_position[0] and y == food_position[1]:
food_position = [round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0, round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0]
snake_length += 1
score += 10
# 更新贪吃蛇列表
snake_head = []
snake_head.append(x)
snake_head.append(y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断是否撞墙或自己
for block in snake_list[:-1]:
if block == snake_head:
game_over = True
if x < 0 or x >= window_width or y < 0 or y >= window_height:
game_over = True
# 绘制游戏画面
game_display.fill(white)
draw_snake_and_food(snake_block_size, snake_list, food_block_size, food_position)
display_score(score)
pygame.display.update()
# 控制游戏速度
clock.tick(20)
# 显示游戏结束信息
game_over()
pygame.quit()
quit()
# 运行游戏
run_game()
```
这是一个比较简单的实现,如果需要更加完善的贪吃蛇游戏,可以自行添加更多特性和功能。
阅读全文