ZBLOG

golang 编写一个2048小游戏

以下是一个简单的2048游戏的实现,使用Go语言和命令行界面:

”` package main

import (

"fmt"
"math/rand"
"time"

)

type Game struct {

board  [4][4]int
score  int
moved  bool
status string

}

func NewGame() *Game {

g := &Game{}
g.AddTile()
g.AddTile()
return g

}

func (g *Game) AddTile() {

rand.Seed(time.Now().UnixNano())
val := 2
if rand.Intn(10) == 0 {
	val = 4
}
for i := 0; i < 16; i++ {
	row, col := rand.Intn(4), rand.Intn(4)
	if g.board[row][col] == 0 {
		g.board[row][col] = val
		return
	}
}

}

func (g *Game) Draw() {

fmt.Printf("Score: %d\n", g.score)
for row := range g.board {
	for col := range g.board[row] {
		tile := g.board[row][col]
		switch tile {
		case 0:
			fmt.Print(".")
		default:
			fmt.Print(tile)
		}
		fmt.Print("\t")
	}
	fmt.Println()
}

}

func (g *Game) MoveLeft() bool {

moved := false
for row := range g.board {
	for col := range g.board[row] {

		nCol, nVal := col, g.board[row][col]

		for nCol > 0 && g.board[row][nCol-1] == 0 { // move left until hit the wall or another number 
			g.board[row][nCol-1], g.board[row][nCol] = nVal, 0
			nCol--
			moved = true
		}

		if nCol > 0 && g.board[row][nCol-1] == nVal && !g.merged[row][nCol-1] { // merge with the left number
			g.board[row][nCol-1], g.board[row][col] = nVal*2, 0
			g.score += nVal * 2
			moved = true
		} else {
			g.board[row][nCol], g.board[row][col] = nVal, 0 // move to the furthest left position 
		}
	}
}
return moved

}

func (g *Game) MoveRight() bool {

// TODO: Implement this function using similar logic as MoveLeft()
return false

}

func (g *Game) MoveUp() bool {

// TODO: Implement this function using similar logic as MoveLeft()
return false

}

func (g *Game) MoveDown() bool {

// TODO: Implement this function using similar logic as MoveLeft()
return false

}

func (g *Game) IsGameOver() bool {

for row := range g.board {
	for col := range g.board[row] {
		if g.board[row][col] == 0 { // found an empty tile 
			return false // not over yet 
		}
		if col < len(g.board)-1 && g.board[row][col] == g.board[row][col+1] { // found a mergeable pair horizontally 
			return false // not over yet 
		}
		if row < len(g.board)-1 && g.board[row][col] == g.board[row+1][col] { // found a mergeable pair vertically 
			return

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=3556

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?