Python贪吃蛇游戏的示例代码:
import pygame
import time
import random# 初始化游戏
pygame.init()# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)# 定义游戏窗口大小和标题
display_width = 800
display_height = 600# 创建游戏窗口
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('贪吃蛇')# 设置游戏时钟
clock = pygame.time.Clock()# 定义蛇的大小和移动速度
snake_block = 10
snake_speed = 30# 定义字体样式和大小
font_style = pygame.font.SysFont(None, 30)
score_font = pygame.font.SysFont(None, 50)# 定义蛇的颜色
snake_color = green# 显示得分
def your_score(score):value = score_font.render("得分: " + str(score), True, black)gameDisplay.blit(value, [0, 0])# 绘制蛇
def our_snake(snake_block, snake_list):for x in snake_list:pygame.draw.rect(gameDisplay, snake_color, [x[0], x[1], snake_block, snake_block])# 显示消息并重新开始游戏
def message(msg, color):mesg = font_style.render(msg, True, color)gameDisplay.blit(mesg, [display_width/6, display_height/3])# 游戏循环
def gameLoop():game_over = Falsegame_close = False# 蛇的起始位置和长度x1 = display_width / 2y1 = display_height / 2x1_change = 0y1_change = 0snake_List = []Length_of_snake = 1# 随机生成食物的位置foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0# 游戏主循环while not game_over:while game_close == True:gameDisplay.fill(white)message("游戏结束,按Q-退出,C-重新开始", red)your_score(Length_of_snake - 1)pygame.display.update()# 游戏结束后的处理for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Truegame_close = Falseif event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:gameLoop()# 控制蛇的移动for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0# 边界判断if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changegameDisplay.fill(white)pygame.draw.rect(gameDisplay, 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 = Trueour_snake(snake_block, snake_List)your_score(Length_of_snake - 1)pygame.display.update()# 吃到食物的判断if x1 == foodx and y1 == foody:foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0Length_of_snake += 1# 控制帧率clock.tick(snake_speed)pygame.quit()quit()# 运行游戏
gameLoop()
运行以上代码,即可启动一个贪吃蛇游戏。你可以用方向键控制蛇的移动,吃到食物后蛇的长度会增加,如果蛇撞到边界或者自己,游戏结束。