给我一个python贪吃蛇代码
时间: 2024-04-29 08:01:41 浏览: 213
下面是一个简单的 Python 贪吃蛇代码,你可以尝试运行它:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义窗口大小和标题
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇的初始位置和大小
snake_block = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义函数,用于显示消息
def message(msg, color):
message = font_style.render(msg, True, color)
screen.blit(message, [width / 6, height / 3])
# 定义函数,用于绘制贪吃蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block, snake_block])
# 游戏循环
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(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_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(white)
pygame.draw.rect(screen, 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
# 绘制贪吃蛇
draw_snake(snake_block, snake_List)
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
# 更新屏幕
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
# 开始游戏
gameLoop()
```
阅读全文