关于python:Python小游戏开发贪食蛇捕蛙

4次阅读

共计 3773 个字符,预计需要花费 10 分钟才能阅读完成。

每个程序员都有一个游戏梦,都想开发一款让他人爱不释手的游戏。游戏开发引擎很多像 Unity 3D,cocos2d,白鹭(Egret),LayaBox,threeJs 等等。一个偶尔的机会,看到 gitee 上举办趣味魔改贪吃蛇游戏,出于程序员的自信心的驱使,加上爱折腾的心理便果决报名加入了。明天和大家一起看看 Python 小游戏的开发。Python 有一个游戏开发的库 pygame,能够非常简单不便地开发游戏。

先看一下游戏运行的成果:

游戏有几个角色

  1. 贪吃蛇(Snake)
  2. 青蛙(Food)
  3. 障碍物 (Stone)

针对这三个角色,别离用三个类来形容。Snake, Food, Stone

Food 类须要做的是: 初始化,挪动,删除,投食物

import param
import pygame
import random
 
 
# 食物类
# 办法:搁置 / 移除
# 点以 25 为单位
class Food:
    def __init__(self):
        self.rect = pygame.Rect(-25, 0, 25, 25)
        self.allposX = []
        self.allposY = []
        for pos in range(25, param.SCREEN_X - 25, 25):
            self.allposX.append(pos)
        for pos in range(25, param.SCREEN_Y - 25, 25):
            self.allposY.append(pos)
 
    def remove(self):
        self.rect.x = -25
 
    def set(self, stone):
        if self.rect.x <= -25:
            allpos = []
            # 不靠墙太近 25 ~ SCREEN_X-25 之间
            for pos in range(25, param.SCREEN_X - 25, 25):
                allpos.append(pos)
 
            self.rect.left = random.choice(self.allposX)
            self.rect.top = random.choice(self.allposY)
 
            if stone.isContain(self.rect.left, self.rect.top):
                self.rect.left = -25
                self.set(stone)
 
    def move(self):
        self.rect.x -= 25

Stone 类须要做的是: 初始化,生成墙,挪动墙,新增墙,判断是否碰撞

import param
import pygame
import random
 
# 石头障碍物
# 点以 50 为单位
class Stone:
    def __init__(self):
        self.body = []
        self.allStoneHeigh = []
 
        for y in range(125, param.HALF_Y - 50, param.STONE_WIDTH):
            self.allStoneHeigh.append(y)
 
        for x in range(0, param.SCREEN_X, 200):
            self.body.append(self.generateWall(x, True))
            self.body.append(self.generateWall(x, False))
 
    def addOne(self):
        self.body.insert(0, self.generateWall(param.SCREEN_X - param.STONE_WIDTH, True))
        self.body.insert(0, self.generateWall(param.SCREEN_X - param.STONE_WIDTH, False))
 
    def generateWall(self, left, isTop):
        heigh = random.choice(self.allStoneHeigh)
        top = 0
        if isTop:
            top = 0
        else:
            top = param.SCREEN_Y - heigh
 
        wall = []
        for i in range(0, heigh, 50):
            wall.append(pygame.Rect(left, top + i,
                                    param.STONE_WIDTH, param.STONE_WIDTH))
        return wall
 
    def movePixel(self, pixel):
        print(len(self.body))
        if len(self.body) > 0:
            for wall in self.body:
                for stone in wall:
                    stone.left -= pixel
            if len(self.body) > 12:
                self.body.pop()
 
    def isContain(self, left, top):
        for wall in self.body:
            for stoneRect in wall:
                if (stoneRect.left == left or stoneRect.left == left - 25) and (stoneRect.top == top or stoneRect.top == top - 25):
                    return True
 
        return False

贪吃蛇类:

import pygame
import random
import param
from stone import Stone
 
# 蛇类
# 点以 25 为单位
class Snake(object):
    # 初始化各种须要的属性 [开始时默认向右 / 身材块 x5]
    def __init__(self):
        self.dirction = pygame.K_RIGHT
        self.body = []
        for x in range(5):
            self.addnode()
 
    # 无论何时 都在前端减少蛇块
    def addnode(self):
        left, top = (0, param.HALF_Y)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.dirction == pygame.K_LEFT:
            node.left -= 25
        elif self.dirction == pygame.K_RIGHT:
            node.left += 25
        elif self.dirction == pygame.K_UP:
            node.top -= 25
        elif self.dirction == pygame.K_DOWN:
            node.top += 25
        self.body.insert(0, node)
 
    # 删除最初一个块
    def delnode(self):
        self.body.pop()
 
    # 死亡判断
    def isdead(self, stone):
        # 撞墙
        if self.body[0].x not in range(param.SCREEN_X):
            return True
        if self.body[0].y not in range(param.SCREEN_Y):
            return True
        # 撞本人
        if self.body[0] in self.body[1:]:
            return True
 
        # 撞障碍物
        for rect in self.body:
            if stone.isContain(rect.left, rect.top):
                return True
        return False
 
    # 挪动!def move(self):
        self.addnode()
        self.delnode()
 
    # 改变方向 然而左右、高低不能被逆向扭转
    def changedirection(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
 
        if curkey == self.dirction:
            self.move()
 
        if curkey in LR + UD:
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            self.dirction = curkey
 
    def deadAction(self, screen, clock):
        failedImg1 = pygame.image.load('res/tail_up.png')
        failedImg2 = pygame.image.load('res/tail_right.png')
        failedImg3 = pygame.image.load('res/tail_down.png')
        failedImg4 = pygame.image.load('res/tail_left.png')
        imgList = [failedImg1, failedImg2, failedImg3, failedImg4]
        count = 0
        for img in imgList:
            count += 1
            if count >= 4:
                break
            screen.blit(img, (350, 300))
            clock.tick(2)
            pygame.display.update()

有了 3 个对象之后,接下来就是怎么管制,让他们动起来

pygame 库有个时钟类 Clock,通过设置 Clock 的帧率,来管制各个物体挪动的速度来达到页面挪动的成果。

clock = pygame.time.Clock()

clock.tick(3)

再增加一些吃到食物计分性能,当分数达到肯定的值,再触发降级进步游戏难度。使整个游戏的可玩度提高。为了进步网络游戏的体验,再加一些背景音乐和音效和死亡成果等等,整个游戏就饱满了。

正文完
 0