用python语言写一个贪吃蛇代码
时间: 2023-05-24 07:01:46 浏览: 88
python 贪吃蛇代码
5星 · 资源好评率100%
好的,以下是用Python语言写一个简单贪吃蛇游戏的代码:
```python
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕宽高,以及块的大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLOCK_SIZE = 20
# 初始化游戏
pygame.init()
# 设置屏幕
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置标题
pygame.display.set_caption('贪吃蛇')
# 设置时钟
clock = pygame.time.Clock()
# 定义字体
font = pygame.font.Font(None, 25)
# 定义函数,随机生成食物的位置
def create_food():
food = [random.randrange(1, (SCREEN_WIDTH // BLOCK_SIZE)) * BLOCK_SIZE,
random.randrange(1, (SCREEN_HEIGHT // BLOCK_SIZE)) * BLOCK_SIZE]
return food
# 定义函数,贪吃蛇的移动
def move_snake(move, snake):
# 判断蛇前进方向
if move == 'RIGHT':
X = 1
Y = 0
elif move == 'LEFT':
X = -1
Y = 0
elif move == 'UP':
X = 0
Y = -1
elif move == 'DOWN':
X = 0
Y = 1
# 获取蛇头坐标
head = snake[0].copy()
# 根据前进方向移动蛇头坐标
head[0] += X * BLOCK_SIZE
head[1] += Y * BLOCK_SIZE
# 将蛇头坐标加入蛇列表的头部
snake.insert(0, head)
# 如果吃到了食物,生成新的食物,蛇长度加1
if snake[0] == food:
food = create_food()
else:
snake.pop()
return snake, food
# 设置初始移动方向
move = 'RIGHT'
# 定义初始蛇的位置
snake = [[0, 0], [BLOCK_SIZE, 0], [BLOCK_SIZE * 2, 0]]
# 随机生成初始食物的位置
food = create_food()
# 设置游戏结束和胜利的标识
game_over = False
game_win = False
# 游戏循环
while not game_over:
# 设置标题
pygame.display.set_caption('贪吃蛇')
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and move != 'LEFT':
move = 'RIGHT'
elif event.key == pygame.K_LEFT and move != 'RIGHT':
move = 'LEFT'
elif event.key == pygame.K_UP and move != 'DOWN':
move = 'UP'
elif event.key == pygame.K_DOWN and move != 'UP':
move = 'DOWN'
# 移动贪吃蛇
snake, food = move_snake(move, snake)
# 判断蛇是否撞到边界
if snake[0][0] < 0 or snake[0][0] >= SCREEN_WIDTH or snake[0][1] < 0 or snake[0][1] >= SCREEN_HEIGHT:
game_over = True
# 判断蛇是否撞到自身
for block in snake[1:]:
if snake[0] == block:
game_over = True
# 绘制屏幕
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, GREEN, [food[0], food[1], BLOCK_SIZE, BLOCK_SIZE])
# 绘制蛇
for block in snake:
pygame.draw.rect(screen, WHITE, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])
# 判断游戏是否获胜,获胜条件为蛇的长度达到50
if len(snake) == 50:
game_win = True
game_over = True
# 显示分数
score = len(snake) - 3
score_text = font.render('Score: ' + str(score), True, RED)
screen.blit(score_text, [10, 10])
# 刷新屏幕
pygame.display.update()
# 设置帧数
clock.tick(10)
# 游戏结束,显示结束信息
if game_win:
game_over_text = font.render('You win!', True, RED)
else:
game_over_text = font.render('Game over!', True, RED)
screen.blit(game_over_text, [SCREEN_WIDTH // 2 - 50, SCREEN_HEIGHT // 2])
pygame.display.update()
# 等待3秒后退出游戏
pygame.time.wait(3000)
pygame.quit()
```
希望这个代码能够帮到您!
阅读全文