当经典游戏遇上Python——体验十分钟构建自己的休闲娱乐贪吃蛇小游戏!
话不多说,直接上源码,复制粘贴即可完美运行!(如果你已经安装了pygame库)
import pygame
import time
import randompygame.init()# 定义颜色
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)# 设置屏幕宽高
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('方块贪吃蛇')# 设置初始速度
snake_block = 10
snake_speed = 15# 字体设置
font_style = pygame.font.SysFont(None, 50)def our_snake(snake_block, snake_list):for x in snake_list:pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block])def message(msg, color):mesg = font_style.render(msg, True, color)dis.blit(mesg, [dis_width / 6, dis_height / 3])def gameLoop(): # 创建游戏循环game_over = Falsegame_close = False# 初始蛇的位置x1 = dis_width / 2y1 = dis_height / 2# 初始蛇的移动方向x1_change = 0y1_change = 0# 初始蛇的长度snake_List = []Length_of_snake = 1# 设置食物初始位置foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0while not game_over:while game_close == True:dis.fill(blue)message("You lost!Press Q-Quit or C-Try again", red)our_snake(snake_block, snake_List)pygame.display.update()for event in pygame.event.get():if 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 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changedis.fill(blue)pygame.draw.rect(dis, 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)pygame.display.update()# 判断蛇是否吃到食物if x1 == foodx and y1 == foody:foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0Length_of_snake += 1pygame.time.Clock().tick(snake_speed)pygame.quit()quit()gameLoop()
这是一个纯Python代码超快速实现简易贪吃蛇小游戏,不需要透明背景的各种图像模型,直接基于原生小方块上手贪吃蛇小游戏
通过键盘上面的上下左右方向键即可控制小蛇开始游戏,与传统移动方式不同的是,此模式中的方块小蛇可以直接向前行过程中实现逆向操作,上行变下行,右行变左行
运行结果如下所示: