Creating Multiple Rectangle Objects at Once (Java) - java

First off, thanks for just clicking this :) I'm an amateur student coder, and I'm creating a (horrible) version of Pacman. I'm trying to create rectangles for each of my dots on my 1000x650 applet screen, so I can create an if statement when Packages hit box touches them, they disappear.
My problem is, I want to create a class so I can create the rectangles easily and have only 1 if statement, and not one for each dot rectangle (trying to learn to be efficient :P)
If I didn't elaborate enough, I'll be wary to bring edits based on your responses, and thanks!!!
(Edit 1: Fixed a run on sentence xD)

If you need to fill rectangles on both X and Y (Matrix), you most probably need nested loops.
Let's consider you want to a 5 * 5 rectangle every 100 pixels in the width with a 50 pixels spacing in the height:
for(int x = 0;x<1000;x+= 100)
{
for(int y=0;y<650; y+= 50)
{
drawRectangle(x, y, 5, 5); // Considering drawRectangle(x, y, width, height)
}
}

Try this code, it will return true when it collides with the dot.
Object pacman = new Object();
pacman.xcoord = null;
pacman.ycoord = null;
final int dotsInStage = 50;
// add other properties
int xcoords[] = new int[dotsInStage];
int ycoords[] = new int[dotsInStage];
Call this Boolean:
public boolean dotCollison (int xcoords[], int ycoords[], Object pacman) {
loop = 0;
while (loop <= dotsInStage) {
if (pacman.xcoord = xcoords[loop] && pacman.ycoord = ycoords[loop]) {
return true;
break;
}
}
}
To add the rectangles, try:
int loop = 0;
while (loop <= dotsInStage) {
Graphics.drawRectangle (xcoord[loop] , ycoord[loop] , xcoord[loop] + 10 , ycoord[loop] + 10);
}
Hope it works and happy coding!

I'm not totally comprehending your question. But
Couldn't you just create a 2 d array use a nested for loop
For( int I = 0; I<array.length;i++){
For (int j = 0; j <array[0].length;I++){
//fill w/ rectangles
array[I][j]= ;
}}

You can use a for statement which repeadly loops untill a condition is met.
This is the general structure:
for (counterInitialization; terminatingCondition; incrementLoopsCount) {
statement(s);
}
And this is an example in which the loop continue for as long as the counter i<n):
int n = 50;
for(int i = 0;i<n;i++){
//code for creating a rectangle
...
}
I suggest you give this a read.

Related

Find element position array in java

I need to write some methods for a game in java and one of them is int[] findStone. The method returns an array, which gives the coordinate of the element that I am searching.
The field looks like this and is defined like this: private static int[][] gamefield = new int[8][6];
So if I use the method: findStone(3)[0], it should return 0 for the x coordinate and for findStone(3)1, 2. This is the code that I wrote.
private static int[] findStone(int stone) {
int[] position = new int[2];
for(int x = 0; x < 8; x++ ){
for(int y = 0; y < 6; y++ ) {
int a = gamefield[x][y];
int i = x;
int j = y;
if(a == stone) {
position[0] = i;
position[1] = j;
}
break;
}
}
return position;
}
The problem is: The method only returns the x-coordinates for the first row corectly, for the other elements it shows me 0. Could someone explain me what I did wrong and what I should change? Please, only simple explanation. I am only at the beginning and I don't have experience in java.
Thank you :)
You probably intended to put your break clause inside the if block. The way you have it now, the break keyword has no effect. It just breaks the inner loop (with y variable), but since this block of code ends here anyway, it simply does nothing.
You're searching for a single point on your map, so when you find the stone position, you can immediately return it, as there's nothing more to do.
Moreover, you don't need additional variables, a, i and j. Using them is not wrong, but code looks clearer and is more concise without them. Have a look at this code:
private static int[] findStone(int stone) {
int[] position = new int[2];
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 6; y++) {
if (gamefield[x][y] == stone) {
position[0] = x;
position[1] = y;
return position;
}
}
}
return null; // if there's no given stone
}

Java 1 million index array of 1x3 arrays - memory and efficiency

I am doing some coding practice during my free time using some coding challenges posted on AdventOfCode.com
Challenge #6 involves turning 1 million (virtual) lights on and off with a set of hundreds of instructions. I find myself unable to even populate an ArrayList that is large enough to handle all of these "lights"
I decided to start the challenge by making a 1000x1000 array of 1x3 arrays which contain "x-coordinate" "y-coordinate" "on/off"
I have very limited experience with java efficiency (besides common sense) and I would greatly appreciate some direction.
Here is the challenge if you are interested: http://adventofcode.com/day/6
And here is my code so far, which sadly does not run past index ~7000 on my craptop (4gb RAM) - i do have a fancy desktop at home though.
I would appreciate some guidance regarding how to approach this problem with better memory and speed efficiency. I am a learning programmer and I will appreciate legitimately any guidance, whatever it may be. (Links/locations for learning are appreciated as well)
import java.util.ArrayList;
public class Day6 {
public static void main(String[] args) {
ReadFileClass myReaderClass = new ReadFileClass();
ArrayList<String> allLines = myReaderClass.readFile("/C:/Users/Steven/Desktop/Day6.txt");
ArrayList<ArrayList<Object>> lightArray = new ArrayList<>();
for(int i = 0; i<=999999; i++){
if(i%1000 ==0) System.out.println(i); //To see how fast/far the array populates
int x;
int y;
String status = "off";
for(int j = 0; j<=999; j++){
x = j;
y = i%999;
ArrayList<Object> innerArray = new ArrayList<>();
innerArray.add(x);
innerArray.add(y);
innerArray.add(status);
lightArray.add(innerArray);
}
}
System.out.println(lightArray);
}
}
Edit 1: I dunno what happened with the ArrayLists exactly (garbage accumulation maybe?) but I switched to a byte array and handle coordinate-->index conversions with a method now and I am smooth sailing. I'll post my final code once I'm finished fixing a small algorithm mistake (I misread the problem slightly). Thank you for your various suggestions!
Edit 2: My code works as intended now. Here it is, for anyone who is interested :)
import java.util.ArrayList;
public class Day6 {
public static void main(String[] args) {
ReadFileExample myReaderClass = new ReadFileExample();
ArrayList<String> allLines = myReaderClass.readFile("/C:/Users/Steven/Desktop/Day6.txt");
byte[] lightArray = new byte[1000000];
for(int i = 0; i<=999999; i++){
lightArray[i] = 0;
}
for(String s : allLines){
int x1, x2, y1, y2;
int indexOfFirstNumber = -1;
String nums = "0123456789";
for(int i = 0; i<s.length();i++){
if(nums.indexOf(s.substring(i,i+1))!=-1){
indexOfFirstNumber = i;
break;
}
}
int IOfirstComma = s.indexOf(",");
int indexOfThrough = s.indexOf("through");
int indexOfX2 = indexOfThrough+8;
int IOsecondComma = s.indexOf(",", IOfirstComma+1);
x1 = Integer.parseInt(s.substring(indexOfFirstNumber, IOfirstComma));
y1 = Integer.parseInt(s.substring(IOfirstComma+1, s.indexOf(" ", IOfirstComma)));
x2 = Integer.parseInt(s.substring(indexOfX2, IOsecondComma));
y2 = Integer.parseInt(s.substring(IOsecondComma+1,s.length()));
ArrayList<Integer> indexesToChange = coordinateRangeToIndexArray(x1, y1, x2, y2);
if(s.substring(0,8).equals("turn off")){
for(int i : indexesToChange){
lightArray[i] = 0;
}
}
else if(s.substring(0,7).equals("turn on")){
for(int i : indexesToChange){
lightArray[i] = 1;
}
}
else if(s.substring(0,6).equals("toggle")){
for(int i : indexesToChange){
if(lightArray[i] == 1){
lightArray[i] = 0;
}
else{
lightArray[i] = 1;
}
}
}
else{
System.out.println("Error: Command not recognized");
}
}
//calculate number of lights that are on
int totalNumLightsOn = 0;
for(int i = 0; i<lightArray.length;i++){
if(lightArray[i] == 1){
totalNumLightsOn++;
}
}
System.out.println(totalNumLightsOn);
}
static ArrayList<Integer> coordinateRangeToIndexArray(int x1, int y1, int x2, int y2){
//Given two coordinates, create an array of all the indexes the smallest possible rectangle encompasses
final int ROW_SIZE = 1000;
ArrayList<Integer> affectedIndexes = new ArrayList<>();
for(int row = x1; row<=x2; row++){
for(int column = y1; column<=y2; column++){
affectedIndexes.add(column*ROW_SIZE+row+1);
}
}
return affectedIndexes;
}
}
The most memory efficient way would be to use a BitSet, in which case it would take you 1,000,000 bits (or one megabit) of memory (and the obvious additional few bytes) to store the on/off status. The individual bits can be operated on easily with the included methods.
Congratulations on solving your challenge.
1.000.000 Objects of each 1kb should take about 1.000 mb or ~ 1gb.
When I read your post I thought
Map <Integer,Lightswitch> = new HashMap <Integer,Lightswitch>();
Maybe start with a basic (empty) Lightswitch
public class Lightswitch {
}
and add 1.000.000 of those into the map.
Or (just thinking):
byte [] switches = new byte [1000000];
And then the byte value represents the lightswitch status ('0', '1', ...)
Just make 2-dimensional integer array of 1000X1000 and fill it with 0's then follow the instructions using file handling. For example for turning on light change 0 to 1.

Minimax Connect 4 AI trouble

I am making connect 4 AI, except the game continues until all 42 spaces are filled.
Score is kept by every 4 in a row gets 1 point.
public int[] Max_Value(GameBoard playBoard, int depth){
GameBoard temp = new GameBoard(playBoard.playBoard);
int h = 0, tempH = 999, tempCol=0;
int myDepth = depth - 1;
int[] tempH2 = new int[2];
boolean noChildren = true;
if(myDepth != -1){
for(int i = 0; i < 7; i++){
if(temp.isValidPlay(i)){
count++;
temp.playPiece(i);
noChildren = false;
tempH2 = Min_Value(temp, myDepth);
if(tempH2[1] < tempH){
tempH=tempH2[1];
tempCol = i;
}
temp.removePiece(i);
}
}
}
int[] x = new int[2];
if(noChildren){
h = temp.getHeuristic();
}
else{
h = tempH;
x[0]=tempCol;
}
x[1]=h;
return x;
}
public int[] Min_Value(GameBoard playBoard, int depth){
GameBoard temp = new GameBoard(playBoard.playBoard);
int h = 0, tempH = -999, tempCol=0;
int myDepth = depth - 1;
int[] tempH2 = new int[2];
boolean noChildren = true;
if(myDepth != -1){
for(int i = 0; i < 7; i++){
if(temp.isValidPlay(i)){
count++;
temp.playPiece(i);
noChildren = false;
tempH2 = Max_Value(temp, myDepth);
if(tempH2[1] > tempH){
tempH=tempH2[1];
tempCol = i;
}
temp.removePiece(i);
}
}
}
int[] x = new int[2];
if(noChildren){
h = temp.getHeuristic();
}
else{
h = tempH;
x[0]=tempCol;
}
x[1]=h;
return x;
}
I feel like I just stumbled through everything, and it feels like terrible code. However, I have never attempted anything like this before, and would appreciate any input. I can't tell where I am going wrong. My evaluation function just gives 1 point for each 4 in a row it can find for any given state. The main function calls the Min_Value function to start things off with a depth of 10.
I am attempting to return the column as well as the value of the heuristic. I hope I have provided enough information. Thanks for any insight.
Allright, after implementing the methods not shown (like evaluation, playmove, remove etc.) I was able to debug this. Assuming that these functions are implemented in some correct way in your version, the mistake is that you never actually call the evaluation function if depth is -1:
You have this:
[...]if(myDepth != -1)
{/*restofthecode*/}[...]
But what you need is something like this:
[...]if(myDepth == -1)
{
return temp.getHeuristic();
}
/*restofthecode*/
[...]
That way, whenever you reach depth -1 (a leaf in your minimax tree), the board will be evaluated and the value returned (which is excactly what you need in minimax).
Do this modification in both parts (min and max) and everything shuold be allright. If there are other problems, feel free to ask.
Even though it isn't stated in the question, I think you are not getting good moves from your search, right?
Without looking through your while code, I can already say that your program will only work during the last 10 moves of the game (last 10 empty fields or forced win in 10). Otherwise, your program will return either the last or the first move it evaluated. That is because of your evaluation function, where you only handle a win (respectively 4 in a row), but not 2 in a row, traps, 3 in a row, etc.). It will think of all moves as equal if it can't force a win.
This is a problem, because starting with an empty field, a win can only be forced by the starting player, and just with the 2nd last piece to be placed on the board. (In your version 4 in a row forced).
And since your searchdepth (10) is smaller than the maximum game moves (42), your program will always play its first move.
If the rest of your algorithm is correctly implemented, you can fix this by simply improve your evaluation function, so that it can differ between "good" and "bad" game positions.

When navigating a 2D array, check neighboring elements for valid path relative to point of entry?

The nature of this problem has changed since submission, but the question isn't fit for deletion. I've answered the problem below and marked it as a community post.
I'm writing a recursive path-navigating function and the final piece I need involves knowing which cell you came from, and determining where to go next.
The Stage
You are given a 2d array where 0's denote an invalid path and 1's denote a valid path. As far as I know, you are allowed to manipulate the data of the array you're navigating, so I mark a traveled path with 2's.
The Goal
You need to recursively find and print all paths from origin to exit. There are four mazes, some with multiple paths, dead ends, or loops.
I've written code that can correctly handle all three cases, except the method for finding the next path is flawed in that it starts at a fixed location relative to your current index, and checks for a travelled path; If you encounter it, it's supposed to retreat.
While this works in most cases, it fails in a case when the first place it checks happens to be the place you came from. At this point, it returns out and ends prematurely.
Because of this, I need to find a way to intelligently start scanning (clockwise or anti-clockwise) based on where you came from, so that that place is always the last place checked.
Here is some code describing the process (note: edge cases are handled prior to this, so we don't need to worry about that):
private static void main()
{
int StartX = ;//Any arbitrary X
int StartY = ;//Any arbitrary Y
String Path = ""; //Recursive calls will tack on their location to this and print only when an exit path is found.
int[][] myArray = ;//We are given this array, I just edit it as I go
Navigator(StartX, StartY, Path, myArray);
}
private static void Navigator(int locX, int locY, String Path, int[][] myArray)
{
int newX = 0; int newY = 0;
Path = Path.concat("["+locX+","+locY+"]");
//Case 1: You're on the edge of the maze
boolean bIsOnEdge = (locX == 0 || locX == myArray.length-1 || locY == 0 || locY == myArray[0].length-1);
if (bIsOnEdge)
{
System.out.println(Path);
return;
}
int[][] Surroundings = surroundingsFinder(locX, locY, myArray);
for (int i = 0; i <= 7; i++)
{
//Case 2: Path encountered
if (Surroundings[0][i] == 1)
{
myArray[locX][locY] = 2;
newX = Surroundings[1][i];
newY = Surroundings[2][i];
Navigator(newX, newY, myArray, Path);
}
//Case 3: Breadcrumb encountered
if (Surroundings[0][i] == 2)
{
myArray[locX][locY] = 1;
return;
}
}
}
//generates 2D array of your surroundings clockwise from N to NW
//THIS IS THE PART THAT NEEDS TO BE IMPROVED, It always starts at A.
//
// H A B
// G - C
// F E D
//
static int[][] surroundingsFinder(int locX, int locY, int[][] myArray)
{
int[][] Surroundings = new int[3][8];
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
}
}
//Can be done simpler, is done this way for clarity
int xA = locX-1; int yA = locY; int valA = myArray[xA][yA];
int xB = locX-1; int yB = locY+1; int valB = myArray[xB][yB];
int xC = locX; int yC = locY+1; int valC = myArray[xC][yC];
int xD = locX+1; int yD = locY+1; int valD = myArray[xD][yD];
int xE = locX+1; int yE = locY; int valE = myArray[xE][yE];
int xF = locX+1; int yF = locY-1; int valF = myArray[xF][yF];
int xG = locX; int yG = locY-1; int valG = myArray[xG][yG];
int xH = locX-1; int yH = locY-1; int valH = myArray[xH][yH];
int[][] Surroundings = new int[3][8];
Surroundings[0][0] = valA; Surroundings[1][0] = xA; Surroundings[2][0] = yA;
Surroundings[0][1] = valB; Surroundings[1][1] = xB; Surroundings[2][1] = yB;
Surroundings[0][2] = valC; Surroundings[1][2] = xC; Surroundings[2][2] = yC;
Surroundings[0][3] = valD; Surroundings[1][3] = xD; Surroundings[2][3] = yD;
Surroundings[0][4] = valE; Surroundings[1][4] = xE; Surroundings[2][4] = yE;
Surroundings[0][5] = valF; Surroundings[1][5] = xF; Surroundings[2][5] = yF;
Surroundings[0][6] = valG; Surroundings[1][6] = xG; Surroundings[2][6] = yG;
Surroundings[0][7] = valH; Surroundings[1][7] = xH; Surroundings[2][7] = yH;
return Surroundings;
}
Can anyone help me with this? As you can see, surroundingsFinder always finds A first, then B all the way to H. This is fine if and only if you entered from H. But if fails on cases where you entered from A, so I need to make a way to intelligently determine where to start finding. Once I know this, I can probably adapt the logic so I no longer use a 2D array of values, as well. But so far I can't come up with the logic for the smart searcher!
NOTE: I am aware that Java does not optimize middle-recursion. It seems impossible to get tail recursion working for a problem like this.
The Solution
The initial goal was to print, from start to end, all of the paths that exit the array.
An earlier rendition of the script wrote "0" on treaded locations rather than "2", but for some reason I imagined that I needed the "2" and I needed to differentiate between "treaded path" and "invalid path".
In fact, due to the recursive nature of the problem, I discovered that you can in fact solve the problem writing only 0's as you go. Also, I no longer needed to keep track of where I came from and instead of checking clockwise over a matrix, I was iterating from left to right down the 3x3 matrix surrounding me, skipping my own cell.
Here is the completed code for such a solution. It prints to console upon finding an exit (edge) and otherwise traces itself around the maze, complete with recursion. To start the function, you are given a square 2D array of 0's and 1's where 1 is a valid path and 0 is invalid. You are also given a set of coordinates where you are "dropped in" (locX, locY) and an empty string that accumulates coordinates, forming a path that is later printed out (String Path = "")
Here is the code:
static void Navigator(int locX, int locY, int[][] myArray, String Path)
{
int newX = 0;
int newY = 0;
Path = Path.concat("["+locX+","+locY+"]");
if ((locX == 0 || locX == myArray.length-1 || locY == 0 || locY == myArray[0].length-1))
{//Edge Found
System.out.println(Path);
pathCnt++;
myArray[locX][locY] = 1;
return;
}
for (int row = -1; row <= 1; row++)
{
for (int col = -1; col <= 1; col++)
{
if (!(col == 0 && row == 0) && (myArray[locX+row][locY+col] == 1))
{ //Valid Path Found
myArray[locX][locY] = 0;
Navigator(locX+row, locY+col, myArray, Path);
}
}
}
//Dead End Found
myArray[locX][locY] = 1;
return;
} System.out.println(Path);
pathCnt++;
swamp[locX][locY] = 1;
return;
}
for (int row = -1; row <= 1; row++)
{
for (int col = -1; col <= 1; col++)
{
if (!(col == 0 && row == 0) && (swamp[locX+row][locY+col] == 1))
{ //Valid Path Found
swamp[locX][locY] = 0;
Navigator(locX+row, locY+col, swamp, Path);
}
}
}
//Dead End Found
swamp[locX][locY] = 1;
return;
}
As you may determine yourself, every time we "enter" a cell, we have 8 neighbors to check for validity. First, to save on run time and to avoid going out of the array during our for loop (it can't find myArray[i][j] if i or j point it outside, and it will error out), we check for edges. Since we're given the area of our swamp we use a truth comparison statement that essentially says ("(am I on the top or left edge?) or (am I on the bottom or right edge?)"). If we ARE on an edge, we print out the Path we're holding (thanks to deep copy, we have a unique copy of the original Path that only prints if we're on an edge, and includes our full set of coordinates).
If we aren't on an edge, then we start looking around us. We start at top left and move horizontally to bottom right, with a special check to make sure we're not checking where we're standing.:
A B C
D . E
F G H
This loop checks only for 1's and only calls the function up again should that happen. Why? Because it is the second-to-last case. There is only one extra situation that will occur, and if we reach the end of the function it means we hit that case. Why write extra code (checking for 0's to specifically recognize it?
So, as I just mentioned, if we exit the for loop, it means we didn't encounter any 1's at all. It means we're surrounded by zeros! It means we've hit a dead end, and that means that all we have to do is error our away out of that instance of the function, ergo the final return;.
All in all, the final function is simple. But coming from no background and having to realize the patterns and meanings of these cases, and after several failed attempts at this, it can take quite a bit of work. I was several days at work on perfecting this.
Happy coding, Everyone!
Your issue seems to be with:
if (Surroundings[0][i] == 2)
{
myArray[locX][locY] = 1;
return;
}
Perhaps this should be changed to:
if (Surroundings[0][i] == 2)
{
// not sure why you need this if it's already 1
myArray[locX][locY] = 1;
// go to next iteration of the "i" loop
// and keep looking for next available path
continue;
}
Your recursive method will automatically return when none of the surrounding cells satisfy the condition if (Surroundings[0][i] == 1).
PS: It's conventional to name your variables using small letter as the first character. For example: surroundings, path, startX or myVar

Battleship-java games

im learning to create a java gameļ¼Œstill new to java. now i want to create a battleshipe game.
But now im stuck here. Now, when i randomly place the shipe as the computer board, sometime it will overlapping the previous ship, so it become not balance for then game. Second, after i get input from player, how do i put the input value into the board.
Here is the code i have:
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
public class Battleship
{
public static void main (String args[]){
String map [][][]=new String [10][10][2];
int row =0,col=0;
//initPlayerMap(map);
//printMap(map,true);// true to printout the map
placeShips(map); // place the shipe at computer map
initMap(map,"~", true);
initMap(map,"#",false);
placeShips(map); // place the shipe at computer map
printMap(map,true);
System.out.println("Now enter your coordinate of the boom");
row = getInput("Please enter row: ");
col = getInput("Please enter col: ");
printMap(map,false); // computer map
hitShip(row,col);
}
private static void hitShip (int row, int col){
if (map[startFrom++][colOrRow][1]== map[row][col][1]){
System.out.println("abc");
}
else
{
System.out.println("darn!");
}
}
private static void initMap(String map[][][] , String initChar, boolean player){
//the 0 in 3rd dimension is representing player map and 1 for computer
int mapNo= (player?0:1);
for (int i = 0 ; i < 10; i ++)
for (int j=0; j<10; j++)
map [i][j][mapNo]= initChar;
}
private static void printMap(String map[][][], boolean player){
int whichMap=0;
if (!player)
whichMap=1;
System.out.println(" 0\t1\t2\t3\t4\t5\t6\t7\t8\t9 ");
for (int i = 0 ; i < 10; i ++){
System.out.print(i+" ");
for (int j=0; j<10; j++){
System.out.print(map [i][j][whichMap]+ "\t");
}
System.out.print("\n");
}
}// end of printMap method
public static int getInput(String message){
Scanner sc = new Scanner (System.in);
System.out.print(message);
return sc.nextInt();
}
private static void placeShips(String[][][] grid)
{
char[] shipType = { 'B' , 'C' , 'F' , 'M' };
int[] shipSize = { 5 , 4 , 3 , 2 };
int[] shipNums = { 1 , 2 , 4 , 4 };
for (int x = 0 ; x < shipType.length ; x++)
for (int y = 1 ; y <= shipNums[x] ; y++)
{
String shipName = shipType[x]+""+y;
placeShip(grid,shipName,shipSize[x]);
}
}
private static void placeShip(String[][][] map, String shipName, int size){
int direction = (int)(Math.random()*2);// 0 or 1
int colOrRow = (int)(Math.random()*map.length); // pick
int startFrom =(int)(Math.random()*(map.length-size)); // which cell?
// placing the ship
for(int i=0; i < size; i++){
// weather is vertical or horizontal
// vertical
if (direction == 0 ){
map[startFrom++][colOrRow][1] = shipName;
}
else {
map[colOrRow][startFrom++][1] = shipName;
}
}
}
}
To start with, you haven't modeled this correctly (IMO)
I would utilize java.awt.Rectangle a lot more. I would start by making the board a Rectangle, then make each ship a Rectangle too. Because Rectangle (comes from Shape in fact) has the method contains(...) you should be able to quickly test whether your rectangles are overlapping.
As far as marking shots on the board, perhaps your Ships need to be defined as more than just rectangles - give them functionality for spots that have been hit. You can use java.awt.Point for hit / miss shots
I think you are asking two questions here, I'll answer them both.
To put a ship on the field and make sure they don't overlap, check if there is a ship in any of the squares you are trying to put your new ship into. Make a 2D array of booleans, in which you save on which square is a ship.
For the user input, what have you tried, and into what problems have you been running? Without anything to hold on to I cannot give you anything to work with. I'd suggest letting the user give two coordinates: the start and the end of the ship. Process that data.
You don't seem to be using a data structure to keep track of your "already filled" positions in your map. That way you can compare or "validate" what positions are not filled in your map.

Categories