ZBLOG

golang 编写一个2048小游戏

以下是一个简单的 2048 小游戏,使用 Go 编写:

”`go package main

import (

  1. "fmt"
  2. "math/rand"
  3. "time"

)

const (

  1. boardSize = 4
  2. winValue = 2048

)

type direction int

const (

  1. up direction = iota
  2. down
  3. left
  4. right

)

type gameBoard [boardSize][boardSize]int

func (gb *gameBoard) String() string {

  1. var s string
  2. for _, row := range gb {
  3. for _, val := range row {
  4. s += fmt.Sprintf("%4d", val)
  5. }
  6. s += "\n"
  7. }
  8. return s

}

func (gb *gameBoard) addRandomTile() bool {

  1. if gb.isFull() {
  2. return false
  3. }
  4. rand.Seed(time.Now().UnixNano())
  5. for i := 0; i < boardSize*boardSize; i++ {
  6. row, col := rand.Intn(boardSize), rand.Intn(boardSize)
  7. if gb[row][col] == 0 {
  8. gb[row][col] = (rand.Int()%2 + 1) * 2 // either 2 or 4 with equal probability
  9. return true
  10. }
  11. }
  12. panic("unreachable")

}

func (gb *gameBoard) isFull() bool {

  1. for _, row := range gb {
  2. for _, val := range row {
  3. if val == 0 {
  4. return false
  5. }
  6. }
  7. }
  8. return true

}

func (gb *gameBoard) canMove(d direction) bool {

  1. switch d {
  2. case up:
  3. for col := range gb[0] {
  4. for row := boardSize - 1; row > 0; row-- { // start from bottom to avoid redundant checks when shifting tiles up and left.
  5. if gb[row][col] != 0 && (gb[row-1][col] == 0 || gb[row-1][col] == gb[row][col]) {
  6. return true
  7. }
  8. }
  9. }
  10. case down:
  11. for col := range gb[0] {
  12. for row := 0; row < boardSize-1; row++ { // start from top to avoid redundant checks when shifting tiles down and right.
  13. if gb[row][col] != 0 && (gb[row+1][col] == 0 || gb[row+1][col] == gb[row][col]) {
  14. return true
  15. }
  16. }
  17. }
  18. case left:
  19. for row := range gb {
  20. for col := boardSize - 1; col > 0; col-- { // start from right to avoid redundant checks when shifting tiles up and left.
  21. if gb[row][col] != 0 && (gb[row][col-1] == 0 || gb[row][col-1] == gb[row][col]) {
  22. return true
  23. }
  24. }
  25. }
  26. case right:
  27. for row := range gb {
  28. for col := 0; col < boardSize-1; col++ { // start from left to avoid redundant checks when shifting tiles down and right.
  29. if gb[row][col] != 0 && (gb[row][col+1] == 0 || gb[row][col+1] == gb[row][col]) {
  30. return true
  31. }
  32. }
  33. }
  34. default:
  35. panic("invalid direction")
  36. }
  37. return false

}

func (gb *gameBoard) shift(d direction) bool {

  1. var moved bool
  2. switch d {
  3. case up:
  4. for col := range gb[0

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?