python python 贪吃蛇
时间: 2023-11-30 16:43:21 浏览: 37
以下是Python实现贪吃蛇小游戏的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置游戏标题
pygame.display.set_caption('贪吃蛇')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的初始位置和大小
BLOCK_SIZE = 10
snake_speed = 15
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义函数,用于在屏幕上显示文字
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [SCREEN_WIDTH / 6, SCREEN_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 game_over():
message_to_screen("Game over, press Q to quit or C to play again", RED)
pygame.display.update()
# 定义函数,用于运行游戏
def gameLoop():
game_exit = False
game_over_flag = False
# 初始化蛇的位置和长度
lead_x = SCREEN_WIDTH / 2
lead_y = SCREEN_HEIGHT / 2
lead_x_change = 0
lead_y_change = 0
snake_List = []
Length_of_snake = 1
# 初始化食物的位置
foodx = round(random.randrange(0, SCREEN_WIDTH - BLOCK_SIZE) / 10.0) * 10.0
foody = round(random.randrange(0, SCREEN_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0
while not game_exit:
while game_over_flag == True:
game_over()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over_flag = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -BLOCK_SIZE
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = BLOCK_SIZE
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -BLOCK_SIZE
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = BLOCK_SIZE
lead_x_change = 0
# 判断蛇是否撞到边界
if lead_x >= SCREEN_WIDTH or lead_x < 0 or lead_y >= SCREEN_HEIGHT or lead_y < 0:
game_over_flag = True
# 更新蛇的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制屏幕
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, [foodx, foody, BLOCK_SIZE, BLOCK_SIZE])
snake_Head = []
snake_Head.append(lead_x)
snake_Head.append(lead_y)
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_over_flag = True
draw_snake(BLOCK_SIZE, snake_List)
pygame.display.update()
# 判断蛇是否吃到食物
if lead_x == foodx and lead_y == foody:
foodx = round(random.randrange(0, SCREEN_WIDTH - BLOCK_SIZE) / 10.0) * 10.0
foody = round(random.randrange(0, SCREEN_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0
Length_of_snake += 1
# 设置游戏时钟
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
gameLoop()
```