贪吃蛇python代码有成绩排行榜
时间: 2023-11-22 08:54:34 浏览: 112
python贪吃蛇完整的源代码资料.zip
以下是一个简单的贪吃蛇Python代码,包括一个成绩排行榜:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏界面尺寸
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 480
# 颜色定义
WHITE_COLOR = (255, 255, 255)
BLACK_COLOR = (0, 0, 0)
RED_COLOR = (255, 0, 0)
GREEN_COLOR = (0, 255, 0)
# 创建游戏界面
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
# 定义字体
font = pygame.font.SysFont('arial', 24)
# 定义贪吃蛇初始位置
snake_x = 100
snake_y = 100
snake_width = 10
snake_height = 10
snake_speed = 10
# 定义贪吃蛇移动方向
snake_direction = 'right'
# 定义食物初始位置
food_x = random.randint(0, SCREEN_WIDTH - snake_width)
food_y = random.randint(0, SCREEN_HEIGHT - snake_height)
food_width = 10
food_height = 10
# 定义分数
score = 0
# 定义成绩排行榜
high_scores = []
# 游戏循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
elif event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
# 移动贪吃蛇
if snake_direction == 'up':
snake_y -= snake_speed
elif snake_direction == 'down':
snake_y += snake_speed
elif snake_direction == 'left':
snake_x -= snake_speed
elif snake_direction == 'right':
snake_x += snake_speed
# 判断贪吃蛇是否吃到食物
if snake_x < food_x + food_width and snake_x + snake_width > food_x and snake_y < food_y + food_height and snake_y + snake_height > food_y:
food_x = random.randint(0, SCREEN_WIDTH - snake_width)
food_y = random.randint(0, SCREEN_HEIGHT - snake_height)
score += 10
# 绘制游戏界面
screen.fill(WHITE_COLOR)
pygame.draw.rect(screen, GREEN_COLOR, [food_x, food_y, food_width, food_height])
pygame.draw.rect(screen, BLACK_COLOR, [snake_x, snake_y, snake_width, snake_height])
# 绘制分数
score_text = font.render('Score: ' + str(score), True, BLACK_COLOR)
screen.blit(score_text, (10, 10))
# 更新游戏界面
pygame.display.update()
# 判断贪吃蛇是否触碰到边界或自己
if snake_x < 0 or snake_x > SCREEN_WIDTH - snake_width or snake_y < 0 or snake_y > SCREEN_HEIGHT - snake_height:
running = False
elif [snake_x, snake_y] in [[x, y] for x, y in high_scores]:
running = False
# 将当前分数添加到排行榜中
if not running:
high_scores.append([score, snake_x, snake_y])
high_scores.sort(reverse=True)
# 绘制成绩排行榜
for i, score in enumerate(high_scores):
score_text = font.render(str(i+1) + '. ' + str(score[0]), True, BLACK_COLOR)
screen.blit(score_text, (SCREEN_WIDTH - 100, 10 + i * 30))
# 退出游戏
pygame.quit()
```
在这个游戏中,成绩排行榜是一个二维列表,每个元素包含了玩家的分数以及玩家游戏结束时贪吃蛇头部的坐标。当游戏结束时,将当前分数添加到排行榜中并按分数从高到低排序,然后在游戏界面上绘制排行榜。
阅读全文