我试图弄清楚如何使用右、上、下、左移位方法。我觉得我的解决方案应该很有效,如果我说错了或其他什么。
主要的
import java.util.Random;
import java.util.Scanner;
import java.util.*;
public class Runner
{
int[][] board = new int[4][4];
Scanner input = new Scanner(System.in);
public void printWelcomeAndDirections()
{
//instructions
System.out.println("press r to start or restart");
System.out.println("press u to move up");
System.out.println("press d to move down");
System.out.println("press r to move right");
System.out.println("press l to move left");
System.out.println("slides multiples of the same number together to form an even bigger number. Do this till no more combinations are possible or the number 2048 is reached");
}
public void placeBlock()
{
Random rad = new Random();
int a = rad.nextInt(4);
int b = rad.nextInt(4);
boolean tf = false;
while(tf == false)
{
if(board[a][b] == 0)
{
board[a][b] = 2;
tf = true;
}
a = rad.nextInt(4);
b = rad.nextInt(4);
}
}
public void printBoard()
{
int rows=4;
int cols=4;
int boxSize = 4;
String rowdashes = "-----------------";
for(int i = 0; i < board.length; i++)
{
System.out.println(rowdashes);
System.out.print("|");
for(int j = 0; j < board[i].length; j++)
{
String number = "";
if(board[i][j] != 0)
{
number = board[i][j] + "";
}
System.out.print(" " + number + "|");
}
System.out.println();
}
System.out.println(rowdashes);
}
public String getUserChoice()
{
String a = input.nextLine();
return a;
}
public void processUserChoice()
{
if(getUserChoice().equals("u"))
{
slideUp();
}
else if(getUserChoice().equals("d"))
{
slideDown();
}
else if(getUserChoice().equals("l"))
{
slideLeft();
}
else if (getUserChoice().equals("r"))
{
slideRight();
}
}
public boolean slideUp()
{
for(int i = 4; i >= 1; i--)
{
for(int j = 4; j > 0; j--)
{
if(board[i][j] == board[i-1][j])
{
board[i][j] = board[i-1][j] * 2;
board[i-1][j] = 0;
return true;
}
else if(board[i][j] == 0)
{
board[i][j] = board[i-1][j];
return true;
}
}
}
return false;
}
public boolean slideRight()
{
for(int i = 4; i >= 0; i--)
{
for(int j = 4; j >= 1; j--)
{
if(board[i][j] == board[i][j-1])
{
board[i][j] = board[i][j-1] * 2;
board[i][j-1] = 0;
return true;
}
else if(board[i][j] == 0)
{
board[i][j] = board[i][j-1];
return true;
}
}
}
return false;
}
public boolean slideLeft()
{
for(int i = 4; i >= 0; i++)
{
for(int j = 4; j >= 1; j++)
{
if(board[i][j] == board[i][j+1])
{
board[i][j] = board[i][j+1] * 2;
board[i][j+1] = 0;
return true;
}
else if(board[i][j] == 0)
{
board[i][j] = board[i][j+1];
return true;
}
}
}
return false;
}
public boolean slideDown()
{
return false;
}
public int gameover()
{
return 0;
}
}
Test
public class test
{
public static void main(String [] args)
{
Runner a = new Runner();
a.printWelcomeAndDirections();
a.printBoard();
while(a.gameover() == 0)
{
a.placeBlock();
a.printBoard();
a.processUserChoice();
}
}
}
我期待董事会在任何所谓的方向上转移,但事实并非如此。
电路板打印并在 0 所在的位置添加 2。除此之外什么都不做。