java - 如何启用点的坐标作为输入
问题描述
我最近开始用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;
}
}
}
解决方案
- 创建一个Scanner对象以获取玩家输入
- 读取 x 和 y 值
- 检查是否被击中
提示:将步骤 2 和 3 放在一个循环中
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
推荐阅读
- sql - PostgreSQL - 带有 id 的种子表
- reactjs - 展开单个映射项的省略号文本
- python-3.x - 如何在 Django runserver 中将环境变量添加到命令行
- node.js - 如何使用内容类型 ='application/x-protobuf' 在 node.js 中发布数据
- elasticsearch - Elastic Search 7:获取特定字段的不同命中
- javascript - 如何使用使用数组填充的javascript并使用依赖下拉列表预填充下拉列表
- kubernetes - traefik 安装 kubespray 后不显示 backend_requests 指标
- powerbi - 是否可以使用 M 语言发出 GraphQL 请求?
- gitlab - 无法使用 gitlab 帐户登录 weblate
- c++ - 使用 M1 芯片在 Xcode 12.4 上构建 C++ 项目出现错误:链接库 libntl.a 缺少此目标所需的一个或多个架构:x86_64