@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // remove title
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main_game);

    allDoneLevels = new ArrayList<>();
    AssetManager am = getResources().getAssets();

    final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard);
    final HowdyShadeView howdyShadeView = (HowdyShadeView) this.findViewById(R.id.howdyShadeView);
    final GlowingBoard glowingBoard = (GlowingBoard) this.findViewById(R.id.glowingBoard);
    final HowdyView howdyView = (HowdyView) this.findViewById(R.id.howdyView);
    this.game = new Game();

    boardView.setHowdyShadeView(howdyShadeView);
    boardView.setGlowingBoard(glowingBoard);
    boardView.setHowdyView(howdyView);
    boardView.setOnTouchListener(new BoardGameTouchListener(this));
  }
 @Test
 public void testThatDefaultConstructorForGameBoardInitializesCorrectly() {
   GameBoard gb = new GameBoard();
   Assert.assertEquals(10, gb.getWidth());
   Assert.assertEquals(10, gb.getHeight());
   Assert.assertEquals(5, gb.getNumberOfShips());
 }
  public void loseGame() {
    final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard);

    game.reInitGame();

    boardView.setGame(game);
    boardView.invalidate();
  }
 private boolean completesDiagonal(Player player) {
   Player center = board.getMark(1, 1);
   if (player != center) {
     return false;
   }
   return (board.getMark(0, 0) == center && center == board.getMark(2, 2))
       || (board.getMark(0, 2) == center && center == board.getMark(2, 0));
 }
 @Test
 public void testThatGameBoardIsNotEmptyAfterAddingShips() {
   GameBoard gb = new GameBoard(10, 10, 2);
   ArrayList<Ship> ships = new ArrayList<Ship>();
   ships.add(new Ship(3, 3, 3, true));
   ships.add(new Ship(4, 6, 2, true));
   gb.checkAndPlaceShips(ships, "bottom");
   Assert.assertFalse(gb.isEmpty());
 }
 @Test
 public void testThatMakesSureMoreShipsThanAllowedCanNotBePlaced() {
   GameBoard gb = new GameBoard(10, 10, 2);
   ArrayList<Ship> ships = new ArrayList<Ship>();
   ships.add(new Ship(3, 3, 3, true));
   ships.add(new Ship(4, 6, 2, true));
   ships.add(new Ship(1, 1, 5, false));
   Assert.assertFalse(gb.checkAndPlaceShips(ships, "bottom"));
 }
Beispiel #7
0
 /** Metod som aktiveras när man trycker på nyttspel knappen. */
 public void nyttSpel() {
   // om man trycker på nytt spel så resettas poängen och metoden newGame anropas i klassen viewer
   // och då resettas värdena i viewern. metoden enableButtons i userInput klassen anropas och
   // knapparna av dimmas.
   humPlayer.setScore(0);
   cpuPlayer.setScore(0);
   gameboard.newGame();
   gameboard.enableButtons();
 }
  /** Implement the run() method for the thread */
  public void run() {
    try {
      // Create data input and output streams
      DataInputStream fromPlayer1 = new DataInputStream(player1.getInputStream());
      DataOutputStream toPlayer1 = new DataOutputStream(player1.getOutputStream());
      DataInputStream fromPlayer2 = new DataInputStream(player2.getInputStream());
      DataOutputStream toPlayer2 = new DataOutputStream(player2.getOutputStream());

      // Write anything to notify player 1 to start
      // This is just to let player 1 know to start
      toPlayer1.writeInt(1);

      // Continuously serve the players and determine and report
      // the game status to the players
      while (true) {
        // Receive a move from player 1
        int row = fromPlayer1.readInt();
        int column = fromPlayer1.readInt();
        int yCoordinate = game.insert("[X]", column);

        // Check if Player 1 wins
        if (game.isWinner(column, yCoordinate, "[X]")) { // if a  winner is found
          toPlayer1.writeInt(PLAYER1_WON);
          toPlayer2.writeInt(PLAYER1_WON);
          sendMove(toPlayer2, row, column);
          break; // Break the loop
        } else {
          toPlayer2.writeInt(CONTINUE);
          sendMove(toPlayer2, row, column);
        }
        // Receive a move from Player 2
        row = fromPlayer2.readInt();
        column = fromPlayer2.readInt();
        yCoordinate = game.insert("[O]", column);
        // Check if Player 2 wins
        if (game.isWinner(column, yCoordinate, "[O]")) { // if a  winner is found
          toPlayer1.writeInt(PLAYER2_WON);
          toPlayer2.writeInt(PLAYER2_WON);
          sendMove(toPlayer1, row, column);
          break; // Break the loop
        } else if (game.boardIsFull()) { // Check if all cells are filled
          toPlayer1.writeInt(DRAW);
          toPlayer2.writeInt(DRAW);
          sendMove(toPlayer1, row, column);
          break;
        } else {
          // Notify player 2 to take the turn
          toPlayer1.writeInt(CONTINUE);
          // Send player 1's selected row and column to player 2
          sendMove(toPlayer1, row, column);
        }
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
 @Test
 public void testThatMakesSureShipsCanBeAddedUsingMultipleCallsToCheckAndPlaceShips() {
   GameBoard gb = new GameBoard(10, 10, 1);
   ArrayList<Ship> ships = new ArrayList<Ship>();
   ships.add(new Ship(3, 3, 3, true));
   Assert.assertTrue(gb.checkAndPlaceShips(ships, "bottom"));
   ships.removeAll(ships);
   ships.add(new Ship(4, 6, 2, true));
   Assert.assertTrue(gb.checkAndPlaceShips(ships, "bottom"));
 }
 // This method is called once a second, and it is a good place to
 // do things like check if the snake has collided into the wall
 // or the apple.
 public void onTimer() {
   if ((snake.hasHitTail() == false) && (snake.hasHitWall(gameBoard) == false)) {
     snake.move(gameBoard);
     if (snake.hasHitApple(apple)) {
       apple.setPos(gameBoard.getRandomXCoord(), gameBoard.getRandomYCoord());
       System.out.println("It hit the apple");
       scoreBoard.incrementPlayerScore();
     }
   } else gameOver = true;
 }
Beispiel #11
0
  private static GameBoard[] GetGameBoards() {
    GameBoard board1 = new GameBoard();
    GameBoard board2 = new GameBoard();

    board1.setupPlacement(placeShip());

    GameBoard[] returnValue = {board1, board2};

    return returnValue;
  }
Beispiel #12
0
  /**
   * 1. Reset Game Board 2. Set Cell (0, 0) value to alive. 3. Perform one game step 4. Check that
   * board doesn't contains any live cells.
   */
  public void testGenerateNextGenerationOneCellAlive() {
    GameBoard.getBoard().reset();
    GameBoard.getBoard().set(0, 0);
    GameBoard.getBoard().generateNextGeneration();

    for (int h = 0; h < GameConfig.HEIGHT; h++) {
      for (int w = 0; w < GameConfig.WIDTH; w++) {
        assertEquals(GameBoard.getBoard().isAlive(h, w), false);
      }
    }
  }
Beispiel #13
0
 public void endGame() {
   if (playerScore > enemyScore) {
     message.setText("Sinu võit!");
   } else if (playerScore < enemyScore) {
     message.setText("Oi oi, kaotasid!");
   } else {
     message.setText("Viik!");
   }
   message.setStyle("-fx-font-size: 150%; -fx-text-fill: red");
   // lülita nupud välja
   playerBoard.disableButtons();
   enemyBoard.disableButtons();
 }
Beispiel #14
0
  /**
   * 1. Reset Game Board 2. Set Cells (3, 3) (3, 4) and (3, 5) value to alive. 3. Perform one game
   * step 4. Check that Game board alive cells are changed to (2, 4) (3, 4) and (4, 4)
   */
  public void testGenerateNextGeneration3CellLineAlive() {
    GameBoard.getBoard().reset();
    GameBoard.getBoard().set(3, 3);
    GameBoard.getBoard().set(3, 4);
    GameBoard.getBoard().set(3, 5);
    GameBoard.getBoard().generateNextGeneration();

    assertEquals(GameBoard.getBoard().isAlive(3, 3), false);
    assertEquals(GameBoard.getBoard().isAlive(2, 4), true);
    assertEquals(GameBoard.getBoard().isAlive(3, 4), true);
    assertEquals(GameBoard.getBoard().isAlive(4, 4), true);
    assertEquals(GameBoard.getBoard().isAlive(3, 5), false);
  }
Beispiel #15
0
  private MinMaxResult bestMinMaxMove(GameBoard gameBoard, int depth, Player currentPlayer) {
    Player winner = gameBoard.getWinner();
    if (winner == mComputerPlayer) {
      return new MinMaxResult(null, MAX_BOARD_SCORE - depth);
    } else if (winner == mHumanPlayer) {
      return new MinMaxResult(null, depth - MAX_BOARD_SCORE);
    } else if (gameBoard.isBoardFull()) {
      return new MinMaxResult(null, 0);
    }

    depth++;
    MinMaxResult bestMove = null;
    boolean maximize = currentPlayer == mComputerPlayer ? true : false;

    for (int i = 0; i < GameBoard.SIZE; ++i) {
      for (int j = 0; j < GameBoard.SIZE; ++j) {
        if (gameBoard.isMovePossible(i, j)) {
          Move move = new Move(i, j, currentPlayer);
          gameBoard.playMove(move);

          // To avoid having to store all moves and perform a sort at each
          // iteration, we keep a running record of the maximum or minimum score
          // depending on what is required. If the player is the computer, we
          // maximize, otherwise we minimize. The recursive call to bestMinMaxMove
          // returns an object that contains a score and the associated move. We
          // replace the move object with our move as we bubble this up so that
          // at the highest level we have the first move in the chain that leads
          // to the best result.
          Player nextPlayer = currentPlayer == Player.CROSS ? Player.CIRCLE : Player.CROSS;
          MinMaxResult potentialBestMove = bestMinMaxMove(gameBoard, depth, nextPlayer);
          potentialBestMove.move = move;

          if (maximize) {
            if (bestMove == null || potentialBestMove.score > bestMove.score) {
              bestMove = potentialBestMove;
            }
          } else {
            if (bestMove == null || potentialBestMove.score < bestMove.score) {
              bestMove = potentialBestMove;
            }
          }

          // Undo the move so that the board returns back to its
          // previous state
          gameBoard.undoMove(move);
        }
      }
    }
    return bestMove;
  }
Beispiel #16
0
  /**
   * Generates recursively all possible moves starting from current configuration taking into
   * account player turns. E.g. X | 0 | X X | 0 | X X | 0 | X 0 | 0 | X => 0 | 0 | X OR 0 | 0 | X X
   * | - | - X | 0 | - X | - | 0
   */
  public void generateAllPossibleMoves() {
    boolean generatedMove = false;
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
        if (this.getBoardField(i, j).equals("-")) {
          generatedMove = true;
          GameBoard newState = new GameBoard(1 - this.getCurrentPlayer());
          newState.setBoard(this.getBoard());
          newState.setBoardField(i, j, this.getPlayerSymbol());
          this.addNextMove(newState);

          if (newState.gameOver()) {
            int Q = newState.evaluateBoard();
            newState.setScore(Q);
            newState.noMoreMoves = true;

          } else newState.generateAllPossibleMoves();
        }
      }
    }
    if (!generatedMove) {
      this.setScore(0);
      this.noMoreMoves = true;
    }
  }
Beispiel #17
0
  @Test
  public void testOnlyValidMovesAreMade() {
    GameBoard gameBoard = new GameBoard();
    GamePiece[][] board = gameBoard.getBoard();

    board[2][2] = new GamePiece(2, 2, Color.BLACK);
    gameBoard.makeMove(Color.CYAN, 2, 2);
    // make sure that piece already taken was not overridden by new piece
    // and new color
    assertEquals(board[2][2].getColor(), Color.BLACK);

    gameBoard.makeMove(Color.CYAN, 3, 3);
    // make sure that an invalid move is not taken
    assertEquals(board[3][3].getColor(), null);
  }
Beispiel #18
0
  public void startGame(boolean isComputerFirst) {
    mGameBoard.clearBoard();

    mComputerPlayer = isComputerFirst ? Player.CROSS : Player.CIRCLE;
    mHumanPlayer = isComputerFirst ? Player.CIRCLE : Player.CROSS;

    updateCurrentPlayer(isComputerFirst ? mComputerPlayer : mHumanPlayer);
    if (isComputerFirst) {
      playComputerMove(true);
    }

    if (mGameListener != null) {
      mGameListener.onBoardUpdated(mGameBoard.getBoard());
    }
  }
Beispiel #19
0
  @Test
  public void testThatAIPlacesShips() {
    GameBoard gb = new GameBoard();
    int[] blank = {5, 4, 3, 2, 1};
    AI ai = new AI(gb, blank);
    ai.placeShips();
    Boolean result = false;

    for (int r = 0; r < gb.getHeight(); r++) {
      for (int c = 0; c < gb.getWidth(); c++) {
        result = result || !(gb.getTopGrid().getGrid()[r][c] instanceof ShipCell);
      }
    }

    Assert.assertTrue(result);
  }
 /**
  * Play a move in the given row and column of the TicTacToe board with the current player.
  *
  * @param row the row to mark
  * @param col the column to mark
  * @return <code>true</code> if this position was playable; <code>false</code> otherwise
  */
 public boolean play(int row, int col) {
   if (board.mark(row, col, currentPlayer)) {
     lastMove = new Position(row, col);
     return true;
   }
   return false;
 }
Beispiel #21
0
 /*
  * Om show valid moves=enabled visas en speciell ikon istället då musen är ovanför.
  */
 @Override
 public void mouseEntered(MouseEvent e) {
   if (value == 3) {
     temp = (ImageIcon) getIcon();
     setIcon(GameBoard.getMouse_Over_Marker());
   }
 }
Beispiel #22
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    GameBoard board = new GameBoard();

    int pRow = 5;
    int clicked = 0;
    while (true) {
      // wait for the user to click
      Coordinate c = board.getClick();
      clicked++;
      int row = c.getRow();
      int col = c.getCol();
      // put a piece where they clicked
      board.putPiece(row, col, Color.blue);
      board.setMessage("You have clicked " + clicked + " times");
    }
  }
  // Gets the AI's next move giving the current state of the board
  private void getAIMove(GameBoard board) {
    // Send the board to the AI for it to determine and return the move in an array {x,y}
    int[] move = ai.move(board, aiMark);
    TextView cell = null;
    // Determine the right cell to use by id first go to the right row then the right column
    switch (move[0]) {
      case 0:
        switch (move[1]) {
          case 0:
            cell = (TextView) findViewById(R.id.cell11);
            break;
          case 1:
            cell = (TextView) findViewById(R.id.cell12);
            break;
          case 2:
            cell = (TextView) findViewById(R.id.cell13);
            break;
        }
        break;
      case 1:
        switch (move[1]) {
          case 0:
            cell = (TextView) findViewById(R.id.cell21);
            break;
          case 1:
            cell = (TextView) findViewById(R.id.cell22);
            break;
          case 2:
            cell = (TextView) findViewById(R.id.cell23);
            break;
        }
        break;
      case 2:
        switch (move[1]) {
          case 0:
            cell = (TextView) findViewById(R.id.cell31);
            break;
          case 1:
            cell = (TextView) findViewById(R.id.cell32);
            break;
          case 2:
            cell = (TextView) findViewById(R.id.cell33);
            break;
        }
        break;
    }

    // Make sure there's nothing already in the cell
    //	then place the mark with the ai's Mark, increment move count
    //	and check to see if the game's over
    if (cell != null && cell.getText() == "") {
      board.placeMark(move[0], move[1], aiMark);
      cell.setText(aiMark);
      moveCount++;
      isOver = checkEnd(aiMark);
    }
  }
 public void drawBoard(Canvas canvas) {
   canvas.drawColor(Color.WHITE);
   Paint p = new Paint();
   p.setAntiAlias(true);
   for (int i = 0; i < board.rowCount(); ++i) {
     for (int j = 0; j < board.columnCount(); ++j) {
       Life l = board.get(i, j);
       if (l.dead) continue;
       p.setColor(l.color);
       canvas.drawRect(
           i * Life.LIFE_SIZE,
           j * Life.LIFE_SIZE,
           (i + 1) * Life.LIFE_SIZE,
           (j + 1) * Life.LIFE_SIZE,
           p);
     }
   }
 }
Beispiel #25
0
  /**
   * Executes the players move desition by: - checking if location is available, using the
   * availableLication method - moving player to new location
   */
  public boolean moveTo(Location location, GameBoard board) {

    if (isValidMove(location, board)) {
      playerLocation = new Location(location);
      board.playerPositionUpdated(this, playerLocation);
      return true;
    }

    return false;
  }
Beispiel #26
0
 private static ActionListener showDestinations() {
   ActionListener a1 =
       (e) -> {
         int index = Integer.parseInt(((JButton) e.getSource()).getText());
         System.out.println(index);
         GameBoard.getPossibleMoves(true, index, new HashSet<Integer>())
             .parallelStream()
             .forEach(i -> GameBoard.board.get(i - 1).setPlayer(7));
         createAndShowGUI();
       };
   return a1;
 }
Beispiel #27
0
 /** main method for solver. solves a sudoku puzzle */
 public static void main(String[] args) {
   Stack<GameBoard> stack = new LinkedList<GameBoard>(); // intializes stack
   GameBoard board = new GameBoard(); // creates the game board
   stack.push(board);
   boolean solved = false;
   while (solved == false) {
     if (stack.isEmpty()) // if stack is empty the board is unsolvable
     System.out.println("board is unsolvable");
     GameBoard curr = stack.pop();
     if (curr.solved()) {
       System.out.println(curr);
       solved = true;
       return;
     }
     int[] mostConstrained =
         curr
             .mostConstrained(); // array containing the row and column of the most constrined spot
                                 // on the board
     for (int i = 1; i < 10; i++) // checks what numbers can be placed at the most constrained spot
     {
       if (curr.canPlace(mostConstrained[0], mostConstrained[1], i)) {
         GameBoard temp =
             new GameBoard(
                 curr); // calls the copy constructor and creates a copy of current game board
         temp.place(mostConstrained[0], mostConstrained[1], i);
         stack.push(temp);
       }
     }
   }
 }
 @Override
 public List<DiscreteGameState> availableStates() {
   List<Position> availableMoves = board.getOpenPositions();
   List<DiscreteGameState> availableStates =
       new ArrayList<DiscreteGameState>(availableMoves.size());
   for (Position move : availableMoves) {
     TicTacToeGameState newState = new TicTacToeGameState(this);
     newState.play(move.getRow(), move.getCol());
     newState.switchPlayer();
     availableStates.add(newState);
   }
   return availableStates;
 }
Beispiel #29
0
  public Game(int shipCount) {
    this.shipCount = shipCount;
    VBox gameLayout = new VBox();
    gameLayout.setPrefSize(300, 650);

    Label playerLabel = new Label("Sinu mängulaud");
    // this on refereering sellele objektile, et nupp teaks, millise mängulaua poole pöörduda,
    // loob mängija mänguvälja, falsega keelan enda mänguvälja nuppude klikkimise
    playerBoard = new GameBoard(shipCount, this, false);
    GridPane playerGrid = playerBoard.getBoardLayout();

    Label enemyLabel = new Label("Vastase mängulaud");
    // truega luban endal vastase mängulaua nuppe klikkida
    enemyBoard = new GameBoard(shipCount, this, true);
    GridPane enemyGrid = enemyBoard.getBoardLayout();

    // lisan elemendid
    gameLayout.getChildren().addAll(playerLabel, playerGrid, enemyLabel, enemyGrid);

    // parempoolne layout
    VBox rightLayout = new VBox();
    rightLayout.setPadding(new Insets(0, 0, 0, 10));

    Button button = new Button("Uus mäng");
    button.setOnAction(
        event -> {
          BattleShips.newGameAction();
        });
    playerScoreLabel = new Label("Sinu punkte: 0");
    enemyScoreLabel = new Label("Vastase punkte: 0");
    message = new Label("");
    // lisan layout-i
    rightLayout.getChildren().addAll(button, playerScoreLabel, enemyScoreLabel, message);

    // terve akna layout
    HBox fullLayout = new HBox();
    fullLayout.getChildren().addAll(gameLayout, rightLayout);
    scene = new Scene(fullLayout, 500, 650);
  }
Beispiel #30
0
  public void enemyPlay() {
    // leiab mänguväljalt juhusliku arvu, mis on vahemikus 0 kuni kasutamata nuppude hulk
    int random = (int) (Math.random() * playerBoard.getButtonList().size());

    // enemy klikib minu mänguvälja nupul
    BoardField field = playerBoard.getButtonList().get(random);
    field.clickButton(false);

    // eemaldan nupu mänguvälja nuppude nimekirjast, kuna sellele uuest nagunii klikkida ei saa
    playerBoard.removeButton(field);

    // kui enemy sai laevale pihta, saab uuesti mängida
    if (field.isHasShip()) {
      increaseEnemyScore();
      if (playerBoard.getButtonList().size() > 0 && enemyScore < shipCount) {
        enemyPlay();
      }
    }
    if (enemyScore == shipCount) {
      endGame();
    }
  }