我最近开始用Java开发基本的“战舰”游戏。
我已经创建了包含每艘船位置的比赛场。现在,我想允许用户为程序提供坐标。如果所讨论的坐标与船的位置重叠,则应将该特定的船从ships队列中移出。
我已经尝试了包中的Scanner类,但java.util没有成功。如果有人可以帮助我解释基于文本的流中的二维坐标,那就太好了。坐标的语法应如下:x, y。很简单吧?
public static void main(String[] args)
{
// Position ships.
Scanner scanner = new Scanner(System.in).next();
List<Point> ships = new ArrayList<>(5);
ships.add(new Point(2, 1));
ships.add(new Point(3, 2));
ships.add(new Point(10, 4));
ships.add(new Point(7, 6));
ships.add(new Point(8, 4));
while(true)
{
// Check status.
if(ships.length > 0)
{
// Check if a field is containing a ship.
for(int y = 0; y < 10; y++)
{
for(int x = 0; x < 40; x++)
{
if (ships.contains(new Point(x, y)))
{
System.out.print('S');
}
else
{
System.out.print('.');
}
}
System.out.println();
}
// TODO: Query the input of the user.
final String input = scanner.next();
}
else
{
System.out.println("You won the game!");
break;
}
}
}
问题来源:Stack Overflow
public static void main(String[] args) {
Point[] shipPositions = new Point[5];
shipPositions[0] = new Point(2, 1);
shipPositions[1] = new Point(3, 2);
shipPositions[2] = new Point(10, 4);
shipPositions[3] = new Point(7, 6);
shipPositions[4] = new Point(8, 4);
//Player input
System.out.println("Coordinates needed");
Scanner in = new Scanner(System.in);
int x, y;
System.out.print("x=");
x = in.nextInt();
System.out.print("y=");
y = in.nextInt();
Point p = new Point(x, y);
if (Arrays.asList(shipPositions).contains(p)) {
System.out.print("Hit");
} else {
System.out.print("Miss");
}
}
例
Coordinates needed
x=2
y=1
Hit
问答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。