I've written a program and it needs a review by skilled programmers.
The programs goal is to change 0-s to X and X-s to 0. The rule is X or O can move only to an empty place and x or o can only "jump" over one X or O. Program looks like:
------------------
|x|x|x|x| |o|o|o|o|
------------------
User input
move from? (0-8)
3
move to? (0-8)
4
Output
-----------------
|x|x|x| |x|o|o|o|o|
------------------
package tornasz;
import java.util.Scanner;
public class Tornasz {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] table = {'x', 'x', 'x', 'x', ' ', 'o', 'o', 'o', 'o'};
int [] move = new int[2];
int result;
int counter = 0;
do
{
drawPlayfield(table, counter);
move = getValidMove(sc,table,move);
makeMove(table,move);
result = checkWin(table);
counter ++;
}
while (result == 0);
drawPlayfield(table,counter);
displayWinner(result);
}
public static void drawPlayfield(char [] table, int counter){
System.out.println("Lépésszám: "+counter);
System.out.println("------------------");
System.out.println("|"+table[0]+"|"+table[1]+"|"+table[2]+
"|"+table[3]+"|"+table[4]+"|"+table[5]+"|"+table[6]+"|"+table[7]
+"|"+table[8]+"|");
System.out.println("------------------");
counter++;
}
public static int [] getValidMove(Scanner sc, char [] table, int [] move)
{
System.out.println("Melyik mezővel lépsz? (0-8)");
int start = sc.nextInt();
if (start == -1)
{
System.exit(0);
}
System.out.println("Melyik mezőre lépsz? (0-8)");
int destination = sc.nextInt();
if (destination == -1)
{
System.exit(0);
}
while (start < 0 || start > 8 || destination < 0 || destination > 8)
{
System.out.println("Érvénytelen lépés!");
System.out.println("Melyik mezővel lépsz? (0-8)");
start = sc.nextInt();
if (start == -1)
{
System.exit(0);
}
System.out.println("Melyik mezőre lépsz? (0-8)");
destination = sc.nextInt();
if (destination == -1)
{
System.exit(0);
}
}
while (table[destination] != ' ')
{
System.out.println("Érvénytelen lépés!");
System.out.println("Melyik mezővel lépsz? (0-8)");
start = sc.nextInt();
System.out.println("Melyik mezőre lépsz? (0-8)");
destination = sc.nextInt();
}
int [] movement = new int[2];
movement[0] = start;
movement[1] = destination;
return movement;
}
public static void makeMove(char [] table, int [] move)
{
table[move[1]] = table[move[0]];
table[move[0]] = ' ';
}
public static int checkWin(char [] table)
{
if (table[0] == 'o' && table[1] == 'o' && table[2] == 'o' &&
table[3] == 'o' && table[4] == ' ' && table[5] == 'x' &&
table[6] == 'x' && table[7] == 'x' && table[8] == 'x')
{
return 1;
}
return 0;
}
public static void displayWinner(int result)
{
if (result == 1)
{
System.out.println("Gratulálok, vége a játéknak!");
}
}
}
Now I only need to set the movement rules. I think it will be an another method with boolean.
makeMoveroutine can only place "x" and not "o" into the table, anyway it's never invoked. I'm deleting my answer and voting to migrate the question to StackOverflow. \$\endgroup\$