Battleship/src/battleship/model/Game.java

110 lines
3.2 KiB
Java
Raw Normal View History

package battleship.model;
import battleship.model.player.Player;
import battleship.utils.Pair;
import battleship.utils.Triplet;
2021-05-01 18:45:18 +02:00
import battleship.view.View;
2021-04-10 12:42:15 +02:00
2021-05-01 18:45:18 +02:00
/**
* Main game class
*/
public class Game {
public Player[] players;
public Player currentPlayer;
public Game(Player[] players) {
this.players = players;
this.currentPlayer = players[0];
players[0].setId(1);
players[1].setId(2);
}
public Player getCurrentPlayer(){
return this.currentPlayer;
}
public Player getOtherPlayer() {
return this.currentPlayer == players[0] ? players[1] : players[0];
}
public Player getOtherPlayer(Player player) {
return this.currentPlayer == player ? getOtherPlayer() : currentPlayer;
}
public void changeCurrentPlayer(){
currentPlayer = getOtherPlayer();
}
2021-05-01 18:45:18 +02:00
/**
* Update ship to know if they're drowned
*/
public void checkDrownedShips(){
Player otherPlayer = getOtherPlayer();
for(Ship ship : otherPlayer.getShips()){
if(!ship.isDrown())
ship.updateIsDrown(currentPlayer);
}
}
2021-05-01 18:45:18 +02:00
/**
* @return player 1 if player 2' ships are drowned, or player 2 if player1' ships are drowned, null otherwise
*/
public Player getWinner(){
Ship remainingShip = players[0].getShips().parallelStream().filter(ship -> !ship.isDrown()).findFirst().orElse(null);
if(remainingShip == null)
return players[1];
remainingShip = players[1].getShips().parallelStream().filter(ship -> !ship.isDrown()).findFirst().orElse(null);
if(remainingShip == null)
return players[1];
return null;
}
2021-05-01 18:45:18 +02:00
/**
* Play the selected move from current player in grid
* @param move selected player move
*/
public void move(Pair<Integer,Integer> move){
boolean bool = false;
Player otherPlayer = getOtherPlayer();
for (Ship ship : otherPlayer.getShips()) {
for(Pair<Integer,Integer> coords : ship.getFullCoords()){
if ((coords.getRight().equals(move.getRight())) && (coords.getLeft().equals(move.getLeft()))) {
bool = true;
break;
}
}
if(bool)
break;
}
currentPlayer.addMove(new Triplet<>(move, bool));
}
2021-05-01 18:45:18 +02:00
/**
* game loop
* @param view can be {@link battleship.view.Terminal} or {@link battleship.view.Window}
*/
public void Play(View view) {
2021-04-27 14:50:47 +02:00
try {
view.setShips(players[0]);
view.setShips(players[1]);
Player winner = null;
while (winner == null) {
System.out.println("Au tour du joueur " + currentPlayer.getId());
view.displayBoard();
move(view.chooseMove(currentPlayer));
checkDrownedShips();
changeCurrentPlayer();
winner = getWinner();
}
view.displayWinner(winner);
2021-04-27 14:50:47 +02:00
} catch (InterruptedException e) {
System.out.println("Une erreur est survenue");
e.printStackTrace();
System.exit(1);
}
}
}