import java.util.*;
public class TwoZeroFourEight { // 游戏棋盘大小 private int boardSize; // 游戏棋盘 private int[][] board; // 随机数生成器 private Random rand;
// 游戏初始化
public TwoZeroFourEight(int boardSize) {
this.boardSize = boardSize;
this.board = new int[boardSize][boardSize];
this.rand = new Random();
addTile();
addTile();
printBoard();
}
// 在棋盘的空白位置上添加一个数(2 或 4)
private void addTile() {
List<int[]> emptyTiles = getEmptyTiles();
if (emptyTiles.size() > 0) {
int[] tile = emptyTiles.get(rand.nextInt(emptyTiles.size()));
board[tile[0]][tile[1]] = rand.nextInt(10) == 0 ? 4 : 2;
}
}
// 打印游戏棋盘
public void printBoard() {
System.out.println(" Score: " + getScore() + "\n");
for (int row = 0; row < boardSize; row++) {
System.out.print("| ");
for (int col = 0; col < boardSize; col++) {
System.out.print(String.format("%-5d", board[row][col]));
System.out.print("| ");
}
System.out.println("\n");
}
}
// 获取所有空白的方块
private List<int[]> getEmptyTiles() {
List<int[]> emptyTiles = new ArrayList<>();
for (int row = 0; row < boardSize; row++) {
for (int col = 0; col < boardSize; col++) {
if (board[row][col] == 0) {
emptyTiles.add(new int[] {row, col});
}
}
}
return emptyTiles;
}
// 获取当前分数
public int getScore() {
int score = 0;
for (int row = 0; row < boardSize; row++) {
for (int col = 0; col < boardSize; col++) {
score += board[row][col];
}
}
return score;
}
// 判断是否游戏结束
public boolean isGameOver() {
if (getEmptyTiles().size() > 0) {
return false;
}
for (int row = 0; row < boardSize; row++) {
for (int col = 0; col < boardSize; col++) {
if (row < boardSize - 1 && board[row][col] == board[row + 1][col]) {
return false;
}
if (col < boardSize - 1 && board[row][col] == board[row][col + 1]) {
return false;
}
}
}
return true;
}
// 向左移动
public void moveLeft() {
boolean hasMoved = false;
for (int row = 0; row < boardSize; row++) {
int[] line = board[row];
for (int col = 0; col < boardSize - 1; col++) {
if (line[col] == 0) {
continue;
}
for (int search = col + 1; search < boardSize; search++) {
if (line[search] == 0) {
continue;
}
if (line[col] == line[search]) {
line[col] *= 2;
line[search] = 0;
hasMoved = true;
}
break;
}
}
int[] newLine = new int[boardSize];
int index = 0;
for (int value : line) {
if (value != 0) {
newLine[index++] = value;
}
}
board[row] = newLine;
while (index < boardSize) {
newLine[index++] = 0;
}
}
if (hasMoved) {
addTile();
}
printBoard();
}
// 继续实现向上、向右和向下移动的方法
// 主程序入口
public static void main(String[] args) {
TwoZeroFourEight game = new TwoZeroFourEight(4);
Scanner scanner = new Scanner(System.in);
while (!game.isGameOver()) {
System.out.println("请输入移动方向:");
String input = scanner.nextLine();
switch (input) {
case "a":
game.moveLeft();
break;
// 继续实现其他移动方向的操作
default:
System.out.println("无效的输入,请重新输入!");
break;
}
}
System.out.println("游戏结束,分数为:" + game.getScore());
scanner.close();
}
}
标签:boardSize,int,2048,++,board,col,row From: https://blog.51cto.com/u_16096459/6342796