2D Arrays Battleship place random ships - java

Hi, I just started to create a battleship game and I would like to know how to place random ships in my 2D Array. Here is the code for 2D Array.
public class javaapplication24 {
public static void main(String[] args) {
int[][] table = new int[10][10];
int i,j,k;
for(i=0;i<table.length;i++){
for(j=0;j<table.length;j++){
System.out.print(table[i][j]+" ");
}
System.out.println();
}
}
}

The problem that you have undoubtedly noticed is that as each ship is placed, it rules out possibilities of where subsequent ships can be placed. The easiest way around the difficulty is just trial and error. First write a function for randomly placing a ship of a given size somewhere on the board. Place the ships using a nested loop. The outer loop could be a for-loop which iterates through the ships to be placed. The inner loop can be a while loop (or maybe a do-loop) that repeatedly calls the ship-placing function to get a candidate placement, then checks if it clashes with previous choices, looping until a clash-free placement is found.
As far as placing a single ship goes:
1) First generate a random number which is either 0 or 1 to determine if the ship will be placed horizontally or vertically
2) Then pick a random number to determine what the row or column it will be in
3) Finally, pick a random number for the first square in the row or column that contains the ship. The size of the ship will enter in here. If it has length 3, for example, then there are only 10-3 = 7 possible choices for the first square (assuming a standard 10x10 board).
On Edit: #Manus raised a good point about difficulties that would be encountered if the number of ships are above a certain threshold. If you have a massive fleet of ships on a small board it is possible that certain partial placements (of some of the ships) would rule out any valid placement of the remaining ships. The only way I see around this difficulty is to use a back-tracking approach that checks if there is enough room for a ship before trying to place it and, if not, revisit the placement of previous ships until you get something that works. But -- the work involved in checking if there is any valid position can be done in such a way that you simultaneously determine the set of valid positions, in which case you might as well directly pick from that set rather than use trial and error. My approach is essentially a quick-and-dirty approach for simulating the child's game. You would need a more sophisticated approach if you want a more flexible game.

Related

How to generate random board for a game in java but according to specefic conditions?

I am making a board game for college project and it needs to be done in java,
the part that i'm stuck in is generating the board game now imagine with me we have a square shaped board and its size is variable meaning the player decides at the beginning of the game,
and the board is composed of Cells i have a class defined that represents the cell (UML of class below)
and the board is just a 2 dimension array of cells (UML of the game class) and each cell has a biome (MOUNTAIN, PLAIN, DESERT, FOREST, OCEAN) the biomes are defined in a enum,
now my problem is i need to generate a random board for each game and the borad needs to fulfill two conditions:
2/3 of the board must be OCEAN
a MOUNTAIN or PLAIN or FOREST or DESERT must have at least one neighbor that is not OCEAN biome and by neighbor i mean in its north, south, east or west.
The first condition is easy to implement but the second one i don't know how to i looked around on the net but nothing is similar to my condition.
There is an example of a board in the image below (blue cells are OCEAN, yellow is DESERT, light green is PLAIN, green is FOREST and brown is MOUNTAIN).
Code of enum of biomes
public enum Biome {
MOUNTAIN, PLAIN, DESERT, FOREST, OCEAN;
}
I guess you will fill your board row by row or column by column.
You know:
Size of the board
How much must be ocean
How much can be other (save how much can be other ie int nonOceanBiomeLeft)
how much you have already filled
while you fill up, for each field you decide randomly (depending on its weight) what you will set. When you place a non-Ocean biome you reduce nonOceanBiomeLeft by one. If it is already nearby another non-Ocean you stop here for that field, otherwise you need to reduce nonOceanBiomeLeft one more time and add one to something like int nonOceanBlocked (if your new field is without neighbor), this is to make sure you do not create a new noOcean biome somewhere and have none left to have the conditions fulfilled. So wenn you have none left you cannot create a noOcean biome.
If you have nonOceanBlocked > 0 you need to watch for the neighbor in the row above if it is an alone nonOcean biome (so save the neighbor info for each field or calculate it on the fly). If your neighbor in the row above is alone you need to add a noOcean and you remove one from nonOceanBlocked Since this one has a neighbor you don't need to increase nonOceanBlocked again.
Additionally if you create a new noOcean biome and the last field was an alone noOcean you can decrease nnoOceanBlocked too.
Be careful with
The last row: there you need to give the neighbors immediately and cannot wait for the next row, since there will be none.
If only nonOceanBiomeLeft is equal to one you cannot place it somewhere it has no neighbor, since you would need to d
This is only a theoretical description of what you could do, but for a college project I guess you should do most of the work yourself ;)
I hope it helps you as a starting point for the filling of the board.

Sudoku board generation logic in Java

I want to make a program that will randomly generate a sudoku board to play. For those not familiar with the game, you are given a 9x9 gameboard with mostly empty spaces and some numbers pre-filled in. To complete it you must fill in the empty squares so there is 1-9 in every row, column, and 3x3 square, but only once.
The way I am currently imagining it is to use a 2d array. I use a for loop within a for loop to populate it, making sure that the number going into the square is never one that has already been used in the same row or column.
The problem I am having is how to check if the number is already used in the 3x3 part of the grid. I was thinking about using a 3d array and the third dimension is where the 3x3 data is stored, but I don't know a simple way to decide which array to check in for the current square.
I also don't know for sure if randomly generating the tiles the way I am will always produce a complete board. I am worried it might get to one of the last few tiles and find that no number between 1 and 9 will fit in the square because it is already used. I don't know how to check if this is a possibility.
I did do a minimal amount of looking at other questions on the topic but I don't want to accidentally come across the answer, I just need a pointer in the right direction. Also none of them seemed to be directly related to what I am asking.
Hopefully what I am asking makes sense, it is a little difficult to describe in text. I would appreciate it if you could give me a pointer in the right direction without giving me the answer. Also if you don't know much about sudoku (why did you click on this question) you can play it here:
http://www.websudoku.com/
If you need clarification I will respond to comments as quickly as I can.
I'll try to just give you some hints rather than giving you the answers outright.
First, its a great idea to use a 2d array -- that is exactly what a sudoku board is. As for your 3d array idea, it is a bit overcomplicated. Think about using mathematical functions to find the top corner of each 3x3 box (i.e. [0, 0], [0, 2], [2, 0], etc.) and use a for loop to traverse that 3x3 box (still in the 2d array). As for generating the board by putting numbers randomly in, it might not work, and board generation is maybe not as trivial as you might think provided you want each board to have only one correct solution. Make sure you can check board validity first, then take a look at the link posted by kenshinji.

Most efficient method to randomly generate a location on some certain area?

I am working on a "greedy snake" game. I am using a 2d array to store the value of each location/grid of the map: either egg or snake body or empty. The egg needs to be generated on the empty spot. One solution could be:
while (new egg location overlaps snake body)
Within the range of 2d array randomly generate an egg location
However when the snake grows very big and fills up most area of the map, the generating new egg become very inefficient, since it has to check almost every element of the 2d array. How can this be optimized?
Maintain a list of all empty squares. Every time you need a new random empty square use:
Collections.shuffle(list).get(0);
First, I would like to say that there is nothing wrong with your solution. The only issue you get is that late game (when most of the squares are taken up by the snake) you may have to try a large number of times to find an empty space.
In this situation OldCurmudgeon's solution is a good fit. However, it suffers from a different issue. Maintaining a list of empty squares from a large empty grid is a waste of time.
So early in the game, your current solution is preferable. But late game their solution is better.
So I would suggest doing a check on the size of the snake. If the snake takes up less than half of the grid use your current solution. Only when the snake takes up more than half of the grid start maintaining a list of empty squares.
Give all the spaces the snake currently occupies as an input and then check from the remainder. Won't quite get to O(1) but will reduce how much of your array it needs to go through.
public Point generateRandomPoint(){
Random rand = new Random();
Point p;
boolean goodPoint = false;
//while the point selected is not empty
while (goodPoint!=true){
p= new Point(rand.nextInt(MAX_X),rand.nextInt(MAX_Y));
//is the point empty
goodPoint = array[p.x][p.y].equals("empty");
}
return p;
}
If you use this, then it only checks the space that the egg would be spawned on. Now, because it is random, it may have to check a lot of spaces, but unless your board is a couple thousand across, it should be almost instant (<<50 ms).

TicTacToe AI - Computer Winning move java

is there a way of getting the winning move for AI on TicTacToe using for loop. So checking if any two buttons next to each other have the value X or O then make the third make the same value to make the AI win.
Using a for loop to go through array of 3 by 3 buttons and checking if any two buttons next to each other has the same value.
I have tried this but not sure if its correct because it isn;t working the computer doesn't make any winning move.
For easier understanding, you could make multiple loops for row/column/diagonal each:
Count X or O in one row/column/diagonal, if it equals 2, add the third one in the remaining field (if it is empty)
There are MANY ways to accomplish what you want. You could even bruteforce every possible move, count the winning results and chose the one with the most possibilities.
Another easy way would be to write a method which will check for every field if it blocks an opponent winning move and/or results in a winning move for oneself.
A common A.I. algorithm in gaming is The Min/Max Algorithm Basically, a player looks ahead to evaluate the state of the game resulting from every possible sequence of events, and chooses the move such as to maximize their chances of winning.
For tic-tac-toe you may want to consider starting with a player and looking at all of the possible child states that could follow a given state. You could evaluate some score such as whether the move leads you to a state where you have 2 x's lined up. You then propagate this score up your tree, so the current player has an informed decision to make.'
Min-max assumes your opponent is playing perfectly, so you can sometimes encounter problems there.
For a good description of A.I. and the tic-tac-toe problem check out Artificial Intelligence: A Modern Approach Chapter 5, adversarial search, covers gaming and specifically refers to tic-tac-toe.

Efficient algorithm for collisions in 2D game?

I'm programming a Bomberman in Java following a tutorial (this is my first game).
The tutorial suggests the following code for detecting collisions.
for (int p=0; p<entities.size(); p++) {
for (int s=p+1; s<entities.size(); s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
him.collidedWith(me);
}
}
By now, entities is an array list containing the enemies and the player.
As I want to also detect the player collides with walls, should I put every single wall or bricks tile in the level into the entities arraylist? If so, isn't this algorithm very inefficient? These tiles aren't going to collide with other tiles, so I was thinking to manage game entities in different lists. What do you suggest? Is there a more efficient algorithm to do it?
Note: I already read other questions related to collisions in 2D games.
Thanks a lot.
I suggest reading this excellent article about how ghost movement and collision detection works in PacMan.
Then I would suggest logically modeling your Bomberman levels as a collection of tiles. Each tile represents a discrete position in your level, and it is not logically possible to ever be "between" tiles or occupying two tiles at the same time. Each tile can track what sort of terrain feature is currently on it, and whether or not it is a valid destination tile for the player (and the enemies, potentially with different rules for each if the enemies are allowed to traverse terrain that is normally impassable for the player).
Then you don't need a collision detection algorithm for every object in the world. When it comes time for an enemy to move, or when the user tries to move their character, all you have to do is check all the tiles that are adjacent to their current tile (4, or 8 max if you allow diagonal movement), see if each tile represents a valid movement direction, and block the movement if it is not in a valid direction.
And to answer your question, yes, iterating every object in the world on every position update will be very inefficient.
There is another way to use grids for collision system. I'm using more complex version of the Aroth's suggestion and using this to fix collision bugs.
Theoretically this system is the fastest(assuming you are doing this check if(Grid[x][y] ==true)) because it only uses a single Boolean check for each entity(the things that can move).
Note: In the above grid check example, I've used a 2 dimensional array of booleans that sets the coordinates of impassable grids to false.`
If you are not worried about physics like bouncing from a wall you can use this:
1- Divide the map into grids.
2- Making every entity only fill a tile would be better but not necessary.
3- Store the previous position or the grid of the entities.
4- Whenever an entity moves, before visually updating their location (also before
doing other calculations) check the grids they are in. If they are in grid
that is not empty or simply in a grid that they are not supposed to
be, return their position back to the previous position (which you have stored).
If you want to allow entities to move freely inside the grids(the grids are bigger than the minimum distance they can move) then you need to put them adjacent to the grids they've entered and they weren't supposed to. Otherwise just return them back to the previous grid.
If you want them to bounce from the wall you can still use this but I'm not sure how many features can be added to a collision system like this.
May I recommend my own project. But it's still wip.
https://github.com/YagaoDirac/Dirac-2d-collision-detection-for-games
It's based on quad-tree which handles sparse pretty well.
It supplies collision group. This conception is also used in both UE and Unity.
It support only circle vs circle and overlapping only for now(2022 feb 22).
I plan to make at least AABB, and collision which at least stop your pawn from leaving the map.
I may also provide another system based on fixed grid.

Categories

Resources