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;
}
}
}
}
答案 0 :(得分:4)
首先,您尚未正确建模(IMO)
我会更多地利用java.awt.Rectangle。我首先将板子变成一个矩形,然后让每艘船都成为一个矩形。因为Rectangle(实际来自Shape)的方法包含(...),你应该能够快速测试你的矩形是否重叠。
至于在棋盘上标记镜头,也许你的船只需要被定义为不仅仅是矩形 - 给它们提供已被击中的点的功能。您可以使用java.awt.Point进行命中/未命中投射
答案 1 :(得分:0)
我想你在这里问两个问题,我会回答他们。
答案 2 :(得分:0)
您似乎没有使用数据结构来跟踪地图中“已填充”的位置。这样,您可以比较或“验证”地图中未填充的位置。