Skip to content

Instantly share code, notes, and snippets.

@sat0b
Created May 21, 2017 16:44
Show Gist options
  • Select an option

  • Save sat0b/6c4014895b7fb3c35fdf477298cd363f to your computer and use it in GitHub Desktop.

Select an option

Save sat0b/6c4014895b7fb3c35fdf477298cd363f to your computer and use it in GitHub Desktop.
import java.util.Scanner;
class Sanmoku {
private int[][] ban;
private static final int N = 3;
Sanmoku() {
ban = new int[N][N];
}
public void mainLoop() {
Scanner sc = new Scanner(System.in);
int x;
int y;
boolean phase = true;
while (true) {
if (phase)
System.out.println("phase : O");
else
System.out.println("phase : X");
try {
System.out.print("put (vertical axis):");
y = sc.nextInt();
System.out.print("put (horizontal axis):");
x = sc.nextInt();
} catch (NumberFormatException e) {
System.out.println("Wrong input");
continue;
}
if (x < 0 || x > 2 || y < 0 || y > 2) {
System.out.println("Wrong input");
continue;
}
if (ban[y][x] != 0) {
System.out.println("Already exsits");
continue;
}
if (phase) {
ban[y][x] = 1;
phase = false;
} else {
ban[y][x] = 2;
phase = true;
}
printBan();
int result = checkWin();
if (result == 0)
continue;
else if (result == 1) {
System.out.println("Winner: O");
break;
} else if (result == 2) {
System.out.println("Winner: X");
break;
}
}
}
private int checkWin() {
for (int i = 0; i < N; i++) {
for (int j = 1; j <= 2; j++) {
if (ban[i][0] == j && ban[i][1] == j && ban[i][2] == j)
return j;
if (ban[0][i] == j && ban[1][i] == j && ban[2][i] == j)
return j;
if (ban[0][0] == j && ban[1][1] == j && ban[2][2] == j)
return j;
if (ban[0][2] == j && ban[1][1] == j && ban[2][0] == j)
return j;
}
}
return 0;
}
private void printBan() {
String banmen = " 012 \n" +
" +---+ \n";
for (int i = 0; i < N; i++) {
banmen += i + "|";
for (int j = 0; j < N; j++) {
assert 0 <= ban[i][j] && ban[i][j] < 3 :
"0 <= ban[i][j] < 3 expected, but " + ban[i][j];
if (ban[i][j] == 0)
banmen += " ";
else if (ban[i][j] == 1)
banmen += "O";
else if (ban[i][j] == 2)
banmen += "X";
}
banmen += "|\n";
}
banmen += " +---+";
System.out.println(banmen);
}
public static void main(String[] args) {
Sanmoku sanmoku = new Sanmoku();
sanmoku.mainLoop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment