基于Pygame如何实现简单的贪吃蛇游戏
这篇文章主要为大家展示了“基于Pygame如何实现简单的贪吃蛇游戏”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“基于Pygame如何实现简单的贪吃蛇游戏”这篇文章吧。
导入相关的包
import pygame, sys, randomfrom pygame.locals import *
设置屏幕大小以及基本参数
设置屏幕大小为400*400,mainClock = pygame.time.Clock()用来设置时间同步,不会根据计算机的运行来决定运行多少次, mainClock.tick(1) 一秒只会运行一次,设置了屏幕的底色为白色。
# 定义屏幕的宽高WIDTH = 400HEIGHT = 400# 初始化屏幕 设置窗口标题surface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)pygame.display.set_caption('贪吃蛇')pygame.init()mainClock = pygame.time.Clock()# 定义使用的颜色BLACK = (0, 0, 0)GREEN = (0, 255, 0)WHITE = (255, 255, 255)while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() surface.fill(WHITE) pygame.display.update() mainClock.tick(1)
设置贪吃蛇的位置,以及移动的大小
这里设置了贪吃蛇的长度和起始位置,和食物和蛇的宽度,这里必须设置为可以被食物和蛇的宽度整除的数,这样才能保证蛇能到任意的位置
# 设置蛇的初始长度snakeWidth = 4# 设置蛇的起始位置为(40,40)snakeX = 40snakeY = 40# 食物和蛇的宽度设置为8FOODSNAKEWIDTH = 8# 定义四个方向moveLeft = FalsemoveRight = FalsemoveUp = FalsemoveDown = False# 定义初始的方向moveRight = Truedef getSnake(): # 设置蛇的初始长度为4,并设置蛇的初始位置为(40,40) # 因为贪吃蛇会拐弯,所以将蛇设置为一个列表 snake = [] for i in range(snakeWidth): snake.append(pygame.Rect(snakeX + i * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) return snake# 贪吃蛇snake = getSnake()
绘制蛇
surface.fill(WHITE)for s in snake: pygame.draw.rect(surface, BLACK, s)
让蛇动起来
这里将蛇列表最后一位移除,然后将第一位的位置根据方向加减坐标
snake.pop() newTop = copy.deepcopy(snake[0]) # 改变蛇的位置 if moveRight: newTop.left += FOODSNAKEWIDTH if moveLeft: newTop.left -= FOODSNAKEWIDTH if moveUp: newTop.top -= FOODSNAKEWIDTH if moveDown: newTop.top += FOODSNAKEWIDTH snake.insert(0, newTop)
这样会有一个问题,如果超出屏幕呢,我们将超出屏幕,那么就会消失,我们只需要你移动第一个元素的时候,如果超出则将元素移动另一个位置。
# 改变蛇的位置 if moveRight: if newTop.right == WIDTH: newTop.left = 0 else: newTop.left += FOODSNAKEWIDTH if moveLeft: if newTop.left == 0: newTop.right == WIDTH else: newTop.left -= FOODSNAKEWIDTH if moveUp: if newTop.top == 0: newTop.bottom = HEIGHT else: newTop.top -= FOODSNAKEWIDTH if moveDown: if newTop.bottom == HEIGHT: newTop.top = 0 else: newTop.top += FOODSNAKEWIDTH
实现贪吃蛇拐弯
为了实现对应的功能,我们将方向变量改为一个变量,这样我们方便修改方向
# 定义四个方向# moveLeft moveRight moveUp moveDown# 定义初始的方向snakeDirection = "moveRight" ---- 省略的代码 ---- for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT: if snakeDirection == "moveRight": snake.reverse() snakeDirection = "moveLeft" if event.key == K_RIGHT: if snakeDirection == "moveLeft": snake.reverse() snakeDirection = "moveRight" if event.key == K_UP: if snakeDirection == "moveDown": snake.reverse() snakeDirection = "moveUp" if event.key == K_DOWN: if snakeDirection == "moveUp": snake.reverse() snakeDirection = "moveDown"
为了方便看到效果,我将mainClock.tick(1) 设置为mainClock.tick(3)
实现随机食物
这里用了很啰嗦的代码,我自己也看不下去,有点含糊,这里为了简单只设计了一个食物,遍历屏幕上不是贪吃蛇的可以放食物的集合,然后随机生成一个食物。
if len(foods) < foodnum: canFoodColl = [] # 获取当前不是贪吃蛇的位置集合 for x in range(sizeNum): for y in range(sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top: foodExist = False break if foodExist: canFoodColl.append({'x': x, 'y': y}) f = canFoodColl[random.randint(0, len(canFoodColl))] foods.append(pygame.Rect(f['x'], f['y'], FOODSNAKEWIDTH, FOODSNAKEWIDTH))
吃食物
这里用 colliderect判断二者是否相撞,然后食物集合置空,不减去贪吃蛇集合的最后一个元素。
if len(foods) < foodnum: canFoodColl = [] # 获取当前不是贪吃蛇的位置集合 for x in range(sizeNum): for y in range(sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top: foodExist = False break if foodExist: canFoodColl.append({'x': x, 'y': y}) f = canFoodColl[random.randint(0, len(canFoodColl))] foods.append(pygame.Rect(f['x'] * FOODSNAKEWIDTH, f['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) print(f['x']) print(f['y']) else: if newTop.colliderect(foods[0]): foods = [] eatFlg = True print('xxx')
完整代码
import pygame, sys, randomfrom pygame.locals import *import copy# 定义屏幕的宽高WIDTH = 400HEIGHT = 400# 初始化屏幕 设置窗口标题surface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)pygame.display.set_caption('贪吃蛇')pygame.init()mainClock = pygame.time.Clock()# 定义使用的颜色BLACK = (0, 0, 0)GREEN = (0, 255, 0)WHITE = (255, 255, 255)# 设置蛇的初始长度snakeWidth = 4# 设置蛇的起始位置为(40,40)snakeX = 40snakeY = 40# 食物和蛇的宽度设置为8FOODSNAKEWIDTH = 8# 定义四个方向# moveLeft moveRight moveUp moveDown# 定义初始的方向snakeDirection = "moveRight"# 食物区间foods = []# 用去宽度处以对应的 大小,减去1 就是食物矩形起点可以存在的区间#sizeNum = HEIGHT / FOODSNAKEWIDTH - 1# 这里为了减少计算sizeNum = 39# 为了简单我们只设置一个食物foodnum = 1def getSnake(): # 设置蛇的初始长度为4,并设置蛇的初始位置为(40,40) # 因为贪吃蛇会拐弯,所以将蛇设置为一个列表 snake = [] for i in range(snakeWidth): snake.append(pygame.Rect(snakeX + i * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) return snake# 贪吃蛇snake = getSnake()while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT: if snakeDirection == "moveRight": snake.reverse() snakeDirection = "moveLeft" if event.key == K_RIGHT: if snakeDirection == "moveLeft": snake.reverse() snakeDirection = "moveRight" if event.key == K_UP: if snakeDirection == "moveDown": snake.reverse() snakeDirection = "moveUp" if event.key == K_DOWN: if snakeDirection == "moveUp": snake.reverse() snakeDirection = "moveDown" surface.fill(WHITE) for s in snake: pygame.draw.rect(surface, BLACK, s) for f in foods: pygame.draw.rect(surface, GREEN, f) pygame.display.update() # 是否吃了食物 eatFlg = False newTop = copy.deepcopy(snake[0]) # 改变蛇的位置 if snakeDirection == "moveRight": if newTop.right == WIDTH: newTop.left = 0 else: newTop.left += FOODSNAKEWIDTH if snakeDirection == "moveLeft": if newTop.left == 0: newTop.right = WIDTH else: newTop.left -= FOODSNAKEWIDTH if snakeDirection == "moveUp": if newTop.top == 0: newTop.bottom = HEIGHT else: newTop.top -= FOODSNAKEWIDTH if snakeDirection == "moveDown": if newTop.bottom == HEIGHT: newTop.top = 0 else: newTop.top += FOODSNAKEWIDTH if len(foods) < foodnum: canFoodColl = [] # 获取当前不是贪吃蛇的位置集合 for x in range(sizeNum): for y in range(sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top: foodExist = False break if foodExist: canFoodColl.append({'x': x, 'y': y}) f = canFoodColl[random.randint(0, len(canFoodColl))] foods.append(pygame.Rect(f['x'] * FOODSNAKEWIDTH, f['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) print(f['x']) print(f['y']) else: if newTop.colliderect(foods[0]): foods = [] eatFlg = True print('xxx') snake.insert(0, newTop) if not eatFlg: snake.pop() mainClock.tick(3)
以上是“基于Pygame如何实现简单的贪吃蛇游戏”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网行业资讯频道!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341