用python编写一个贪吃蛇
时间: 2023-07-01 11:13:03 浏览: 84
Python编写一个贪吃蛇游戏
好的,这是一个简单的 Python 贪吃蛇游戏,可以用 Pygame 模块实现:
```python
import pygame
import time
import random
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 定义屏幕大小和蛇身单元格大小
dis_width = 800
dis_height = 600
snake_block = 10
# 创建屏幕
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake game by CSDN')
# 创建时钟对象
clock = pygame.time.Clock()
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 绘制蛇
def 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 gameLoop():
game_over = False
game_close = False
# 初始蛇头和长度
x1 = dis_width / 2
y1 = dis_height / 2
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(blue)
message("You lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()
# 当用户按下 Q 或者 C 键的时候
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:
gameLoop()
# 处理按键事件
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(blue)
# 绘制食物
pygame.draw.rect(dis, red, [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
# 绘制蛇
snake(snake_block, snake_List)
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(25)
# 退出 Pygame 模块
pygame.quit()
quit()
# 启动游戏循环
gameLoop()
```
你可以复制以上代码,粘贴到 Python 环境中运行,就可以玩到贪吃蛇游戏了。
阅读全文