This game uses a 2d array(7x7) and uses two array lists to store the ship (of lengths 2,3,4) and user guesses. The user first types the row and column of each ship and the orientation (either extending down or right). Then a blank board is printed to console and the user will guess row and column. If there is a ship in that spot "hit!" is printed to console, else "miss!" is printed. After each guess, the new state of the board is printed where each hit is a "X" and each miss is a "M". also each guess is added to the guess array list. once the user guesses where each element of the ship is, the game is over and the guess history is printed. My code seems to be working however I am having trouble ending the game. It never gets out of the while loop in the main. Here is my code, is there something that I am doing wrong or need to change?
===========================================================================
My code:
class Ship {
int x;
int y;
//String orient;
public Ship (int x, int y) {
super();
this.x = x;
this.y = y;
//this.orient = orient;
}
}
class Guess {
int row;
int col;
public Guess (int row, int col) {
super();
this.row = row;
this.col = col;
}
}
public class CS125_Project5
{
//create the 2d arrays for the realBoard where the user will add the ships
// and the guessBoard which will update when user makes guesses
/////////what i had at first but kept getting nullpointerexception
//static String realBoard[][];
//static String guessBoard[][];
//with these i get the thing printed but it says null for all values
static String gameBoard[][] = new String[7][7];
static String guessBoard[][] = new String[7][7];
//creating the arrayList for both ships and guesses
static ArrayList<Ship> ships = new ArrayList<>();
static ArrayList<Guess> guesses = new ArrayList<>();
////////////////////////////////////////////////////////
////// Constructor
////////////////////////////////////////////////////////
public CS125_Project5() {
//initializing the arrays to have a fixed size of 7x7
//realBoard = new String[7][7];
//guessBoard = new String[7][7];
ships = new ArrayList<>();
guesses = new ArrayList<>();
//adding a '-' to each element of the 2d arrays for both boards
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
gameBoard[i][j] = "-";
guessBoard[i][j] = "-";
}
}
}
////////////////////////////////////////////////////////
/////// Method to Print the game maker board
////////////////////////////////////////////////////////
public static void printGameMakerBoard(){
System.out.print("r\\c\t");
//printing the column numbers
for(int i=0;i<7;i++){
System.out.print(i+"\t");
}
//printing the row numbers
System.out.println();
//printing the gameMaker board to show user what the board looks like
for(int i=0;i<7;i++){
System.out.print(i+"\t");
for(int j=0;j<7;j++){
System.out.print(gameBoard[i][j] +"\t");
}
System.out.println();
}
}
public static void updateBoard(int row, int col, String orient, int length) {
//if statement to determine orientation of ship
if (orient.contains("r")) {
int updateCol;
for (int j = 0; j < length; j++) {
updateCol = j + col;
gameBoard[row][updateCol] = "S";
}
} else {
int updateRow;
for (int j = 0; j < length; j++) {
updateRow = row + j;
gameBoard[updateRow][col] = "S";
}
}
printBoard(gameBoard);
}
public static void printBoard(String[][] board) {
System.out.print("r\\c"+"\t");
//printing the column numbers
for(int i=0;i<7;i++){
System.out.print(i+"\t");
}
System.out.println();
//printing the row numbers
// printing the guess board
for(int i=0;i<7;i++){
System.out.print(i+"\t");
for(int j=0;j<7;j++){
System.out.print(board[i][j] +"\t");
}
System.out.println();
}
}
private static void addShip(int x, int y, int length, String orient) {
gameBoard[x][y] = "S";
if (length == 2 || length == 3 || length == 4) {
if (orient.contains("d")) {
for (int i = 0; i < length; i++) {
Ship ship = new Ship(x, y+i);
ships.add(ship);
}
} else { //orient.contains("s")
for (int j = 0; j < length; j++) {
Ship ship = new Ship(x+j, y);
ships.add(ship);
}
}
}
// Ship ship = new Ship(x, y);
// ships.add(ship);
}
public void guess(int x, int y) {
//adding user guesses to ArrayList
Guess g = new Guess(x , y);
guesses.add(g);
//check to see if hit or miss, if hit replace user guess with 'X'
// else if its a miss replace guess with 'M'
if (gameBoard[x][y] == "S") {
guessBoard[x][y] = "X";
System.out.println("Hit!");
//now remove the ship from the list
for(int i = 0; i < ships.size(); i++) {
Ship ship = ships.get(i);
if (ship.x== x && ship.y == y){
ships.remove(i);
break;
}
}
} else {
guessBoard[x][y] = "M";
System.out.println("Miss!");
}
}
public static boolean gameOver() {
if(ships.size() == 0) {
return true;
} return false;
}
public static void printGuesses() {
System.out.println("Guess || Row Col");
System.out.println("=====================");
for(int i = 0; i < guesses.size(); i++) {
Guess g = guesses.get(i);
System.out.println(" " + i + " || " + g.row + " " + g.col);
}
}
////////////////////////////////////////////////////////
////// Main
////////////////////////////////////////////////////////
public static void main(String[] args)
{
// Your program should always output your name and the project number.
// DO NOT DELETE OR COMMENT OUT. Replace with relevant info.
System.out.println("Mason Sarna");
System.out.println("Project 5");
System.out.println("");
// Your code should go below this line
System.out.println("------------Welcome to BattleShip------------");
//printGameMakerBoard();
CS125_Project5 userShip = new CS125_Project5();
//CS125_Project5.printGameMakerBoard();
printBoard(guessBoard);
// create scanner
Scanner sc = new Scanner(System.in);
//initializing variables
int row = 0;
int col = 0;
String orient = "";
int length = 0;
/////////////////////
// Getting user input for row, col, and orientation of 3 different ships, updates/prints the board after each ship input
for (int i = 2; i < 5; i++) {
System.out.println("Please enter coordinates for ship of length "+ i);
System.out.println("Starting Row (0-6):");
row = sc.nextInt();
System.out.println("Starting column (0-6):");
col = sc.nextInt();
System.out.println("From the starting point, extend down or right? (d/r):");
orient = sc.next().toLowerCase();
length = i;
//CS125_Project5.updateBoard(row, col, orient, length);
updateBoard(row,col,orient,length);
CS125_Project5.addShip(row,col, i, orient);
}
System.out.println();
System.out.println("------------Final Game Maker Board------------");
CS125_Project5.printGameMakerBoard();
System.out.println();
System.out.println();
System.out.println("------------GAME STARTING NOW------------");
printBoard(guessBoard);
while(!gameOver()) {
System.out.println("Enter guess in row/col:");
int r = sc.nextInt();
int c = sc.nextInt();
if (guesses.contains(r) && guesses.contains(c)) {
System.out.println("r\\c = " + r + "\\" + c + " has already been guessed");
} else {
userShip.guess(r, c);
CS125_Project5.printBoard(guessBoard);
}
System.out.println("---------------------------------------------------");
}
System.out.println("------------Game Over------------");
CS125_Project5.printGuesses();
}
I want to check a whole Sudoku table if all the blocks got the 9 values or not but I was able to check only the first block and I need to check the other 8 blocks how?
public static boolean checkSubs(int[][] p) {
int[] nums = new int[9];
int x=0, temp;
for (int i=0; i<3; i++)
for (int j=0; j<3; j++) {
temp = p[i][j];
for ( int m=0; m<nums.length; m++)
if ( nums[m]==temp ) return false;
nums[x++]=temp; }
return true; }
You can modify your checkSubsMethod.
Add i and j of the top left corner of sudoku subblock (e.g (0,0), (0,3),... (3,0), (3,3)... (6,3),(6,6)).
Use set to check does the value already used or not. The add() method of Set class return true if value doesn't in the set and false if value already added to the set.
And when you generalise your method you can use it for fields of any size. In your case size is 9x9, here is the example
public static boolean checkSubs(int[][] p, int topI, int topJ) {
Set<Integer> nums = new HashSet<>();
for (int i = topI; i < topI + 3; i++) {
for (int j = topJ; j < topJ + 3; j++) {
if (!nums.add(p[i][j])) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
int[][] sudoku = {
{1,2,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{7,8,9,7,8,9,7,8,9},
{1,2,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{7,8,9,7,8,9,7,8,9},
{1,2,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{7,8,9,7,8,9,7,8,9}};
for (int i = 0; i < sudoku.length;i += 3){
for (int j = 0; j<sudoku[0].length; j += 3){
if (!checkSubs(sudoku, i, j)){
System.out.println("DUPLICATED VALUES FOUND!");
return;
}
}
}
System.out.println("OK!!");
}
The output for this case will be OK!!
If you change the input like this
int[][] sudoku = {
{3,3,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{7,8,9,7,8,9,7,8,9},
{1,2,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{7,8,9,7,8,9,7,8,9},
{1,2,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{7,8,9,7,8,9,7,8,9}};
The output will be DUPLICATED VALUES FOUND!
You can modify this example for your purposes in future.
Basically, the project description asks the user to create a matching game, consisting of:
A two dimensional playing table (4x4), 16 pairs of matching cards, and a running count of the number of face-down cards. Include a method to retrieve a specific card from the table at an input x,y position.
A gameBoard, and loop that continues play until all cards remain face up.
The loop includes an interface with the user to pick two cards (inputting x,y table positions), checking if two cards are equal,
decrementing the count of faceDown cards, and setting the faceUp boolean of the cards.
Essnetially, the program should run until all the cards are face up, and the game is won. I separated my program in to four separate classes below.
1.
public class Card {
private final int cardValue;
private boolean faceUp;
public Card(int value) {
cardValue = value;
faceUp = false;
}
public int getValue() {
return cardValue;
}
public boolean isFaceUp() {
return faceUp;
}
public void setFaceUp(boolean input) {
faceUp = input;
}
public static void printBoard(Card[][] cards) {
System.out.println("\t\t1\t2\t3\t4");
System.out.println("\t____________");
for(int i = 0; i < cards.length; i++) {
System.out.println((i + 1) + "\t|\t");
for(int j = 0; j < cards[0].length; j++)
if(cards[i][j].isFaceUp()) {
System.out.print(cards[i][j].getValue() + "\t"); }
else
System.out.println("*\t");
}
System.out.println();
}
}
2.
public class CreateBoard {
public static Card[][] createBoard() {
Card[][] board = new Card[4][4];
for(int i = 1; i <= 8; i++) {
for(int j = 1; j <= 2; j++) {
boolean boardLocation = false;
while(!boardLocation) {
int row = (int)(Math.random() * 4);
int column = (int)(Math.random() * 4);
if(board[row] == null && board[column] == null) {
boardLocation = true;
board[row][column] = new Card(i);
}
}
}
}
return board;
}
}
3.
public class Game {
public static boolean wonGame(Card[][] board) {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(!board[i][j].isFaceUp())
return false;
}
}
return true;
}
}
And finally, the main class:
public class GameDriver {
public static void main(String[] args) {
Card[][] board = CreateBoard.createBoard();
Scanner keyboard = new Scanner(System.in);
System.out.println("Starting Game...");
while(!Game.wonGame(board)) {
Card.printBoard(board);
System.out.println("Enter X-Coordinate #1 (1-4): ");
int column1 = keyboard.nextInt();
System.out.println("Enter Y-Coordinate #1 (1-4): ");
int row1 = keyboard.nextInt();
System.out.println("Enter X-Coordinate #2 (1-4): ");
int column2 = keyboard.nextInt();
System.out.println("Enter Y-Coordinate #2 (1-4): ");
int row2 = keyboard.nextInt();
Card card1 = board[row1][column1];
Card card2 = board[row2][column2];
if(card1.getValue() == card2.getValue() && !(row1 == row2 && column1 == column2))
{
card1.setFaceUp(true);
card2.setFaceUp(true);
}
else if(row1 == row2 && column1 == column2)
{
System.out.println("Points selected are the same, try again");
}
else
{
System.out.println(card1.getValue() + " and " + card2.getValue() + " do not match");
}
}
Card.printBoard(board);
}
}
The code seems to run fine, no errors or anything. However, after multiple test trials, the glaring issue is that it does not output anything to console... Am I missing something? Help would be appreciated!
Create board should be
public class CreateBoard {
public static Card[][] createBoard() {
Card[][] board = new Card[4][4];
for(int i = 1; i <= 8; i++) {
for(int j = 1; j <= 2; j++) {
boolean boardLocation = false;
while(!boardLocation) {
int row = (int)(Math.random() * 4);
int column = (int)(Math.random() * 4);
if(board[row][column] == null) {
boardLocation = true;
board[row][column] = new Card(i);
}
}
}
}
return board;
}
}
And for the Game class, since java array index is starting with 0 then
these lines should be
Card card1 = board[row1-1][column1-1];
Card card2 = board[row2-1][column2-1];
I am doing a game called 1010! Probably some of you have heard of it. Bascially I encouter some trouble when writing the Algorithm for clearance.
The rule is such that if any row or any column is occupied, then clear row and column respectively.
The scoring is such that each move gains a+10*b points. a is the number of square in the input piece p and b is the total number of row&column cleared.
To start, I create a two dimensional Array board[10][10], poulate each elements in the board[][] with an empty square.
In the class of Square, it has public void method of unset()-> "empty the square" & boolean status() -> "judge if square is empty"In the class of piece, it has int numofSquare -> "return the number of square in each piece for score calculation"
In particular, I don't know how to write it if both row and column are occupied as they are inter-cross each other in an two dimensional array.
It fail the test under some condition, in which some of the squares are not cleared but they should have been cleared and I am pretty sure is the logic problem.
My thinking is that:
Loop through squares in first row and first column, record the number of square that are occupied (using c and r); if both are 10, clear row&column, otherwise clear row or column or do nothing.
reset the c &r to 0, loop through square in the second row, second column…
update score.
Basically the hard part is that if I seperate clear column and clear row algorithm ,I will either judge row or column first then clear them . However, as every column contains at least one square belong to the row, and every row contains at least one square belong to the column, there will be mistake when both row and column are full.
Thanks for help.
import java.util.ArrayList;
public class GameState{
public static final int noOfSquares = 10;
// the extent of the board in both directions
public static final int noOfBoxes = 3;
// the number of boxes in the game
private Square[][] board; // the current state of the board
private Box[] boxes; // the current state of the boxes
private int score; // the current score
// initialise the instance variables for board
// all squares and all boxes are initially empty
public GameState()
{
getboard();
score = 0;
board = new Square[10][10];
for(int i =0;i<board.length;i++){
for(int j =0;j<board[i].length;j++){
board[i][j] = new Square();
}
}
boxes = new Box[3];
for(int k =0;k<boxes.length;k++){
boxes[k] = new Box();
}
}
// return the current state of the board
public Square[][] getBoard()
{
return board;
}
// return the current score
public int getScore()
{
return score;
}
// place p on the board with its (notional) top-left corner at Square x,y
// clear columns and rows as appropriate
int r =0;
int c = 0;
int rowandcolumn = 0;
for (int row=0;row<10;row++){
for (int column=0;column<10;column++) {
if (board[row][column].status() == true){
c = c + 1;
if( c == 10 ) {
rowandcolumn = rowandcolumn + 1;
for(int z=0;z<10;z++){
board[row][z].unset(); //Clear column
}
}
}
if (board[column][row].status() == true){
r = r + 1;
if( r == 10) {
rowandcolumn = rowandcolumn + 1;
for(int q=0;q<10;q++){
board[q][row].unset(); //Clear row
}
}
}
}
r=0; //reset
c=0;
}
score = score + p.numberofBox()+10*rowandcolumn;
}
how about this
void Background::liquidate(int &score){
int arr_flag[2][10]; //0 is row,1 is column。
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 10; j++)
{
arr_flag[i][j] = 1;
}
}
//column
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (arr[i][j].type == 0)
{
arr_flag[0][i] = 0;
break;
}
}
}
//row
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (arr[j][i].type == 0)
{
arr_flag[1][i] = 0;
break;
}
}
}
//clear column
for (int i = 0; i < 10; i++)
{
if (arr_flag[0][i] == 1)
{
for (int j = 0; j < 10; j++)
{
arr[i][j].Clear();
}
}
}
//clear row
for (int i = 0; i < 10; i++)
{
if (arr_flag[1][i] == 1)
{
for (int j = 0; j < 10; j++)
{
arr[j][i].Clear();
}
}
}
}
I tried to write somme code for the idea I posted
// place p on the board with its (notional) top-left corner at Square x,y
// clear columns and rows as appropriate
int r =0;
int c = 0;
int rowandcolumn = 0;
int row=FindFirstRow();
int column=FindFirstColumn();
if(row!=-1 && column!=-1)
{
rowandcolumn++;
//actions here: row found and column found
//clear row and column
clearRow(row);
clearColumn(column);
}
else if(row!=-1)
{
//only row is found
//clear row
clearRow(row);
}
else if(column!=-1)
{
//only column is found
//clear column
clearColumn(column);
}
else
{
//nothing is found
}
public void clearRow(int row)
{
for(int i=0; i<10;i++)
{
board[row][i].unset();
}
}
public void clearColumn(int column)
{
for(int i=0; i<10;i++)
{
board[i][column].unset();
}
}
//this method returns the first matching row index. If nothing is found it returns -1;
public int FindFirstRow()
{
for (int row=0;row<10;row++)
{
int r=0;
for (int column=0;column<10;column++)
{
if (board[row][column].status() == true)
{
r = r + 1;
if( r == 10)
{
//row found
return row;
}
}
}
r=0; //reset
}
//nothing found
return -1;
}
//this method returns the first matching column index. If nothing is found it returns -1;
public int FindFirstColumn()
{
for (int column=0;column<10;column++)
{
int c=0;
for (int row=0;row<10;row++)
{
if (board[row][column].status() == true)
{
c = c + 1;
if( c == 10 )
{
//matching column found
return column;
}
}
}
c=0; //reset
}
//nothing found
return -1;
}
Why isn't my game of life working correctly?
They don't always die when they're too crowded.
Relevant code is grann(x,y) which is supposed to return the number of living cells surrounding matrix[x][y],
run is supposed to calculate the next generation:
private int grann(int x,int y) {
int n = 0;
for(int i=-1; i<2; i++) {
for(int j=-1; j<2; j++) {
if(i!=0 || j!=0) {
if(matrix[x+i][y+j]) {
n++;
}
}
}
}
return n;
}
public void run() {
boolean[][] next = matrix;
for(int i=1; i<w; i++) {
for(int j=1; j<h; j++) {
int n = grann(i,j);
if(matrix[i][j]) {
if(!(n==2 || n==3)) {
next[i][j] = false;
}
} else {
if(n==3) {
next[i][j] = true;
}
}
}
}
matrix = next;
}
The object has a matrix, width and height.
matrix is a boolean[w+2][h+2], and w and h are ints.
If you don't know the rules of Conway's game of life:
http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
I think the problem is that grann should say:
if(i != 0 && j != 0)
because you want to eliminate just the centre square of the 3x3 area you are checking (the cell itself), not the row and column it is in also.