国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

目錄
游戲演示
代碼結(jié)構(gòu)
渲染蛇身
控制蛇的方向
給貪吃蛇添加音效
結(jié)語
首頁 web前端 uni-app 聊聊如何利用uniapp開發(fā)一個貪吃蛇小游戲!

聊聊如何利用uniapp開發(fā)一個貪吃蛇小游戲!

May 20, 2022 pm 07:56 PM
uni-app

如何利用uniapp開發(fā)一個貪吃蛇小游戲?下面本篇文章就手把手帶大家在uniapp中實現(xiàn)貪吃蛇小游戲,希望對大家有所幫助!

聊聊如何利用uniapp開發(fā)一個貪吃蛇小游戲!

第一次玩貪吃蛇還隱約記得是??后父親給我玩的第一個游戲

該小游戲使用uniapp開發(fā)

前置詳細內(nèi)容就不細說了詳細看:https://juejin.cn/post/7085727363547283469#heading-14

游戲演示

1.gif

代碼結(jié)構(gòu)

詳細代碼結(jié)構(gòu)如果需要請到github查看

主要分為:開始游戲、地塊、蛇身、蟲子、污染地塊,游戲音效

<template>
	<view ref="body" class="content">
		<view>蛇蛇目前:{{snakes.length}}米長</view>
		<view class="game-field">
                <!-- 地面板塊 -->
		  <view class="block"  v-for="(x, i) in blocks" :key="i"></view>
		</view>
                    <view v-show="!started || ended" class="game-board-wrap">
                        <view v-show="!started" class="game-board">
                            <view class="title">選擇游戲難度</view>
                            <radio-group name="radio" @change="bindLevelChange">
                                <label class="label">
                                    <radio value="1" :checked="level==1" /><text>簡單模式</text>
                                </label>
                                <label class="label">
                                    <radio value="2" :checked="level==2" /><text>正常模式</text>
                                </label>
                                <label class="label">
                                    <radio value="3" :checked="level==3" /><text>困難模式</text>
                                </label>
                                <label class="label">
                                    <radio value="4" :checked="level==4" /><text>地獄模式</text>
                                </label>
                            </radio-group>
                            <button type="primary" @click="start">開始游戲</button>
                        </view>
			<view v-show="ended" class="settle-board">
                            <view class="title">游戲結(jié)束</view>
                            <view class="result">您的蛇蛇達到了{{snakes.length}}米</view>
                            <view class="btns">
                                <button type="primary" @click="reStart">再次挑戰(zhàn)</button>
                                <button type="primary" plain @click="rePick">重選難度</button>
                            </view>
			</view>
		</view>
	</view>
</template>
<script>
export default {
    data() {
            return {
                blocks: [], // 板塊
                worms: [], // 蟲子
                snakes: [0, 1, 2, 3], // 蛇身
                direction: "right", // 蛇移動方向
            };
    },
    onLoad() {
        this.initGame();
    },
    methods: {
        initGame() {
            this.blocks = new Array(100).fill(0); // 生成100個地面板塊
            this.worms = [Math.floor(Math.random() * 96) + 4]; // 隨機生成蟲子
            this.snakes = [0, 1, 2, 3]; // 初始化蛇身位置
        }
    }
}
</script>

渲染蛇身

給我們的蛇穿上他的外衣 蛇身的渲染根據(jù)snakes(里邊放著蛇的身體)來匹配地面板塊的索引 從而找到對應(yīng)的格格并修改背景圖來渲染蛇身 蛇頭和蛇尾就是取snakes第0位和最后一位 并找到對應(yīng)的格格修改當(dāng)前背景圖

<template>
    <view class="game-field">
        <view class="block" :style="`background-image: ${bg(x, i)}" v-for="(x, i) in blocks" :key="i">
        </view>
    </view>
</template>
<script>
import worm from "worm.png";
import snakeBody from "snake_body.png";
import snakeHead from "snake_head.png";
import snakeTail from "snake_tail.png";
import polluteBlock from "pollute.png";
import wormBoom from "worm_4.png";
export default {
    methods: {
        bg(type, index) {
            let bg = "";
            switch (type) {
                case 0: // 地板
                    bg = "unset";
                    break;
                case 1: // 蟲子
                    if (this.boom) {
                            bg = `url(${wormBoom})`;
                    } else {
                            bg = `url(${worm})`;
                    }
                    break;
                case 2: // 蛇
                    let head = this.snakes[this.snakes.length - 1];
                    let tail = this.snakes[0];
                    if (index === head) {
                            bg = `url(${snakeHead})`;
                    } else if (index === tail) {
                            bg = `url(${snakeTail})`;
                    } else {
                            bg = `url(${snakeBody})`;
                    }
                    break;
                case 3: // 污染的地塊
                    bg = `url(${polluteBlock})`;
                    break;
            }
            return bg;
        },
    }
}
</scipt>

控制蛇的方向

控制蛇的方向pc端我們通過監(jiān)聽鍵盤事件找到對應(yīng)的鍵盤鍵的編碼上下左右來改變蛇的方向 而手機端我們通過touch時間手指觸摸點及滑動點的XY軸值來判斷蛇的方向

<template>
<view ref="body" class="content" @keyup.left="bindLeft" @keyup.right="bindRight" @keyup.down="bindDown"
@keyup.up="bindUp" @touchstart="handleTouchStart" @touchmove="handleTouchMove">
    <view>蛇蛇目前:{{snakes.length}}米長</view>
    <view class="game-field">
        <view class="block" :style="`background-image: ${bg(x, i)}; v-for="(x, i) in blocks" :key="i"></view>
    </view>
</view>
</template>
<script>
    export default {
        data(){
            return {
                direction: "right",
                started: false, // 游戲開始了
                ended: false, // 游戲結(jié)束了
                level: 1, // 游戲難度
                lastX: 0,
                lastY: 0,
            }
        },
        onLoad() {
            this.initGame();
        },
        methods:{
            initGame() {
                this.blocks = new Array(100).fill(0); // 生成100個地面板塊
                this.worms = [Math.floor(Math.random() * 96) + 4]; // 隨機生成蟲子
                this.snakes = [0, 1, 2, 3]; // 初始化蛇身位置
                document.onkeydown = (e) => {
                    switch (e.keyCode) { // 獲取當(dāng)前按下鍵盤鍵的編碼
                        case 37: // 按下左箭頭鍵
                            this.bindLeft();
                            break;
                        case 39: // 按下右箭頭鍵
                            this.bindRight();
                            break;
                        case 38: // 按下上箭頭鍵
                            if (!this.started) {
                                    this.level--;
                            } else {
                                    this.bindUp();
                            }
                            break;
                        case 40: // 按下下箭頭鍵
                            if (!this.started) {
                                    this.level++;
                            } else {
                                    this.bindDown();
                            }
                            break;
                    }
                }
            },
            handleTouchStart(e) {
                // 手指開始位置
                this.lastX = e.touches[0].pageX;
                this.lastY = e.touches[0].pageY;
            },
            handleTouchMove(e) {
                let lastX = e.touches[0].pageX; // 移動的x軸坐標(biāo)
                let lastY = e.touches[0].pageY; // 移動的y軸坐標(biāo)

                let touchX = lastX - this.lastX;
                let touchY = lastY - this.lastY
                if (Math.abs(touchX) > Math.abs(touchY)) {
                if (touchX < 0) {
                    if(this.direction === "right") return;
                    this.direction = &#39;left&#39;
                    } else if (touchX > 0) {
                        if(this.direction === "left") return;
                        this.direction = &#39;right&#39;
                    }
                } else {
                    if (touchY < 0) {
                        if(this.direction === "down") return;
                        this.direction = &#39;up&#39;
                    } else if (touchY > 0) {
                        if(this.direction === "up") return;
                        this.direction = &#39;down&#39;
                    }
                }
                this.lastX = lastX;
                this.lastY = lastY;
            },
            bindUp() {
                if (this.direction === "down") return;
                this.direction = "up";
            },
            bindDown() {
                if (this.direction === "up") return;
                this.direction = "down";
            },
            bindLeft() {
                if (this.direction === "right") return;
                this.direction = "left";
            },
            bindRight() {
                if (this.direction === "left") return;
                this.direction = "right";
            },
        }
    }
</script>

給貪吃蛇添加音效

添加游戲音效游戲代入感就強了很多 現(xiàn)在我們要給蛇加上背景音樂、點擊交互音樂、蛇隔兒屁的音樂、蛇吃掉食物的音樂、蟲子爆炸倒計時的音樂和蟲子爆炸的音樂

先給添加上背景音樂 總有刁民可以玩到地圖滿為止 背景音樂的話要loop播放 我們只需要 使用uni.createInnerAudioContext來創(chuàng)建并返回內(nèi)部 audio 上下文 innerAudioContext 對象 拿到音樂的路徑并且設(shè)置自動播放

<script>
import bgm from &#39;bgm.mp3&#39;;
export default {
    data(){
        return {
            bgmInnerAudioContext:null,
        }
    },
    methods:{
        start() { // 開始游戲
            this.initGame();
            this.handleBgmVoice()
        },
        handleBgmVoice() {
            // 背景音樂
            this.bgmInnerAudioContext = uni.createInnerAudioContext() // 創(chuàng)建上下文
            this.bgmInnerAudioContext.autoplay = true; // 自動播放
            this.bgmInnerAudioContext.src= bgm; // 音頻地址
            this.bgmInnerAudioContext.loop = true; // 循環(huán)播放
        }
    }
}
<script>

背景音樂確實響起來了 蛇gameover后還一直響 頓時我聽著就不耐煩 這時我們在蛇gameover后暫停背景音樂pause音樂會暫停而不會清楚

<script>
import bgm from &#39;bgm.mp3&#39;;
export default {
    data(){
        return {
            bgmInnerAudioContext:null,
        }
    },
    methods:{
        start() { // 開始游戲
            this.initGame();
            this.handleBgmVoice()
        },
        handleBgmVoice() {
            // 背景音樂
            this.bgmInnerAudioContext = uni.createInnerAudioContext() // 創(chuàng)建上下文
            this.bgmInnerAudioContext.autoplay = true; // 自動播放
            this.bgmInnerAudioContext.src= bgm; // 音頻地址
            this.bgmInnerAudioContext.loop = true; // 循環(huán)播放
        }
        checkGame(direction, next) {
            let gameover = false;
            let isSnake = this.snakes.indexOf(next) > -1;
            let isPollute = this.pollutes.indexOf(next) > -1;
            // 撞到蛇和被污染的地塊游戲結(jié)束
            if (isSnake || isPollute) {
                gameover = true;
            }
            // 撞到邊界游戲結(jié)束
            switch (direction) {
                case "up":
                    if (next < 0) {
                            gameover = true;
                    }
                    break;
                case "down":
                    if (next >= 100) {
                            gameover = true;
                    }
                    break;
                case "left":
                    if (next % 10 === 9) {
                            gameover = true;
                    }
                    break;
                case "right":
                    if (next % 10 === 0) {
                            gameover = true;
                    }
                    break;
            }
            return gameover;
        },
        toWards(direction) {
            let gameover = this.checkGame(direction, next);
            if (gameover) {
                this.ended = true;
                this.handleDieVoice()
                this.bgmInnerAudioContext.pause() // 游戲結(jié)束 暫停背景音樂
                clearInterval(this.timer);
                clearInterval(this.boomTimer);
            } else {
                // 游戲沒結(jié)束
                this.snakes.push(next);
                let nextType = this.blocks[next];
                this.blocks[next] = 2;
                // 如果是空白格
                if (nextType === 0) {
                    this.snakes.shift();
                } else {
                    // 如果是蟲子格
                    this.handleEatVoice() // 吃掉蟲子后的音樂
                    this.worms = this.worms.filter((x) => x !== next);
                    let nextWorm = this.createWorm();
                    this.worms.push(nextWorm);
                }
                this.blocks[tail] = 0;
                this.paint();
            }
        },
    }
}
<script>

首個音樂添加成功其他的也就簡單多了 蟲子爆炸倒計時也需要爆炸或者gameover后需要清楚倒計時音效stop(下次播放會從頭開始) 剩余的不需要清楚音效和循環(huán)播放 下面附上剩余的代碼

<script>
export default {
    data() {
        return {
             bgmInnerAudioContext:null,
             clockInnerAudioContext:null,
        }
    },
    watch: {
        boomCount(val) {
            if (val === 0) {
                // 超過爆炸時間還沒吃到,則將蟲子格子變成被污染的土地,并且重置爆炸狀態(tài),同時生成一只新的蟲子:
                this.handleExplodeVoice() // 爆炸的音樂
                this.clockInnerAudioContext.stop() // 清楚倒計時音樂
                const boomWorm = this.worms.pop();
                this.pollutes.push(boomWorm);
                this.blocks[boomWorm] = 3; // 被污染的地方我們用3表示
                this.boom = false;
                this.worms.push(this.createWorm());
            }
        }
    },
    methods:{
        // 蛇吃到食物后的聲音
        handleEatVoice() {
            const innerAudioContext = uni.createInnerAudioContext();
            innerAudioContext.autoplay = true;
            innerAudioContext.src = eatVoice;
        },
        // 蟲子污染爆炸后的聲音
        handleExplodeVoice(){
            const innerAudioContext = uni.createInnerAudioContext();
            innerAudioContext.autoplay = true;
            innerAudioContext.src = explodeVoice;
        },
        // 游戲背景音樂
        handleBgmVoice() {
            this.bgmInnerAudioContext = uni.createInnerAudioContext()
            this.bgmInnerAudioContext.autoplay = true;
            this.bgmInnerAudioContext.src= bgm;
            this.bgmInnerAudioContext.loop = true;
        },
        // 按鈕點擊的聲音
        handleClickVoice() {
            const innerAudioContext = uni.createInnerAudioContext()
            innerAudioContext.autoplay = true;
            innerAudioContext.src= click;
        },
        // 爆炸倒計時的聲音
        handleClockVoice() {
            this.clockInnerAudioContext = uni.createInnerAudioContext()
            this.clockInnerAudioContext.autoplay = true;
            this.clockInnerAudioContext.src= clock;
        },
        // 蛇gameover后的聲音
        handleDieVoice() {
            const innerAudioContext = uni.createInnerAudioContext()
            innerAudioContext.autoplay = true;
            innerAudioContext.src= die;
        },
        checkGame(direction, next) {
            let gameover = false;
            let isSnake = this.snakes.indexOf(next) > -1;
            let isPollute = this.pollutes.indexOf(next) > -1;
            // 撞到蛇和被污染的地塊游戲結(jié)束
            if (isSnake || isPollute) {
                gameover = true;
            }
            // 撞到邊界游戲結(jié)束
            switch (direction) {
                case "up":
                    if (next < 0) {
                            gameover = true;
                    }
                    break;
                case "down":
                    if (next >= 100) {
                            gameover = true;
                    }
                    break;
                case "left":
                    if (next % 10 === 9) {
                            gameover = true;
                    }
                    break;
                case "right":
                    if (next % 10 === 0) {
                            gameover = true;
                    }
                    break;
            }
            return gameover;
        },
        paint() {
            this.worms.forEach((x) => {
                this.blocks[x] = 1;
            });
            this.snakes.forEach((x) => {
                this.blocks[x] = 2;
            });
            this.$forceUpdate();
        },
        toWards(direction) {
            let gameover = this.checkGame(direction, next);
            if (gameover) {
                this.ended = true;
                this.handleDieVoice()
                this.bgmInnerAudioContext.pause() // 游戲結(jié)束 暫停背景音樂
                this.clockInnerAudioContext && this.clockInnerAudioContext.stop() // 清楚倒計時音樂
                clearInterval(this.timer);
                clearInterval(this.boomTimer);
            } else {
                // 游戲沒結(jié)束
                this.snakes.push(next);
                let nextType = this.blocks[next];
                this.blocks[next] = 2;
                // 如果是空白格
                if (nextType === 0) {
                    this.snakes.shift();
                } else {
                    // 如果是蟲子格
                    this.handleEatVoice() // 吃掉蟲子后的音樂
                    this.worms = this.worms.filter((x) => x !== next);
                    let nextWorm = this.createWorm();
                    this.worms.push(nextWorm);
                }
                this.blocks[tail] = 0;
                this.paint();
            }
        },
        // 生成下一只蟲子
        createWorm() {
            this.boom = false;
            let blocks = Array.from({
                    length: 100
            }, (v, k) => k);
            // 在不是蛇和被污染的地方生成蟲子
            let restBlocks = blocks.filter(x => this.snakes.indexOf(x) < 0 && this.pollutes.indexOf(x) < 0);
            let worm = restBlocks[Math.floor(Math.random() * restBlocks.length)];
            // 根據(jù)游戲難度,概率產(chǎn)出會爆炸的蟲子:
            this.boom = Math.random() / this.level < 0.05;
            // 生成了新蟲子說明吃到了那個爆炸的蟲子,重置下爆炸
            if (this.boom) {
                this.boomCount = 10;
                this.boomTimer && clearInterval(this.boomTimer);
                this.handleClockVoice()
                this.boomTimer = setInterval(() => {
                        this.boomCount--;
                }, 1000)
            } else {
                this.clockInnerAudioContext && this.clockInnerAudioContext.stop()
                clearInterval(this.boomTimer);
            }
            return worm;
        },
    }
}
<script>

結(jié)語

特別鳴謝@大帥老猿@末世未然 感謝大帥老師的帶隊及指導(dǎo)以及每天的督促,也特別的感謝隊友的幫助及支持

源碼地址:https://github.com/MothWillion/snake_eat_worm

原文地址:https://juejin.cn/post/7087525655478272008

作者:Sophora

推薦:《uniapp教程

以上是聊聊如何利用uniapp開發(fā)一個貪吃蛇小游戲!的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1601
29
PHP教程
1502
276
VSCode中如何開發(fā)uni-app?(教程分享) VSCode中如何開發(fā)uni-app?(教程分享) May 13, 2022 pm 08:11 PM

VSCode中如何開發(fā)uni-app?下面本篇文章給大家分享一下VSCode中開發(fā)uni-app的教程,這可能是最好、最詳細的教程了??靵砜纯?!

利用uniapp開發(fā)一個簡單的地圖導(dǎo)航 利用uniapp開發(fā)一個簡單的地圖導(dǎo)航 Jun 09, 2022 pm 07:46 PM

怎么利用uniapp開發(fā)一個簡單的地圖導(dǎo)航?本篇文章就來為大家提供一個制作簡單地圖的思路,希望對大家有所幫助!

uni-app?vue3接口請求怎么封裝 uni-app?vue3接口請求怎么封裝 May 11, 2023 pm 07:28 PM

uni-app接口,全局方法封裝1.在根目錄創(chuàng)建一個api文件,在api文件夾中創(chuàng)建api.js,baseUrl.js和http.js文件2.baseUrl.js文件代碼exportdefault"https://XXXX.test03.qcw800.com/api/"3.http.js文件代碼exportfunctionhttps(opts,data){lethttpDefaultOpts={url:opts.url,data:data,method:opts.method

手把手帶你開發(fā)一個uni-app日歷插件(并發(fā)布) 手把手帶你開發(fā)一個uni-app日歷插件(并發(fā)布) Jun 30, 2022 pm 08:13 PM

本篇文章手把手帶大家開發(fā)一個uni-app日歷插件,介紹下一款日歷插件是如何從開發(fā)到發(fā)布的,希望對大家有所幫助!

聊聊如何利用uniapp開發(fā)一個貪吃蛇小游戲! 聊聊如何利用uniapp開發(fā)一個貪吃蛇小游戲! May 20, 2022 pm 07:56 PM

如何利用uniapp開發(fā)一個貪吃蛇小游戲?下面本篇文章就手把手帶大家在uniapp中實現(xiàn)貪吃蛇小游戲,希望對大家有所幫助!

實例詳解uniapp如何實現(xiàn)電話錄音功能(附代碼) 實例詳解uniapp如何實現(xiàn)電話錄音功能(附代碼) Jan 05, 2023 pm 04:41 PM

本篇文章給大家?guī)砹岁P(guān)于uniapp的相關(guān)知識,其中主要介紹了怎么用uniapp實現(xiàn)撥打電話并且還能同步錄音的功能,感興趣的朋友一起來看一下吧,希望對大家有幫助。

實例講解uniapp實現(xiàn)多選框的全選功能 實例講解uniapp實現(xiàn)多選框的全選功能 Jun 22, 2022 am 11:57 AM

本篇文章給大家?guī)砹岁P(guān)于uniapp的相關(guān)知識,其中主要整理了實現(xiàn)多選框的全選功能的相關(guān)問題,無法實現(xiàn)全選的原因是動態(tài)修改checkbox的checked字段時,界面上的狀態(tài)能夠?qū)崟r變化,但是無法觸發(fā)checkbox-group的change事件,下面一起來看一下,希望對大家有幫助。

聊聊uniapp的scroll-view下拉加載 聊聊uniapp的scroll-view下拉加載 Jul 14, 2022 pm 09:07 PM

uniapp怎么實現(xiàn)scroll-view下拉加載?下面本篇文章聊聊uniapp微信小程序scroll-view的下拉加載,希望對大家有所幫助!

See all articles