【鸿蒙】贪吃蛇(JS)

【1】创建项目

这里我们创建一个Snake项目,开发语言选JS。至于API的选择无所谓啦(反正没有后端)

可运行的设备,这里至少选择一个,各人建议选择平板(不过也无所谓),在平板上运行的效果更好一点。 话不多说直接上图。

【2】清空hml、css、js文件

别清错了嗷,清理完如下图

【3】编写index.hml

话不多说之接上代码,写好的注释,傻子阅读。

<!--容量-->
<div class="container">
    <!-- 标题 -->
    <text class="title">Snake Game</text>
    
    <!-- 画布组件 : 贪吃蛇移动的区域-->
    <canvas ref="canvasref" style="width: 600px; height: 600px; background-color: black;"></canvas>

    <!-- 上按键 -->
    <image src="/common/up.png" class="backBtnup" onclick="onStartGame(1)"></image>

    <!-- 下面三个按键 -->
    <div class="directsecond">
        <!-- 左按键 -->
        <image src="/common/left.png" class="backBtnleft" onclick="onStartGame(2)"></image>
        <!-- 下按键 -->
        <image src="/common/down.png" class="backBtncenter" onclick="onStartGame(3)"></image>
        <!-- 右按键 -->
        <image src="/common/right.png" class="backBtnright" onclick="onStartGame(4)"></image>
    </div>

    <!-- 判断游戏是否结束,如果结束就显示 -->
    <text if="{{gameOver}}" class="scoretitle">
        <span>Game Over</span>
    </text>

    <!-- 显示得分 -->
    <text if="{{!gameOver}}" class="scoretitle">
        <span>Score: {{score}}</span>
    </text>

</div>

 【4】index.css

css的代码没什么好说的,看代码吧

.container {
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: white;
}

.title {
    font-size: 50px;
    margin-bottom: 10px;
}

.scoretitle {
    font-size: 50px;
    margin-top: 30px;
}

/*
css选择器,逗号代表并列关系
*/
.backBtnup, .backBtncenter, .backBtnleft, .backBtnright {
    width: 50px;
    height: 50px;
    margin-bottom: 20px;
    margin-top: 20px;
    border-radius: 10px;
    background-color: black;
}

.directsecond {
    flex-direction: row;
    justify-content: center;
    align-items: center;
}

.backBtnup {
    margin-top: 80px;
}

.backBtncenter {
    margin-left: 40px;
    margin-right: 40px;
}

【5】index.js

这才是今天的重中之重,好好看好好学,懒得讲了,不难都有注释自己看吧。

export default {
    data: {
        title: "",
        snakeSize: 30,      // 蛇身格子像素大小
        w: 600,             // 背景的宽度
        h: 600,             // 背景的高度
        score: 0,           // 得分为0
        snake : [],         // 数组用来存蛇每个格子的位置
        ctx: null,          // 用来调用填充颜色的
        food: null,         // 食物位置
        direction: '',      // 按键的状态
        gameOver: false,    // 游戏状态
        tail: {             // 记录更新后蛇头的位置
            x: 0,
            y: 0
        },
        interval : null     // 获得setInterval()的返回值
    },
    onInit() {
        this.title = this.$t('strings.world');
    },
    onShow() {
        // 通过$refs得到组件,进而调用组件的变量和方法
        const canvas = this.$refs.canvasref;
        // 指定了二维绘画
        this.ctx = canvas.getContext("2d");
        // 第一次打开app时,初始化蛇的方向
        this.direction = 'down';
        // 调用初始化蛇体的方法
        this.drawSnake()
        // 创建食物的位置
        this.createFood()
        // 渲染帧画面
        this.paint()
    },
    // 画背景
    drawArea() {
        var ctx = this.ctx
        // 设置填充颜色
        ctx.fillStyle = '#61c7e6';
        // 填充
        ctx.fillRect(0, 0, this.w, this.h);
        // 设置矩阵颜色
        ctx.strokeStyle = '#00000';
        // 矩阵的线宽
        ctx.lineWidth = 5;
        // 绘制矩阵(不填色)
        ctx.strokeRect(0, 0, this.w, this.h);
        this.ctx = ctx
    },
    // 创建蛇体
    drawSnake() {
        var len = 7;
        var snake = [];
        // 默认蛇的长度为7
        for (var i = len - 1; i >= 0; i--) {
            // 将x轴和y轴的坐标数据存到数组中,这些数据就是每个蛇格子的位置
            snake.push({
                x: 0,
                y: i
            });
        }
        // 更新蛇的长度
        this.snake = snake;
    },
    // 设计蛇身的颜色
    bodySnake(x, y) {
        //组成蛇的像素
        var ctx = this.ctx;
        // 蛇的颜色及填充的位置和大小
        ctx.fillStyle = '#e28743';
        // fillRect()指的是要填充的位置及大小 参数说明:fillRect(X轴位置, Y轴位置, 宽度, 高度)
        ctx.fillRect(x * this.snakeSize, y * this.snakeSize, this.snakeSize, this.snakeSize);
        // 蛇的内部格子边框颜色,加了才会分割
        ctx.strokeStyle = '#063970';
        ctx.strokeRect(x * this.snakeSize, y * this.snakeSize, this.snakeSize, this.snakeSize);
        this.ctx = ctx;
    },
    //食物的颜色
    cookie(x, y) {
        var ctx = this.ctx;
        // 食物的颜色及填充位置和大小
        ctx.fillStyle = '#e2d743';
        ctx.fillRect(x * this.snakeSize, y * this.snakeSize, this.snakeSize, this.snakeSize);
        this.ctx = ctx;
    },
    // 创建食物的位置
    createFood() {
        // 随机生成食物的位置
        // 这里的20是背景高度(宽度)/ 格子高度(宽度),即 600 / 30 = 20
        this.food = {
            x: Math.floor((Math.random() * 20) + 1),
            y: Math.floor((Math.random() * 20) + 1)
        }
        for (var i = 0; i > this.snake.length; i++) {
            // 获取刚创建蛇的时候,蛇上每个点的位置,再和食物的位置进行比较
            var snakeX = this.snake[i].x;
            var snakeY = this.snake[i].y;
            // 如果食物的位置出现在蛇的身上,则重新生成
            if (this.food.x === snakeX && this.food.y === snakeY || this.food.y === snakeY && this.food.x === snakeX) {
                this.food.x = Math.floor((Math.random() * 20) + 1);
                this.food.y = Math.floor((Math.random() * 20) + 1);
            }
        }
    },
    // 检查是否碰壁
    checkCollision(x, y, array) {
        for(var i = 0; i < array.length; i++) {
            if(array[i].x === x && array[i].y === y)
            return true;
        }
        return false;
    },
    // 鼠标点击绑定的事件
    onStartGame(direct){
        // 设置游戏初始状态,控制text标签的显示
        this.gameOver = false
        // 通过对应的参数,获取对应direct的字段
        if (direct == 1) {
            this.direction = 'up'
        } else if (direct == 2) {
            this.direction = 'left'
        } else if (direct == 3) {
            this.direction = 'down'
        } else if (direct == 4) {
            this.direction = 'right'
        }
        // 调用绘图方法
        this.paint()
        // 设置蛇的移动间隔时间,也可以理解为绘图的时间间隔
        if (this.interval == null) {
            // setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式
            this.interval = setInterval(this.paint, 250);
        }
    },
    // 每次移动刷新的操作,即帧画面创建和渲染的流程
    paint() {
        // 调用画背景
        this.drawArea()
        // 获得蛇头的位置的初始坐标
        var snakeX = this.snake[0].x;
        var snakeY = this.snake[0].y;
        // 移动操作,更新数据
        if (this.direction == 'right') {
            snakeX++;
        }
        else if (this.direction == 'left') {
            snakeX--;
        }
        else if (this.direction == 'up') {
            snakeY--;
        } else if (this.direction == 'down') {
            snakeY++;
        }
        // 反向移动或碰撞壁的时候,游戏失败,重启游戏
        if (snakeX == -1 || snakeX == this.w / this.snakeSize || snakeY == -1 || snakeY == this.h / this.snakeSize || this.checkCollision(snakeX, snakeY, this.snake)) {
            clearInterval(this.interval);
            this.interval = null
            this.restart()
            return;
        }
        //  判断是否吃到食物
        if(snakeX == this.food.x && snakeY == this.food.y) {
            // 吃到食物
            // 将食物的位置记录下来
            this.tail = {x: snakeX, y: snakeY};
            // 分数加5
            this.score = this.score+5;
            // 再创建食物
            this.createFood();
        } else {
            // 没吃到食物
            // 去掉数组最后的元素并返回,相当于删除蛇尾
            this.tail = this.snake.pop();
            // 将移动更新后蛇头的位置加到tail中
            this.tail.x = snakeX;
            this.tail.y = snakeY;
        }
        // unshift()方法可向数组的开头添加一个或多个元素
        // 将更新后的节点添加蛇头
        this.snake.unshift(this.tail);
        // 渲染每个蛇身格子的位置
        for(var i = 0; i < this.snake.length; i++) {
            this.bodySnake(this.snake[i].x, this.snake[i].y);
        }
        // 渲染食物的位置
        this.cookie(this.food.x, this.food.y);
    },
    // 重启操作
    restart() {
        this.drawArea()
        this.drawSnake()
        this.createFood()
        this.gameOver = true
        this.score = 0
    },
}

【6】添加图片

这一步本来是要创建好项目就要做的(忘记写了)。

图片放在common文件下。

用到的图片我也一起放下面(省的你们找了)。

 

  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南京在逃大学生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值