请用Python写一个贪吃蛇的小游戏
时间: 2023-06-01 21:06:46 浏览: 44
好的,我可以为您提供 Python 代码实现贪吃蛇小游戏。以下是代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设定游戏屏幕大小
screen = pygame.display.set_mode((400, 400))
# 定义颜色变量
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 设定游戏字体
font_style = pygame.font.SysFont(None, 30)
# 定义函数显示得分
def show_score(score):
value = font_style.render("Score: " + str(score), True, white)
screen.blit(value, [0, 0])
# 定义函数画蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, blue, [x[0], x[1], snake_block, snake_block])
# 定义游戏循环
def gameLoop():
game_over = False
game_close = False
# 初始化蛇位置和移动方向
x1 = 200
y1 = 200
x1_change = 0
y1_change = 0
# 初始化苹果位置
foodx = round(random.randrange(0, 400 - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, 400 - snake_block) / 10.0) * 10.0
# 初始化蛇身列表
snake_list = []
Length_of_snake = 1
# 设定刷新频率
clock = pygame.time.Clock()
while not game_over:
while game_close == True:
screen.fill(black)
message = font_style.render("You Lost! Press Q-Quit or C-Play Again", True, white)
message_rect = message.get_rect(center=(200, 200))
screen.blit(message, message_rect)
show_score(Length_of_snake - 1)
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 >= 400 or x1 < 0 or y1 >= 400 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)
show_score(Length_of_snake - 1)
pygame.display.update()
# 吃到苹果,加长一节
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, 400 - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, 400 - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 设定刷新频率
clock.tick(snake_speed)
# 退出pygame,退出python
pygame.quit()
quit()
# 初始化游戏相关参数
snake_block = 10
snake_speed = 15
# 开始游戏
gameLoop()
```
请注意,此代码仅供参考,您可能需要修改以适应您的游戏需求。