基于python的贪吃蛇代码
时间: 2023-11-04 21:14:19 浏览: 68
以下是基于Python的贪吃蛇代码,包括游戏界面的设计、蛇的移动、食物的生成等功能:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义游戏界面大小
play_width = 600
play_height = 400
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 创建游戏界面
game_display = pygame.display.set_mode((play_width, play_height))
pygame.display.set_caption("贪吃蛇游戏")
# 设置游戏界面的时钟
clock = pygame.time.Clock()
# 定义蛇的大小
snake_block = 10
# 定义字体大小
font_style = pygame.font.SysFont(None, 30)
# 定义分数的显示函数
def score(score):
value = font_style.render("得分:" + str(score), True, white)
game_display.blit(value, [0, 0])
# 定义蛇的移动函数
def snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, green, [x[0], x[1], snake_block, snake_block])
# 定义游戏结束的函数
def message(msg, color):
mesg = font_style.render(msg, True, color)
game_display.blit(mesg, [play_width/6, play_height/3])
# 定义游戏主函数
def game_loop():
game_exit = False
game_over = False
# 定义蛇的初始位置和长度
x1 = play_width / 2
y1 = play_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
# 定义食物的初始位置
foodx = round(random.randrange(0, play_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, play_height - snake_block) / 10.0) * 10.0
while not game_exit:
# 如果游戏结束,显示分数和提示语
while game_over == True:
game_display.fill(black)
message("游戏结束!按Q退出,按C重新开始游戏", red)
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_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()
# 判断是否按下按键
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = 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 >= play_width or x1 < 0 or y1 >= play_height or y1 < 0:
game_over = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制游戏界面
game_display.fill(black)
pygame.draw.rect(game_display, 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_over = True
snake(snake_block, snake_List)
score(Length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, play_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, play_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 设置游戏界面的帧率
clock.tick(15)
# 退出pygame
pygame.quit()
# 运行游戏主函数
game_loop()
```
这个代码中,游戏界面的大小为600x400,蛇的大小为10x10,游戏界面的帧率为15帧。游戏中通过键盘控制蛇的移动,如果撞到墙壁或者自己的身体,游戏结束,如果吃到食物,蛇的长度增加。游戏结束后可以按Q退出,按C重新开始游戏。
阅读全文