Python贪食蛇代码
时间: 2023-11-05 22:02:03 浏览: 95
好的,您需要我提供Python贪食蛇的代码吗?下面是一个简单的Python贪食蛇游戏代码示例:
```python
import pygame
import random
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 设置窗口大小
width = 800
height = 600
# 初始化pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇")
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的大小和速度
snake_block = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义显示消息的函数
def message(msg, color):
msg = font_style.render(msg, True, color)
screen.blit(msg, [width / 6, height / 3])
# 定义游戏循环
def gameLoop():
game_over = False
game_close = False
# 蛇的第一个块
x1 = width / 2
y1 = height / 2
# 蛇的起始位置和长度
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
# 食物的起始位置
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 游戏循环
while not game_over:
# 游戏结束提示
while game_close == True:
screen.fill(black)
message("你输了!按 Q 退出,按 C 开始新游戏", red)
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
# 检测蛇是否碰到了边界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 在游戏窗口画蛇和食物
screen.fill(black)
pygame.draw.rect(screen, green, [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
draw_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)
pygame.display.update()
# 检测蛇是否吃到了食物,如果吃到了,长度加一
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 控制游戏速度
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
# 定义绘制蛇的函数
def draw_snake(snake_block, snake_List):
for x in snake_List:
pygame.draw.rect(screen, white, [x[0], x[1], snake_block, snake_block])
# 定义显示得分的函数
def Your_score(score):
value = font_style.render("得分: " + str(score), True, white)
screen.blit(value, [0, 0])
# 启动游戏循环
gameLoop()
```
以上便是一个简单的Python贪食蛇游戏代码示例,供您参考。
阅读全文