I decided to make the 2048 Command Line Edition, but I had problems getting the correct tile movement ...
My current structure is that the board is a 2d (4x4) array of ints. When the input is received, it will try to push each plate in this direction (ignoring the tiles with a value of 0) if it sees the change that it will start (because the tiles in the bottom row should go all the way up, not just one step). However, a side effect of this is the following problem:
[2] [2] [4] using the command β should give [0] [4] [4], but since it starts, the program will be able to combine 4 and 4 and get [0] [0] [8] download Another difficult problem is [4] [4] [8] [8], which should give [0] [0] [8] [16], so I can't just stop after the merge.
Below is my processCommand function. It takes the board and input (βd,β βu,β βl,β or βr.β If a game notices a game, it will enter a βgameoverβ as input). This is not very beautiful, and I tried to make a single loop to move the tiles (for example, if you write "l", then the horizontal value will be -1, and if you write "r", it will be 1, and then I will move the tiles horizontal horizon, but I could not do this work).
Any ideas on how to do this (and criticism of my programming) would be greatly appreciated!
func processCommand(board [][]int, input string) {
board_new := board
switch input {
case "d":
for i := 0; i < height - 1; i++ {
for j := 0; j < width; j++ {
if board[i][j] == 0 {
continue
}
if board[i + 1][j] == 0 || board[i + 1][j] == board[i][j] {
board_new[i + 1][j] = board[i + 1][j] + board[i][j]
board_new[i][j] = 0
i = 0
j = 0
change = true
}
}
}
case "u":
for i := 1; i < height; i++ {
for j := 0; j < width; j++ {
if board[i][j] == 0 {
continue
}
if board[i - 1][j] == 0 || board[i - 1][j] == board[i][j] {
board_new[i - 1][j] = board[i - 1][j] + board[i][j]
board_new[i][j] = 0
i = 1
j = 0
change = true
}
}
}
case "l":
for i := 0; i < height; i++ {
for j := 1; j < width; j++ {
if board[i][j] == 0 {
continue
}
if board[i][j - 1] == 0 || board[i][j - 1] == board[i][j] {
board_new[i][j - 1] = board[i][j - 1] + board[i][j]
board_new[i][j] = 0
i = 0
j = 1
change = true
}
}
}
case "r":
for i := 0; i < height; i++ {
for j := 0; j < width - 1; j++ {
if board[i][j] == 0 {
continue
}
if board[i][j + 1] == 0 || board[i][j + 1] == board[i][j] {
board_new[i][j + 1] = board[i][j + 1] + board[i][j]
board_new[i][j] = 0
i = 0
j = 0
change = true
}
}
}
case "gameover":
gameOver = true
default:
processCommand(board, input)
}
board = board_new
}
source
share