py写一个贪吃蛇游戏
时间: 2024-06-13 15:03:46 浏览: 107
Python编写一个贪吃蛇游戏
好的,我可以为你提供一个简单的贪吃蛇游戏的代码。
```python
import pygame
import random
# 初始化
pygame.init()
# 屏幕尺寸
screen_width = 500
screen_height = 500
# 设置游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
# 蛇的尺寸
snake_size = 10
# 蛇的速度
snake_speed = 15
# 字体
font_style = pygame.font.SysFont(None, 30)
def message(msg, color):
"""
展示消息
"""
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [screen_width / 6, screen_height / 3])
def draw_snake(snake_list):
"""
绘制蛇
"""
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], snake_size, snake_size])
def game_loop():
"""
游戏循环
"""
game_over = False
game_close = False
# 蛇的初始位置
x1 = screen_width / 2
y1 = screen_height / 2
# 蛇的移动方向
x1_change = 0
y1_change = 0
# 初始长度
snake_list = []
length_of_snake = 1
# 食物位置
foodx = round(random.randrange(0, screen_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - snake_size) / 10.0) * 10.0
while not game_over:
while game_close:
screen.fill(white)
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:
game_loop()
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_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# 判断蛇是否超出屏幕
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_close = True
# 移动蛇的头部
x1 += x1_change
y1 += y1_change
# 绘制食物
pygame.draw.rect(screen, red, [foodx, foody, snake_size, snake_size])
# 添加蛇的头部坐标到列表中
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_list)
# 更新屏幕
pygame.display.update()
# 判断是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, screen_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - snake_size) / 10.0) * 10.0
length_of_snake += 1
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
game_loop()
```
这是一个简单的贪吃蛇游戏,仅供参考。如果您想要更加完整的游戏,可以在此基础上进行扩展。
阅读全文