python贪吃蛇代码
时间: 2023-09-14 20:11:55 浏览: 41
下面是一个简单的Python贪吃蛇代码,希望能帮到你:
```python
import pygame
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)
# 设置屏幕大小和标题
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_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 message(msg, color):
"""
显示提示信息
"""
message_text = font_style.render(msg, True, color)
game_display.blit(message_text, [display_width / 6, display_height / 3])
def game_loop():
# 初始化蛇的位置和长度
snake_list = []
length_of_snake = 1
# 初始化食物的位置
food_x = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
# 初始化蛇的位置
x1 = display_width / 2
y1 = display_height / 2
x1_change = 0
y1_change = 0
game_exit = False
game_over = False
while not game_exit:
while game_over:
game_display.fill(white)
message("You Lost! Press Q-Quit or C-Play Again", red)
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 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
game_over = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 填充背景色
game_display.fill(black)
# 绘制食物
pygame.draw.rect(game_display, green, [food_x, food_y, 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
# 绘制蛇
for x in snake_list:
pygame.draw.rect(game_display, blue, [x[0], x[1], snake_block, snake_block])
# 更新屏幕
pygame.display.update()
# 当蛇头碰到食物时,更新食物的位置,蛇的长度加1
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
length_of_snake += 1
# 设置蛇的速度
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
# 退出程序
quit()
# 启动游戏循环
game_loop()
```
这是一个基本的贪吃蛇游戏代码,你可以根据自己的需要进行修改和优化。