写一个python贪吃蛇代码
时间: 2023-07-25 12:06:54 浏览: 130
以下是一个简单的Python贪吃蛇游戏代码:
```python
import pygame
import random
# 定义颜色变量
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 设置游戏屏幕尺寸
dis_width = 600
dis_height = 400
# 初始化pygame
pygame.init()
# 创建游戏屏幕
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game')
# 设置时钟
clock = pygame.time.Clock()
# 设置方块尺寸和速度
snake_block = 10
snake_speed = 15
# 设置字体
font_style = pygame.font.SysFont(None, 30)
# 绘制分数
def our_score(score):
value = font_style.render("Score: " + str(score), True, white)
dis.blit(value, [0, 0])
# 绘制蛇
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block])
# 提示信息
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
# 游戏循环
def game_loop():
game_over = False
game_close = False
# 初始位置
x1 = dis_width / 2
y1 = dis_height / 2
# 初始移动方向
x1_change = 0
y1_change = 0
# 蛇的初始长度
snake_List = []
Length_of_snake = 1
# 随机生成食物位置
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
# 游戏开始循环
while not game_over:
# 游戏结束提示
while game_close == True:
dis.fill(black)
message("You Lost! Press Q-Quit or C-Play Again", red)
our_score(Length_of_snake - 1)
pygame.display.update()
# 判断玩家操作
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
# 判断玩家操作
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 判断蛇越界
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
# 更新蛇位置
x1 += x1_change
y1 += y1_change
# 绘制背景色
dis.fill(black)
# 绘制食物
pygame.draw.rect(dis, blue, [foodx, foody, snake_block, snake_block])
# 更新蛇列表
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
# 判断蛇与食物碰撞
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
# 绘制蛇
our_snake(snake_block, snake_List)
# 绘制分数
our_score(Length_of_snake - 1)
# 更新游戏屏幕
pygame.display.update()
# 判断蛇与食物重合
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 控制游戏速度
clock.tick(snake_speed)
# 关闭pygame
pygame.quit()
# 退出程序
quit()
# 开始游戏
game_loop()
```
运行代码即可开始游戏,使用方向键控制蛇的移动,吃到食物后蛇的长度会增加。游戏结束后可以选择退出或重新开始。
阅读全文