跟著小白一起學(xué)鴻蒙—一起學(xué)做Tetris(下)
作者:王石
現(xiàn)在我們需要設(shè)置高度后增加一個Row的布局,并增加兩個Button控件,以下就是基礎(chǔ)的Hap的page文件:index.ets。
??想了解更多關(guān)于開源的內(nèi)容,請訪問:???
簡介
接著《#跟著小白一起學(xué)鴻蒙# [番外]一起學(xué)做Tetris(上)》我們完善了頁面,增加了左右按鍵和之前方塊顯示,方塊消除。
開發(fā)
1、按鍵增加
之前我們布局一直是只有個Canvas控件,現(xiàn)在我們需要設(shè)置高度后增加一個Row的布局,并增加兩個Button控件,以下就是基礎(chǔ)的Hap的page文件:index.ets。
build() {
Column() {
Column() {
Canvas(this.context)
.width('100%')
.height('100%')
.onClick((ev: ClickEvent) => {
console.info("click!!")
this.doClick()
})
.onTouch((ev) => {
console.info("touch:"+ev.type.toString())
console.info("touch x:"+ev.touches[0].screenX.toString())
console.info("touch y:"+ev.touches[0].screenY.toString())
})
.onReady(() =>{
this.context.imageSmoothingEnabled = false
this.randomType()
this.drawall()
})
}
.height('92%')
.width('100%')
Row() {
Button() { //按鈕控件
Text('左')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.width('20%')
.height('6%')
.backgroundColor('#0D9FFB')
.onClick(() => { //點擊事件
if (this.left > 0) {
this.moveAction -= 1
}
})
Button() { //按鈕控件
Text('右')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.width('20%')
.height('6%')
.backgroundColor('#0D9FFB')
.onClick(() => { //點擊事件
if (this.rightX < 240) {
this.moveAction += 1
}
})
}
}
.width('100%')
.height('100%')
.backgroundColor("#cccccc")
}
2、游戲完善的說明
之前我們的游戲只有布局,方塊顯示和變形,在完善后我們增加了積累方塊的顯示,消除,計分,游戲結(jié)束判斷等。
(1)積累方塊顯示
drawBlockmap() {
let bs = this.blockSize
this.context.fillStyle = 'rgb(250,0,0)'
for (let i=0;i<23;i++) {
for (let j=0;j<9;j++) {
//是否有方塊
if (this.blockmap[i][j] == 1) {
let y = i * this.blockSize
let x = j * this.blockSize
this.context.fillRect(x, y, bs, bs)
this.context.rect(x, y, bs, bs)
console.info("drawBlockmap:"+x.toString()+":"+y.toString())
}
}
this.context.stroke()
console.info("drawBlockmap:"+this.storeBlock.length.toString())
}
}
因為都是畫布畫的,為了重繪已經(jīng)存在的方塊,我們應(yīng)用二維數(shù)組blockmap表示,值為1則有方塊,數(shù)組索引則表示繪制坐標(biāo)位置:
(2)判斷是否到底還是到頂
checkBlockmap() {
if (this.storeBlock.length == 0) {
if (this.slotBottomY >= 660) {
return 1
}
} else {
let coords = this.curBlockShap
let startx = this.slotStartX + this.moveAction * this.blockSize
let starty = this.slotStartY + this.step * this.blockSize
for (let i=0;i<4;i++) {
let x = startx + coords[i][0]*this.blockSize
let y = starty + coords[i][1]*this.blockSize + this.blockSize
for (let k=0;k<22;k++) {
for (let l=0;l<9;l++) {
if (this.blockmap[k][l] == 1) {
let blocky = k * this.blockSize
let blockx = l * this.blockSize
//判斷是否到底
if ((x == blockx && y == blocky) || y > 660) {
//判斷是否到頂
if (y == 210) {
this.context.drawImage( this.gameoverImg,this.startX,this.startY,300,90)
//到頂回2
return 2
}
//到底回1
return 1
}
}
}
}
}
}
return 0
}
先判斷是否到底,到底的同時判斷是否到頂,如果到頂了就是滿了,如果只是到底則表明游戲可以繼續(xù) 。
(3)到底積累方塊
stackBlock() {
let block = []
let coords = this.curBlockShap
let startx = this.slotStartX + this.moveAction * this.blockSize
let starty = this.slotStartY + this.step * this.blockSize
for (let i=0;i<4;i++) {
let x = startx + coords[i][0]*this.blockSize
let y = starty + coords[i][1]*this.blockSize
console.info("stackBlock x:"+x.toString()+"y:"+y.toString())
let indexX = x/this.blockSize
let indexY = y/this.blockSize
this.blockmap[indexY][indexX] = 1
console.info("stackBlock:"+indexX+":"+indexY)
block.push([x,y])
}
this.storeBlock.push(block)
console.info("stackBlock:"+this.storeBlock.length.toString())
}
如果到底了,就用坐標(biāo)計算出 索引,然后在blockmap里標(biāo)識為1,說明此處有方塊,這樣方便后面的繪制的顯示。
(4)清除方塊
cleanBlockmap() {
//檢查是否一行滿了
let needMove = 0
for (let i=22;i>=0;i--) {
let linecnt = 0
for (let j = 8;j >= 0; j--) {
//是否有方塊
if (this.blockmap[i][j] == 1) {
linecnt += 1
}
}
if (linecnt == 9) {
//此行都是方塊,消除,計分
for (let j = 8;j >= 0; j--) {
this.blockmap[i][j] = 0
}
needMove += 1
this.score += 1
} else if (needMove > 0) {
for (let j = 8;j >= 0; j--) {
this.blockmap[i+needMove][j] = this.blockmap[i][j]
this.blockmap[i][j] = 0
}
}
}
}
二維數(shù)組的好處就是方便每行計數(shù)清除,然后從底向上再逐層替換。
(5)繪制每一步
drawStep() {
this.context.clearRect(0,0,this.context.width,this.context.height)
this.step += 1
this.drawBox()
this.drawBlockmap()
this.cleanBlockmap()
this.drawSideBlock()
this.drawBoxBlock()
this.drawScore()
let stepType = this.checkBlockmap()
if ( stepType == 1) {
this.stackBlock()
this.step = 0
this.randomType()
} else if (stepType == 2) {
this.state= 2
this.context.drawImage( this.gameoverImg,this.startX,this.startY,300,90)
}
}
繪制每一步其實就是重繪界面,包括如果游戲結(jié)束顯示game over。
3、游戲邏輯
簡單的小游戲主體游戲邏輯為:等待開始,開始,結(jié)束流程圖如下:
graph LR
timer開始 --> 方塊下落
timer開始 --> click[點擊]
click[點擊] --> 方塊變形
方塊下落 --> |落到底| 能消除 --> 計分 --> 堆積
方塊下落 --> |落到底| 不能消除 --> 堆積
堆積 --> |堆積到頂| 滿了 --> 游戲結(jié)束
堆積 --> |堆積到頂| 未滿 --> 方塊下落
doClick() {
if (this.state == 0) {
this.direction += 1
} else if (this.state == 2) {
this.state = 0
this.score = 0
this.storeBlock = []
this.initMap()
}
}
游戲結(jié)束后需要重新初始化內(nèi)部數(shù)據(jù)。
4、完整邏輯
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private gameoverImg:ImageBitmap = new ImageBitmap("common/images/gameover.png")
private blockType: number = 0
private blockSize: number = 30
private blockShapBasic = [
[[0,0],[0,1],[0,2],[0,3]],
[[0,0],[0,1],[0,2],[1,2]],
[[0,0],[0,1],[1,1],[0,2]],
[[0,0],[0,1],[1,1],[1,2]],
[[0,0],[0,1],[1,0],[1,1]],
]
private blockShap = [
[[0,0],[0,1],[0,2],[0,3]],
[[0,0],[0,1],[0,2],[1,2]],
[[0,0],[0,1],[1,1],[0,2]],
[[0,0],[0,1],[1,1],[1,2]],
[[0,0],[0,1],[1,0],[1,1]],
]
private blockmap = [];
private curBlockShap = []
private storeBlock = []
private sideStartX = 300;
private sideStartY = 150;
private startX = 20
private startY = 300
private slotStartX = 120;
private slotStartY = 150;
private slotBottomY = 150;
private xleft = 0;
private rightX = 0;
private score = 0;
private step = 0;
private direction = 0;
private moveAction = 0;
private state = 0;
aboutToDisappear() {
}
aboutToAppear() {
this.initMap()
this.sleep(1000)
}
initMap() {
for (let i=0;i<23;i++) {
let item = []
for (let j=0;j<9;j++) {
item.push(0)
}
this.blockmap.push(item)
}
}
async sleep(ms: number) {
return new Promise((r) => {
setInterval(() => {
// console.log(this.message)
if (this.state == 0) {
this.drawStep()
}
}, ms)
})
}
doClick() {
if (this.state == 0) {
this.direction += 1
} else if (this.state == 2) {
this.state = 0
this.score = 0
this.storeBlock = []
this.initMap()
}
}
drawBox() {
this.context.lineWidth = 4
this.context.beginPath()
this.context.lineCap = 'butt'
this.context.moveTo(0, 100)
this.context.lineTo(270, 100)
this.context.moveTo(270, 100)
this.context.lineTo(270, 690)
this.context.moveTo(0, 690)
this.context.lineTo(270, 690)
}
setDirection() {
this.curBlockShap = this.blockShap[this.blockType]
if (this.direction > 0) {
for (let i=0;i<4;i++) {
let x = this.curBlockShap[i][0]
this.curBlockShap[i][0] = this.curBlockShap[i][1]
this.curBlockShap[i][1] = x
}
this.direction = 0
}
}
drawSideBlock() {
this.context.fillStyle = 'rgb(250,0,0)'
let bs = this.blockSize
let coords = this.blockShapBasic[this.blockType]
for (let i=0;i<4;i++) {
let x = this.sideStartX + coords[i][0]*this.blockSize
let y = this.sideStartY + coords[i][1]*this.blockSize
this.context.fillRect(x, y, bs, bs)
this.context.rect(x, y, bs, bs)
// console.info("x,y"+x.toString()+":"+y.toString())
}
this.context.stroke()
}
drawBoxBlock() {
let min = 690
let max = 0
this.setDirection()
this.context.fillStyle = 'rgb(250,0,0)'
let bs = this.blockSize
let coords = this.curBlockShap
let startx = this.slotStartX + this.moveAction * this.blockSize
let starty = this.slotStartY + this.step * this.blockSize
for (let i=0;i<4;i++) {
let x = startx + coords[i][0]*this.blockSize
let y = starty + coords[i][1]*this.blockSize
min = min > x ? x:min
max = max < x ? x:max
this.context.fillRect(x, y, bs, bs)
this.context.rect(x, y, bs, bs)
// console.info("x,y"+x.toString()+":"+y.toString())
this.slotBottomY = y
this.xleft = min
this.rightX = max
}
this.context.stroke()
// console.info("min,max"+min.toString()+":"+max.toString())
}
stackBlock() {
let block = []
let coords = this.curBlockShap
let startx = this.slotStartX + this.moveAction * this.blockSize
let starty = this.slotStartY + this.step * this.blockSize
for (let i=0;i<4;i++) {
let x = startx + coords[i][0]*this.blockSize
let y = starty + coords[i][1]*this.blockSize
console.info("stackBlock x:"+x.toString()+"y:"+y.toString())
let indexX = x/this.blockSize
let indexY = y/this.blockSize
this.blockmap[indexY][indexX] = 1
console.info("stackBlock:"+indexX+":"+indexY)
block.push([x,y])
}
this.storeBlock.push(block)
console.info("stackBlock:"+this.storeBlock.length.toString())
}
checkBlockmap() {
if (this.storeBlock.length == 0) {
if (this.slotBottomY >= 660) {
return 1
}
} else {
let coords = this.curBlockShap
let startx = this.slotStartX + this.moveAction * this.blockSize
let starty = this.slotStartY + this.step * this.blockSize
for (let i=0;i<4;i++) {
let x = startx + coords[i][0]*this.blockSize
let y = starty + coords[i][1]*this.blockSize + this.blockSize
for (let k=0;k<22;k++) {
for (let l=0;l<9;l++) {
if (this.blockmap[k][l] == 1) {
let blocky = k * this.blockSize
let blockx = l * this.blockSize
//判斷是否到底
if ((x == blockx && y == blocky) || y > 660) {
//判斷是否到頂
if (y == 210) {
this.context.drawImage( this.gameoverImg,this.startX,this.startY,300,90)
//到頂回2
return 2
}
//到底回1
return 1
}
}
}
}
}
}
return 0
}
cleanBlockmap() {
//檢查是否一行滿了
let needMove = 0
for (let i=22;i>=0;i--) {
let linecnt = 0
for (let j = 8;j >= 0; j--) {
//是否有方塊
if (this.blockmap[i][j] == 1) {
linecnt += 1
}
}
if (linecnt == 9) {
//此行都是方塊,消除,計分
for (let j = 8;j >= 0; j--) {
this.blockmap[i][j] = 0
}
needMove += 1
this.score += 1
} else if (needMove > 0) {
for (let j = 8;j >= 0; j--) {
this.blockmap[i+needMove][j] = this.blockmap[i][j]
this.blockmap[i][j] = 0
}
}
}
}
drawBlockmap() {
let bs = this.blockSize
this.context.fillStyle = 'rgb(250,0,0)'
for (let i=0;i<23;i++) {
for (let j=0;j<9;j++) {
//是否有方塊
if (this.blockmap[i][j] == 1) {
let y = i * this.blockSize
let x = j * this.blockSize
this.context.fillRect(x, y, bs, bs)
this.context.rect(x, y, bs, bs)
console.info("drawBlockmap:"+x.toString()+":"+y.toString())
}
}
this.context.stroke()
console.info("drawBlockmap:"+this.storeBlock.length.toString())
}
}
drawScore() {
this.context.fillStyle = 'rgb(0,0,0)'
this.context.font = '80px sans-serif'
this.context.fillText("Score:"+this.score.toString(), 20, 140)
}
randomType() {
this.blockType = Math.floor(Math.random()*5)
console.info("blocktype:"+this.blockType.toString())
}
drawStep() {
this.context.clearRect(0,0,this.context.width,this.context.height)
this.step += 1
this.drawBox()
this.drawBlockmap()
this.cleanBlockmap()
this.drawSideBlock()
this.drawBoxBlock()
this.drawScore()
let stepType = this.checkBlockmap()
if ( stepType == 1) {
this.stackBlock()
this.step = 0
this.randomType()
} else if (stepType == 2) {
this.state= 2
this.context.drawImage( this.gameoverImg,this.startX,this.startY,300,90)
}
}
drawall() {
this.drawBox()
this.drawSideBlock()
this.drawBoxBlock()
this.drawScore()
}
build() {
Column() {
Column() {
Canvas(this.context)
.width('100%')
.height('100%')
.onClick((ev: ClickEvent) => {
console.info("click!!")
this.doClick()
})
.onTouch((ev) => {
console.info("touch:"+ev.type.toString())
console.info("touch x:"+ev.touches[0].screenX.toString())
console.info("touch y:"+ev.touches[0].screenY.toString())
})
.onReady(() =>{
this.context.imageSmoothingEnabled = false
this.randomType()
this.drawall()
})
}
.height('92%')
.width('100%')
Row() {
Button() { //按鈕控件
Text('左')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.width('20%')
.height('6%')
.backgroundColor('#0D9FFB')
.onClick(() => { //點擊事件
if (this.xleft > 0) {
this.moveAction -= 1
}
})
Button() { //按鈕控件
Text('右')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.width('20%')
.height('6%')
.backgroundColor('#0D9FFB')
.onClick(() => { //點擊事件
if (this.rightX < 240) {
this.moveAction += 1
}
})
}
}
.width('100%')
.height('100%')
.backgroundColor("#cccccc")
}
}
遺留問題:
- 有bug,方塊變形不完整。
- 可實現(xiàn)網(wǎng)絡(luò)對戰(zhàn)(分布式對戰(zhàn))。
總結(jié)
本文主要介紹了小游戲的開發(fā),畫布功能的使用,游戲邏輯,分布式。
責(zé)任編輯:jianghua
來源:
51CTO開源基礎(chǔ)軟件社區(qū)