生成一段python代码,实现贪吃蛇游戏
时间: 2023-04-12 19:00:36 浏览: 70
PyGame贪吃蛇的实现代码示例
以下是一个基本的贪吃蛇游戏的Python代码实现,你可以根据自己的需要进行修改和优化:
```python
import pygame
import time
import random
# 初始化pygame
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
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('贪吃蛇游戏')
# 设置帧率
clock = pygame.time.Clock()
# 定义蛇的大小和速度
snake_block = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 显示得分
def Your_score(score):
value = font_style.render("得分: " + 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, black, [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
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(blue)
message("游戏结束,按 Q-退出或 C-重新开始", red)
Your_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:
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
# 超出屏幕范围,游戏结束
阅读全文