11

用golang写一个简单的游戏(二)

 3 years ago
source link: https://studygolang.com/articles/28692
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.

上篇文章写到了,我已经打印出了一个从起点到终点的路径,并且这是受键盘事件控制的。今天我会继续给这个游戏添加一些东西,让它看起来像个“游戏”。

现在我要加上一个障碍,不是随便一条路径都可以从起点到终点,这个障碍就姑且叫它“炸弹”,我赋给它的规则是,它的上下左右(称之为陷阱)及它本身不能经过,必须绕着走。即如图:

nERnqqj.png!web

boom.png

添加这个道具,我有几个改动的地方,如下:

  1. 获取每个关卡的参数,增加了炸弹的位置和周围陷阱的位置,结构体变成了这样子:
type RoundParams struct {
    Height       int //画布高度
    Width        int //画布宽度
    BoomNum      int //炸弹数量
    BoomPosition [][]int //炸弹位置,坐标数组
    TrapPosition [][]int //陷阱位置,坐标数组
}
  1. 增加一个检查下一步是否会踏入陷阱的函数
func checkTrap(round int, point *components.Point, direction string) bool {
    rp := rounds.GetRoundParams(round)
    x := point.X
    y := point.Y
    switch direction {
    case "up":
        y -= 1
    case "down":
        y += 1
    case "left":
        x -= 1
    case "right":
        x += 1
    }
    for _, v := range rp.TrapPosition {
        if x == v[0] && y == v[1] {
            return true
        }
    }
    return false
}
  1. 由于炸弹的上下左右都不能走了,那么炸弹的位置就有要求,不能是画布上随意的一个点,具体要求是:假设画布是m×n,起点位置是(0,0),终点位置是(m,n),炸弹位置是(x,y),那么2≤x≤m-2,2≤y≤n-2,否则永远无法走出起点或者无法走到终点,那多么可怜。
memUriN.png!web

boomboom.png

来看下效果:

mU3auuU.gif

boom-demo.gif

至此,我添加了一个炸弹在路上,再也不是随便能到达终点。项目地址是: https://github.com/TomatoMr/boomboom.git

后面,还可以继续思考,一张m×n画布上,最多可以有多少个炸弹,以及有多个炸弹的干扰,从起点到终点的最短路径怎么计算。

欢迎关注我的公众号:onepunchgo,给我留言。

IFraEjM.jpg!web

image

欢迎关注我们的微信公众号,每天学习Go知识

FveQFjN.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK