Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize gluttonous Snake Game based on Vue uniapp

Shulou Source: shulou.com Published: 2022-05-31 21:21:09 09月30日 Update

This article introduces the knowledge about "how to realize snake game based on Vue uniapp". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

game demo

代码结构

详细代码结构如果需要请到github查看

蛇蛇目前:{{snakes.length}}米长 选择游戏难度 简单模式 正常模式 困难模式 地狱模式 开始游戏 游戏结束 您的蛇蛇达到了{{snakes.length}}米 再次挑战 重选难度 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]; // 初始化蛇身位置 } }}渲染蛇身

蛇身的渲染根据snakes来匹配地面板块的索引 修改对应的背景图来渲染蛇身

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; }, }}控制蛇的方向

通过监听键盘按键事件和手势来控制蛇的方向

蛇蛇目前:{{snakes.length}}米长

Tags: Plates patterns arrows bugs generation position ground direction difficulty movement code content coordinates more knowledge structure keyboard meter length control practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MySQL Docker Shulou Information Linux