0
点赞
收藏
分享

微信扫一扫

Python游戏开发,pygame模块,Python实现贪吃蛇小游戏

MaxWen 2021-09-21 阅读 124

前言

今天给大家分享贪吃蛇小游戏,废话不多说,让我们愉快地开始吧~

效果展示

开发工具

Python版本: 3.6.4

相关模块:

pygame模块;

以及一些Python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

原理简介

贪吃蛇的游戏规则应该不需要我多做介绍了吧T_T。写个贪吃蛇游戏其实还是很简单的。首先,我们进行一下游戏初始化:

pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('Greedy Snake —— 微信公众号:Charles的皮卡丘')
clock = pygame.time.Clock()

然后定义一个贪吃蛇类:

'''贪吃蛇类'''
class Snake(pygame.sprite.Sprite):
def __init__(self, cfg, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.cfg = cfg
self.head_coord = [random.randint(5, cfg.GAME_MATRIX_SIZE[0]-6), random.randint(5, cfg.GAME_MATRIX_SIZE[1]-6)]
self.tail_coords = []
for i in range(1, 3):
self.tail_coords.append([self.head_coord[0]-i, self.head_coord[1]])
self.direction = 'right'
self.head_colors = [(0, 80, 255), (0, 255, 255)]
self.tail_colors = [(0, 155, 0), (0, 255, 0)]

其中head_coord用来记录蛇头所在位置,而tail_coords是一个二维数组,用来记录所有蛇身的位置。一开始,贪吃蛇长为3,并且位置是随机生成的。用户通过↑↓←→键来控制贪吃蛇的行动:

# --按键检测
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:
snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])

需要注意的是,贪吃蛇不能180°大拐弯,只能90°地拐弯。例如正在向左行动的贪吃蛇不能瞬间变成向右行动。具体而言,代码实现如下:

'''设置方向'''
def setDirection(self, direction):
assert direction in ['up', 'down', 'right', 'left']
if direction == 'up':
if self.head_coord[1]-1 != self.tail_coords[0][1]:
self.direction = direction
elif direction == 'down':
if self.head_coord[1]+1 != self.tail_coords[0][1]:
self.direction = direction
elif direction == 'left':
if self.head_coord[0]-1 != self.tail_coords[0][0]:
self.direction = direction
elif direction == 'right':
if self.head_coord[0]+1 != self.tail_coords[0][0]:
self.direction = direction

然后,我们需要随机生成一个食物,且需要保证该食物的位置不与贪吃蛇的位置相同:

'''食物类'''
class Apple(pygame.sprite.Sprite):
def __init__(self, cfg, snake_coords, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.cfg = cfg
while True:
self.coord = [random.randint(0, cfg.GAME_MATRIX_SIZE[0]-1), random.randint(0, cfg.GAME_MATRIX_SIZE[1]-1)]
if self.coord not in snake_coords:
break
self.color = (255, 0, 0)
'''画到屏幕上'''
def draw(self, screen):
cx, cy = int((self.coord[0] + 0.5) * self.cfg.BLOCK_SIZE), int((self.coord[1] + 0.5) * self.cfg.BLOCK_SIZE)
pygame.draw.circle(screen, self.color, (cx, cy), self.cfg.BLOCK_SIZE//2-2)
# 随机生成一个食物
apple = Apple(cfg, snake.coords)

在更新贪吃蛇的时候,如果它吃到了食物,则蛇身长加一,否则只是简单的按照给定的方向行动而不改变蛇身长度:

'''更新贪吃蛇'''
def update(self, apple):
# 根据指定的方向运动
self.tail_coords.insert(0, copy.deepcopy(self.head_coord))
if self.direction == 'up':
self.head_coord[1] -= 1
elif self.direction == 'down':
self.head_coord[1] += 1
elif self.direction == 'left':
self.head_coord[0] -= 1
elif self.direction == 'right':
self.head_coord[0] += 1
# 判断是否吃到了食物
if self.head_coord == apple.coord:
return True
else:
self.tail_coords = self.tail_coords[:-1]
return False

同时,当贪吃蛇吃到食物时,需要重新生成一个新的食物:

apple = Apple(cfg, snake.coords)

最后,当贪吃蛇碰到墙壁或者蛇头碰到蛇身时,游戏结束:

'''判断游戏是否结束'''
@property
def isgameover(self):
if (self.head_coord[0] < 0) or (self.head_coord[1] < 0) or \
(self.head_coord[0] >= self.cfg.GAME_MATRIX_SIZE[0]) or \
(self.head_coord[1] >= self.cfg.GAME_MATRIX_SIZE[1]):
return True
if self.head_coord in self.tail_coords:
return True
return False

并显示一下游戏结束界面:

endInterface(screen, cfg)

文章到这里就结束了,感谢你的观看,Python24个小游戏系列,下篇文章分享扫雷小游戏

为了感谢读者们,我想把我最近收藏的一些编程干货分享给大家,回馈每一个读者,希望能帮到你们。

All done~详见个人主页简介或私信获取完整源代码。。

往期回顾

Python实现2048小游戏

Python实现五子棋联机对战小游戏

Python实现过迷宫小游戏

Python实现“小兔子和Bun”游戏

Python实现八音符小游戏

Python实现拼图小游戏

Python实现滑雪小游戏

Python实现经典90坦克大战

Python实现FlappyBird小游戏

Python实现恐龙跳一跳小游戏

Python实现塔防小游戏

Python实现接水果和金币小游戏

Python实现简易版飞机大战小游戏

Python实现俄罗斯方块小游戏

Python实现推箱子小游戏

Python实现外星人入侵小游戏

Python实现经典吃豆豆小游戏

Python实现消消乐小游戏

Python实现24点小游戏

Python实现乒乓球小游戏

Python实现打砖块小游戏

Python实现过打地鼠小游戏

举报

相关推荐

0 条评论