繁体   English   中英

阻止字符超出绑定的二维数组

[英]Stop character from going out of bound 2D array

我有这个游戏,用户选择角色的 position,然后角色开始随机移动。 我正在尝试确保角色不会 go 超出范围,如果超出范围,系统会随机选择一个新的 position 并且角色移动 60 次然后停止。 有人可以帮忙吗

import java.util.*;

public class a1 {

public static String map[][] = new String[21][21];
public static int x;
public static int y;

public static void main(String[] args) throws InterruptedException {

    fillGrid();

    System.out.println("Enter starting (x,y) cooridinates for the player (0-20)");

    try (Scanner sc = new Scanner(System.in)) {
        System.out.print("Enter X position: ");
        x = sc.nextInt();

        System.out.print("Enter Y position: ");
        y = sc.nextInt();
    }
    map[x][y] = " ## "; // Letter to represent the location of the player
    movement();

}

public static void fillGrid() {
    // place a square in each space of the array(grid)
    for (int i = 0; i < map.length; i++) {
        for (int j = 0; j < map[i].length; j++) {
            map[i][j] = " |_| ";
        }
    }
}

public static void showMap() {
    // display the map
    for (int i = 0; i < map.length; i++) {
        for (int j = 0; j < map[i].length; j++) {
            System.out.print(map[i][j]);
        }
        System.out.print("\n");
    }

    System.out.print("\n");
    System.out.print("\n");
}

private static void movement() throws InterruptedException {

    Random rand = new Random();

    for (int i = 0; i < 10; i++) {

        i = rand.nextInt(4);
        map[x][y] = " |_| ";

        if (i == 0) {
            y = y + 1;
        } else if (i == 1) {
            y = y - 1;
        } else if (i == 2) {
            x = x + 1;
        } else if (i == 3) {
            x = x - 1;
        }

        map[x][y] = "  X  ";
        showMap();
        Thread.sleep(300);
    }

}

}

您可以将玩家 position 夹在网格的边界

x = clamp(sc.nextInt(), 0, 21);
y = clamp(sc.nextInt(), 0, 21);


int clamp(int val, int min, int max){
    return Math.max(min, Math.min(max, val));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM