java - Need Help Programming Battleship Location Selector/Checker -
i trying develop 1-sided battleship game , have set up. need incorporate array holds @ time, 5, ships objects. class created each ship called ships.java. earlier having problems initializing array has been settled.
the problem arises when try pull in length of ship (2, 3, 4 or 5) index in array. i'm not sure how conceptually go placing ships.
i feel i've tried every combination of do-whiles, loops , if statements. tried switch-case.
the goal have computer select positions 5 ships , set each cell in grid (rowsxcols) equal nc_ship (not clicked, plus ship). problem making check positions of cells adjacent random location on grid. has check if ship in question fit (pulling ships[i].getshiplength()).
here code have far:
int shipsplaced = 0; (int = 0; < ships.length; i++) { boolean shipplaced = false; { int randomrow = (int)(math.random()*rows); int randomcol = (int)(math.random()*cols); int p = 0; if (randomrow - ships[p].getshiplength() >= 0 && gameboard[(randomrow - p)][randomcol] == nc_empty) { (int x = 0; x < ships[x].getshiplength(); x++) { gameboard[(randomrow - x)][randomcol] = nc_ship; shipsplaced = shipsplaced + 1; if (x == ships[x].getshiplength()) { shipplaced = true; p = p + 1; } } } }while (shipplaced == false); } everything has been initialized , set if it's not visible here. problem math/logic used place ships in 'random' locations.
first of all: ships go horizontal, should randomize placement direction of ship.
there 2 ways face problem:
- first fit initial pos if ship fits.
- first list available positions, randomize number equal list length
1 - make recursive random initial position (x,y) (which should free, if not re-throw position). in recursive "lookforpos" method, make randomplacementdirection, , that, flag (eg ishorizontal). if doesn't fit (length start final position overflows size of matrix), re-throw. cover positions (position, position+1, position+2, ..., position+n) 'n' length of ship , position x,y pair , +1 affects 1 of cardinals (depending if ishorizontal or not) if of them occupied re-throw. you'll have need.
2 - make list of positions fits (a 'for' structure), both horizontal , vertical, randomize length of list.
Comments
Post a Comment