帮我写一个贪吃蛇游戏,要python格式的
时间: 2024-05-11 11:15:41 浏览: 105
很高兴为你服务!下面是一个简单的 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)
# 初始化 Pygame
pygame.init()
# 设置窗口
window_width = 600
window_height = 400
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的属性
snake_block_size = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义函数来显示消息
def message(msg, color):
message = font_style.render(msg, True, color)
window.blit(message, [window_width/6, window_height/3])
# 定义函数来显示蛇
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_block_size, snake_block_size])
# 定义主函数
def gameLoop():
game_over = False
game_close = False
x1 = window_width / 2
y1 = window_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
# 开始游戏循环
while not game_over:
# 如果游戏结束,显示结束消息
while game_close == True:
window.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:
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_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断蛇是否超出窗口边界
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
# 修改蛇的坐标
x1 += x1_change
y1 += y1_change
# 绘制食物
window.fill(white)
pygame.draw.rect(window, green, [foodx, foody, snake_block_size, snake_block_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_block_size, snake_List)
pygame.display.update()
# 判断蛇是否吃到了食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
Length_of_snake += 1
# 控制蛇的速度
pygame.time.Clock().tick(snake_speed)
# 退出 Pygame
pygame.quit()
quit()
gameLoop()
```
当然,这只是一个简单的贪吃蛇游戏,你可以根据自己的需求进行扩展和改进。
阅读全文