Skip to content

Instantly share code, notes, and snippets.

@DevPGSV
Created April 18, 2016 20:37
Show Gist options
  • Save DevPGSV/9a009d6aef61be138ee673553c0b2499 to your computer and use it in GitHub Desktop.
Save DevPGSV/9a009d6aef61be138ee673553c0b2499 to your computer and use it in GitHub Desktop.
ConnectN
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Game {
private Character board[][];
private int dimensions;
private List<Character> players;
private int conditionToWin;
private Character winner = null;
private boolean gameFinished = false;
private Scanner in;
private int turn;
public Game(int dimensions, int conditionToWin, List<Character> players) {
board = new Character[dimensions][dimensions];
this.dimensions = dimensions;
this.players = players;
this.conditionToWin = conditionToWin;
this.in = new Scanner(System.in);
}
private void run() {
this.turn = 0;
Character turnChar;
while (!this.gameFinished) {
System.out.println(boardToString(this.board));
turnChar = this.players.get(this.turn % this.players.size());
System.out.println("Turn for " + turnChar);
System.out.print("Choose coordinate(row col)(ie: 2 2): ");
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
if (this.board[x][y] == null) {
this.board[x][y] = turnChar;
checkStatus();
this.turn++;
} else {
System.out.println("Already occupied! Try again!");
}
}
System.out.println(boardToString(this.board));
System.out.println("Winner: " + this.winner);
}
private void checkStatus() {
int pieces;
Character piece;
// Horizontal:
for (int i = 0; i < this.dimensions; i++) {
pieces = 0;
piece = null;
for (int j = 0; j < this.dimensions; j++) {
if (this.board[i][j] != null) {
if (this.board[i][j].equals(piece)) {
pieces++;
} else {
pieces = 1;
piece = this.board[i][j];
}
}
if (pieces >= this.conditionToWin) {
this.winner = piece;
this.gameFinished = true;
return;
}
}
}
// Vertical
for (int i = 0; i < this.dimensions; i++) {
pieces = 0;
piece = null;
for (int j = 0; j < this.dimensions; j++) {
if (this.board[j][i] != null) {
if (this.board[j][i].equals(piece)) {
pieces++;
} else {
pieces = 1;
piece = this.board[j][i];
}
}
if (pieces >= this.conditionToWin) {
this.winner = piece;
this.gameFinished = true;
return;
}
}
}
// Diagonal1 TODO
// Diagonal2 TODO
}
private String boardToString(Character board[][]) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < this.dimensions; i++) {
for (int j = 0; j < this.dimensions; j++) {
if (this.board[i][j] != null)
b.append(" "+this.board[i][j]+" ");
else
b.append(" - ");
}
b.append("\n");
}
return b.toString();
}
public static void main(String[] args) {
List<Character> p = new ArrayList<Character>();
p.add('X'); p.add('O');
Game m = new Game(3, 3, p);
m.run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment