python写贪吃蛇
时间: 2023-06-30 07:17:45 浏览: 46
好的,下面是一个简单的 Python 贪吃蛇游戏的代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏界面大小
size = (800, 600)
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的初始位置和大小
snake_block = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 显示得分
def show_score(score):
score_font = font_style.render("得分: " + str(score), True, WHITE)
screen.blit(score_font, [0, 0])
# 画蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block, snake_block])
# 显示消息
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [size[0]/6, size[1]/3])
# 游戏循环
def gameLoop():
game_over = False
game_close = False
# 定义蛇的初始位置
x1 = size[0] / 2
y1 = size[1] / 2
# 蛇的移动距离
x1_change = 0
y1_change = 0
# 定义蛇的初始长度
snake_List = []
Length_of_snake = 1
# 随机生成食物的位置
foodx = round(random.randrange(0, size[0] - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, size[1] - snake_block) / 10.0) * 10.0
# 游戏主循环
while not game_over:
while game_close == True:
screen.fill(BLACK)
message("你失败了! 按 Q 退出或按 C 重新开始", RED)
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 >= size[0] or x1 < 0 or y1 >= size[1] or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 更新游戏界面
screen.fill(BLACK)
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)
show_score(Length_of_snake - 1)
pygame.display.update()
# 判断是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, size[0] - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, size[1] - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 设置游戏帧率
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
# 开始游戏
gameLoop()
```
这就是一个简单的 Python 贪吃蛇游戏,你可以根据自己的需求进行修改和扩展。