【问题标题】:Assistance with creating grid/ball (objects?) in Java协助在 Java 中创建网格/球(对象?)
【发布时间】:2016-12-02 21:50:23
【问题描述】:

我正在尝试创建一个 Roomba 程序,其中包含一个在屏幕上弹跳的球,用于清理它经过的瓷砖。程序应该从所有灰色瓷砖开始,当球越过它们时,瓷砖变成白色。目前我有一个到处反弹的球和一个创建 5x5 网格的网格方法。

我遇到了两个问题:

  1. 在运行程序时,我无法让网格和球出现在同一个模拟中,要么是一个,要么是另一个。

  2. 我无法找到一种方法来分析球是否经过网格中的某些方格,也许我需要为网格/球创建一个对象?

我的代码:

import edu.princeton.cs.introcs.StdDraw;

public class Roomba {

private static int windowWidth = 200;
private static int windowHeight = 200;

private static double x = 100;
private static double y = 100;
private static double vx = 2;
private static double vy = 4;
private static int radius = 5;

private static boolean inGame = true;

public static void updateLocations() {
    x += vx;
    y += vy;
}

public static void drawGrid() {
    StdDraw.setScale(0, 5);

    int[][] grid = new int[5][5];

    for (int x = 0; x < grid.length; x++) {
        for (int y = 0; y < grid.length; y++) {
            grid[x][y] = 255;
        }
    }

    for (int x = 0; x < grid.length; x++) {
        for (int y = 0; y < grid.length; y++) {
            StdDraw.square(x, y, 1);
        }
    }

}

public static void updateVelocities() {

    if (y + radius >= windowHeight) {
        vy = -vy;
    } else if (y - radius <= 0) {
        vy = -vy;
    }

    if (x >= 194 || x <= 6) {
        vx = -vx;
    }

}

public static void setBackground() {
    StdDraw.clear(StdDraw.GRAY);
//      drawGrid();
}

public static void drawBall() {
    StdDraw.setPenColor(StdDraw.BLACK);
    StdDraw.filledCircle(x, y, radius);
    // StdDraw.setPenColor(StdDraw.RED);
    // StdDraw.filledSquare(x + 3, y + 3, 1);
    StdDraw.setPenColor(StdDraw.BLACK);
    StdDraw.text(100, 70, "x is: " + x + " y is: " + y);

}

public static void draw() {
    setBackground();
    drawBall();
}

public static void main(String[] args) {
    StdDraw.setCanvasSize(800, 800);

    StdDraw.setXscale(0, windowWidth);
    StdDraw.setYscale(0, windowHeight);

    while (true) {
        if (inGame) {
            draw();
            updateVelocities();
            updateLocations();
        } else {
            StdDraw.text(100, 100, "Game Over");
        }

        // change to if all tiles have been cleaned
        // if (x + radius > windowWidth || x - radius < 0) {
        // inGame = false;
        // }

        StdDraw.show(20);
    }
}
}

【问题讨论】:

    标签: java object graphics grid simulation


    【解决方案1】:

    也许背景是在球上绘制的,反之亦然?先画球再画背景?确保球实际上以正确的大小渲染,而不是整个屏幕。我不熟悉 2D 图形,但也许有一些 z 战斗?

    【讨论】:

    • 尝试使用顺序但没有运气,当尝试绘制它们时,它们出现在第一帧而不是后续帧。
    猜你喜欢
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多