8

有趣!10分钟用Python编写一个贪吃蛇小游戏

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzIzNTg3MDQyMQ%3D%3D&%3Bmid=2247486556&%3Bidx=2&%3Bsn=8693d19c836f6902ea1f6d14ff406069
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

来源:网络,版权归原作者所有

贪吃蛇,大家应该都玩过。当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎。今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果:

VRbI7ne.gif

好了,先介绍一个思路

所有的游戏最主要的内容都是程序的内循环,这才是保证一个游戏能够正常运行的前提。

以下是编写贪吃蛇小游戏的主要思路。

YbyY3eJ.jpg!web

废话不多说,我们直接来讲解如何利用Python进行贪吃蛇的编写吧

一、调用库以及初始设置

1. 调用第三方库

Python与其他语言很不一样的一点在于他有很多的第三方库可以调用。在Python编写游戏时,pygame是一个很简单上手的第三方库,可以通过pip直接安装。安装方法在之前的文章中已经讲过,就不再赘述。想要了解更多pygame功能的朋友也可以查阅官方的文档。

这就是编写贪吃蛇时我们需要调用的库。

import pygame
import sys
import random
from pygame.locals import *
import time

2 .初始设置

我们通过这几行代码来初始化pygame,定义窗口(边界)的大小,窗口的标题和图标。

# 初始化pygame
pygame.init()  # 调用pygame模块初始函数
fpsClock = pygame.time.Clock()

playSurface = pygame.display.set_mode((640, 480))  # 界面
pygame.display.set_caption('Snake Go!')  # 标题
image=pygame.image.load('game.ico')            # 背景
pygame.display.set_icon(image)

3. 定义颜色变量

由于我们需要用到一些颜色,而Python是不自带的。所以我们需要定义几个颜色。

# 3、定义颜色变量
redColor = pygame.Color(255, 0, 0)
blackColor = pygame.Color(0, 0, 0)
whiteColor = pygame.Color(255, 255, 255)
greyColor = pygame.Color(150, 150, 150)
lightColor = pygame.Color(220, 220, 220)

二、GameOver

之前提到,所有游戏最重要的部分是循环。而GameOver函数就是跳出这个循环的条件。这里给出当蛇吃到自己身体或者碰到边界时显示的界面(判断死亡的代码会在之后展示)

# 4、Game Over
def gameOver(playSurface, score):
    gameOverFont = pygame.font.SysFont('arial', 72)
    gameOverSurf = gameOverFont.render('Game Over', True, greyColor)
    gameOverRect = gameOverSurf.get_rect()
    gameOverRect.midtop = (320, 125)
    playSurface.blit(gameOverSurf, gameOverRect)
    scoreFont = pygame.font.SysFont('arial', 48)
    scoreSurf = scoreFont.render('SCORE:' + str(score), True, greyColor)
    scoreRect = scoreSurf.get_rect()
    scoreRect.midtop = (320, 225)
    playSurface.blit(scoreSurf, scoreRect)
    pygame.display.flip()
    time.sleep(5)
    pygame.quit()
    sys.exit()

三、贪吃蛇与树莓

接下来介绍游戏的主题部分,即贪吃蛇与蛇莓的显示以及运动。

1. 定义初始位置

我们将整个界面看成许多20*20的小方块,每个方块代表一个单位,蛇的长度就可以用几个单位表示啦。这里蛇的身体用列表的形式存储,方便之后的删减。

# 5、定义初始位置
snakePosition = [100, 100]  # snake位置
snakeSegments = [[100, 100], [80, 100], [30, 100]]  # snake长度
raspberryPosition = [300, 300]  # food位置
raspberrySpawned = 1  # food数量
direction = 'right'  # 方向
changeDirection = direction  # 改变方向
score = 0  # 得分

2 .键盘输入判断蛇的运动

我们需要通过键盘输入的上下左右键或WASD来控制蛇类运动,同时加入按下Esc就退出游戏的功能。

for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    elif event.type == KEYDOWN:  # 键盘输入
        if event.key == K_RIGHT or event.key == ord('d'):  # 方向键和AWSD
            changeDirection = 'right'
        if event.key == K_LEFT or event.key == ord('a'):
            changeDirection = 'left'
        if event.key == K_UP or event.key == ord('w'):
            changeDirection = 'up'
        if event.key == K_DOWN or event.key == ord('s'):
            changeDirection = 'down'
        if event.key == K_ESCAPE:
            changeDirection == 'up'

贪吃蛇运动有一个特点:不能反方向运动。所以我们需要加入限制条件。

if changeDirection == 'right' and not direction == 'left':  # 在事件for之下,控制不能反向
    direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
    direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
    direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
    direction = changeDirection

接下来就是将蛇头按照键盘的输入进行转弯操作,并将蛇头当前的位置加入到蛇身的列表中。

if direction == 'right':  # 方向为→,snake位置加1
    snakePosition[0] += 10
if direction == 'left':
    snakePosition[0] -= 10
if direction == 'up':
    snakePosition[1] -= 20
if direction == 'down':
    snakePosition[1] += 10
snakeSegments.insert(0, list(snakePosition))

3 .判断是否吃到树莓

如果蛇头与树莓的方块重合,则判定吃到树莓,将树莓数量清零;而没吃到树莓的话,蛇身就会跟着蛇头运动,蛇身的最后一节将被踢出列表。

if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
    raspberrySpawned = 0
else:
    snakeSegments.pop()

4 .重新生成树莓

当树莓数量为0时,重新生成树莓,同时分数增加。

if raspberrySpawned == 0:
    x = random.randrange(1, 32)
    y = random.randrange(1, 24)
    raspberryPosition = [int(x * 20), int(y * 20)]
    raspberrySpawned = 1
    score += 1

5. 刷新显示层

每次蛇与树莓的运动,都会进行刷新显示层的操作来显示。有点类似于动画的"帧"。

playSurface.fill(blackColor)
for position in snakeSegments[1:]:
    pygame.draw.rect(playSurface, whiteColor, Rect(position[0], position[1], 20, 20))
pygame.draw.rect(playSurface, lightColor, Rect(snakePosition[0], snakePosition[1], 20, 20))
pygame.draw.rect(playSurface, redColor, Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()

6. 判断是否死亡

当蛇头超出边界或者蛇头与自己的蛇身重合时,蛇类死亡,调用GameOver。

if snakePosition[0] > 620 or snakePosition[0] < 0:
    gameOver(playSurface, score)
if snakePosition[1] > 460 or snakePosition[1] < 0:
    gameOver(playSurface, score)
for snakeBody in snakeSegments[1:]:
    if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
        gameOver(playSurface, score)

7. 控制游戏速度

为了增加难度,我们设置蛇身越长速度越快,直到达到一个上限。

if len(snakeSegments) < 40:
    speed = 6 * len(snakeSegments) // 4
else:
    speed = 16
fpsClock.tick(speed)

到这里,贪吃蛇小游戏就写完了。怎样,简单不?

本文完整代码可以在公众号后台回复  贪吃蛇  来获取。

好文章,我 在看 :heart:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK