2048: Difference between revisions

97 bytes removed ,  7 years ago
formatting
(formatting)
Line 2,195:
 
<lang kotlin>
package com.sbg.g2048.stateless
 
import java.io.BufferedReader
import java.io.InputStreamReader
Line 2,216 ⟶ 2,214:
 
fun run2048(grid: Array<Array<Int>>): String {
if (isGridSolved(grid)) return positiveGameOverMessage
else if (isGridFull(grid)) return negativeGameOverMessage
 
Line 2,226 ⟶ 2,224:
 
fun isGridSolved(grid: Array<Array<Int>>): Boolean = grid.any { row -> row.contains(2048) }
fun isGridFull(grid: Array<Array<Int>>): Boolean = grid.all { row -> !row.contains(0) }
 
fun spawnNumber(grid: Array<Array<Int>>): Array<Array<Int>> {
val coordinates = locateSpawnCoordinates(grid)
val number = generateNumber()
Line 2,243 ⟶ 2,241:
}
 
return emptyCells[(Math.random() * (emptyCells.size() - 1)).toInt()]
}
 
fun generateNumber(): Int = if (Math.random() > 0.10) 2 else 4
 
Line 2,253 ⟶ 2,252:
}
 
fun waitForValidInput(): String {
val input = waitForInput()
return if (isValidInput(input)) input else waitForValidInput()
}
 
fun isValidInput(input: String): Boolean = arrayOf("a", "s", "d", "w").contains(input)
 
fun waitForInput(): String {
val br = BufferedReader(InputStreamReader(System.`in`));
println("Direction? ")
return br.readLine()
Line 2,274:
 
fun shiftCellsLeft(grid: Array<Array<Int>>): Array<Array<Int>> =
grid.map { row -> grid.map(::mergeAndOrganizeCells(row) }.toTypedArray()
 
fun shiftCellsRight(grid: Array<Array<Int>>): Array<Array<Int>> =
grid.map { row -> mergeAndOrganizeCells(row.reversed().toTypedArray()).reversed().toTypedArray() }.toTypedArray()
 
fun shiftCellsUp(grid: Array<Array<Int>>): Array<Array<Int>> {
Line 2,289:
val updatedGrid = grid.copyOf()
 
rows.map(::mergeAndOrganizeCells).forEachIndexed { rowIdx, row ->
mergeAndOrganizeCells(row)
}.forEachIndexed { rowIdx, row ->
updatedGrid[0][rowIdx] = row[0]
updatedGrid[1][rowIdx] = row[1]
Line 2,311 ⟶ 2,309:
val updatedGrid = grid.copyOf()
 
rows.map(::mergeAndOrganizeCells).forEachIndexed { rowIdx, row ->
mergeAndOrganizeCells(row)
}.forEachIndexed { rowIdx, row ->
updatedGrid[3][rowIdx] = row[0]
updatedGrid[2][rowIdx] = row[1]
Line 2,340 ⟶ 2,336:
} else {
return if (row[idxToCompare] != 0) merge(row, idxToMatch + 1, idxToMatch + 2)
else merge(row, idxToMatch, idxToCompare + 1)
}
}