Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package airware;
- public class Board {
- public int rows;
- public int cols;
- private int[][] board;
- private int SHIP_LENGTH = 3;
- public Board(int rows, int cols) {
- this.rows = rows;
- this.cols = cols;
- this.board = new int[rows][cols];
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- this.board[i][j] = 0;
- }
- }
- }
- public int[][] getBoard() {
- return board;
- }
- public void placeShip() {
- while (true) {
- int x = (int) Math.floor(Math.random() * rows);
- int y = (int) Math.floor(Math.random() * cols);
- int orientation = (int) Math.floor(Math.random() * 2); // 0 or 1
- if (isValidPlacement(x, y, orientation)) {
- // placeShip
- if (orientation == 0) {
- for (int i = 0; i < SHIP_LENGTH; i++) {
- board[x][y+i] = 1;
- }
- } else if (orientation == 1) {
- for (int i = 0; i < SHIP_LENGTH; i++) {
- board[x+i][y] = 1;
- }
- }
- break;
- }
- }
- }
- /*
- * Orientation: 0 = horizontal, 1 = vertical
- */
- private boolean isValidPlacement(int x, int y, int orientation) {
- if (this.board[x][y] != 0) {
- return false;
- }
- if (orientation == 0) {
- if (y+SHIP_LENGTH < 0 || y+SHIP_LENGTH >= cols) {
- return false;
- }
- for (int i = 0; i < SHIP_LENGTH; i++) {
- if (board[x][y+i] != 0) {
- return false;
- }
- }
- } else if (orientation == 1) {
- if (x+SHIP_LENGTH < 0 || x+SHIP_LENGTH >= rows) {
- return false;
- }
- for (int i = 0; i < SHIP_LENGTH; i++) {
- if (board[x+i][y] != 0) {
- return false;
- }
- }
- }
- return true;
- }
- public boolean guess(int x, int y) {
- // out of bounds
- if (x < 0 || y < 0 || x >= rows || y >= cols) {
- return false;
- // in bounds, check board
- } else {
- if (board[x][y] == 0) {
- return false;
- } else {
- board[x][y] = -1;
- return true;
- }
- }
- }
- }
- package airware;
- import static org.junit.Assert.*;
- import org.junit.Test;
- public class BoardTest {
- @Test
- public void createBoardTest() {
- Board b = new Board(10, 10);
- int[][] board = b.getBoard();
- int[][] result = new int[10][10];
- for (int i = 0; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- result[i][j] = 0;
- }
- }
- assertEquals(board, result);
- }
- @Test
- public void placeShipTest() {
- Board b = new Board(10, 10);
- b.placeShip();
- int[][] board = b.getBoard();
- int counter = 0;
- for (int i = 0; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- if (board[i][j] == 1) {
- counter++;
- }
- }
- }
- assertEquals(counter, 3);
- }
- @Test
- public void guessTest() {
- Board b = new Board(10, 10);
- b.placeShip();
- int trueGuesses = 0;
- for (int i = 0; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- if (b.guess(i, j)) {
- trueGuesses++;
- }
- }
- }
- assertEquals(trueGuesses, 3);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement