微信小程序为开发者提供了一个强大的平台,可以快速创建各种有趣的应用。在这篇博客中,我们将介绍如何制作一个简单的微信小程序——“飞翔的小鸟”。
项目介绍
“飞翔的小鸟”是一款基于微信小程序的小游戏,玩家需要控制一只小鸟在障碍物之间飞行,避免撞到柱子。游戏难度逐渐增加,挑战玩家的反应速度和操作技巧。
准备工作
注册微信小程序账号:首先,你需要在微信公众平台注册一个小程序账号。 安装开发工具:下载并安装微信开发者工具,用于开发和调试小程序。
创建项目:在微信开发者工具中创建一个新项目,选择合适的目录并填写项目名称。
项目结构
├── miniprogram/
│ ├── images/
│ │ └── bird.png
│ ├── pages/
│ │ └── index/
│ │ ├── index.js
│ │ ├── index.json
│ │ ├── index.wxml
│ │ └── index.wxss
├── app.js
├── app.json
├── app.wxss
代码实现
- app.json
定义小程序的页面路径和全局样式。
json
{
"pages": [
"pages/index/index"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "飞翔的小鸟",
"navigationBarTextStyle": "black"
}
}
2. index.wxml
定义游戏页面的布局。
html
<view class="container">
<canvas canvas-id="gameCanvas" style="width:100%;height:100%"></canvas>
</view>
- index.wxss
设置页面样式。
css
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #70c5ce;
}
4. index.js
实现游戏逻辑。
javascript
const ctx = wx.createCanvasContext('gameCanvas')
Page({
data: {
birdY: 0,
birdSpeed: 0,
gameStart: false,
pillars: [],
score: 0
},
onLoad() {
this.resetGame()
this.draw()
},
resetGame() {
this.setData({
birdY: 150,
birdSpeed: 0,
gameStart: false,
pillars: this.generatePillars(),
score: 0
})
},
generatePillars() {
let pillars = []
for (let i = 0; i < 3; i++) {
pillars.push({
x: 300 + i * 200,
gapY: Math.floor(Math.random() * 100) + 100
})
}
return pillars
},
draw() {
const { birdY, pillars, score } = this.data
ctx.clearRect(0, 0, 375, 667)
// Draw bird
ctx.drawImage('/images/bird.png', 50, birdY, 30, 30)
// Draw pillars
pillars.forEach(pillar => {
ctx.fillRect(pillar.x, 0, 30, pillar.gapY - 50)
ctx.fillRect(pillar.x, pillar.gapY + 50, 30, 667 - pillar.gapY - 50)
})
ctx.setFontSize(20)
ctx.fillText(`Score: ${score}`, 10, 30)
ctx.draw()
},
onTouchStart() {
if (!this.data.gameStart) {
this.setData({ gameStart: true })
this.gameLoop()
}
this.setData({ birdSpeed: -10 })
},
gameLoop() {
if (!this.data.gameStart) return
this.updateBird()
this.updatePillars()
this.checkCollision()
this.draw()
setTimeout(() => this.gameLoop(), 30)
},
updateBird() {
this.setData({
birdY: this.data.birdY + this.data.birdSpeed,
birdSpeed: this.data.birdSpeed + 2
})
},
updatePillars() {
let pillars = this.data.pillars.map(pillar => {
pillar.x -= 5
return pillar
})
if (pillars[0].x < -30) {
pillars.shift()
pillars.push({
x: pillars[pillars.length - 1].x + 200,
gapY: Math.floor(Math.random() * 100) + 100
})
this.setData({ score: this.data.score + 1 })
}
this.setData({ pillars })
},
checkCollision() {
const { birdY, pillars } = this.data
for (let pillar of pillars) {
if (pillar.x < 80 && pillar.x > 20) {
if (birdY < pillar.gapY - 50 || birdY > pillar.gapY + 50) {
this.endGame()
}
}
}
if (birdY < 0 || birdY > 630) {
this.endGame()
}
},
endGame() {
this.setData({ gameStart: false })
wx.showToast({
title: `Game Over! Score: ${this.data.score}`,
icon: 'none'
})
this.resetGame()
}
})