gpt4 book ai didi

java - 使用矩阵创建迷宫(JAVA)

转载 作者:行者123 更新时间:2023-11-30 07:23:33 25 4
gpt4 key购买 nike

所以我试图用 Java 制作一个单一迷宫(没有生成器),但我遇到了障碍。我当前的代码将制作一个迷宫,并制作一个 jframe,但它不会对其进行着色...有没有办法使着色工作?

    import java.awt.*;
import javax.swing.*;
import java.lang.*;

public class ayy{

public static void main(String [] args){

JFrame frame = new JFrame("Maze");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(1000,1000);
frame.setVisible(true);

int width = 1;
int height = 1;

int [][] map= {
{0,0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,0,},
{2,1,1,1,0,0,0,0,0,0,},
{0,0,0,1,0,0,0,1,1,2,},
{0,0,0,1,0,0,0,1,0,0,},
{0,0,0,1,0,0,0,1,0,0,},
{0,0,0,1,1,1,1,1,0,0,},
{0,0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,0,}
};

for(int i=0;i<map.length;i++){
for(int j=0;j<map.length;j++){
switch(map[i][j]){
case 0:
class rectangle{

public void paint(Graphics g){
g.drawRect(1,1,1,1);
g.setColor(Color.red);
}
}
break;
case 1:
class rectangle2{

public void paint(Graphics g){
g.drawRect(1,1,1,1);
g.setColor(Color.yellow);
}
} break;
case 2:
class rectangle3{

public void paint(Graphics g){
g.drawRect(1,1,1,1);
g.setColor(Color.blue);
}
} break;
}
}
}
}
}

任何帮助都可以谢谢!

最佳答案

1-)不要在 Switch 案例上创建类,这不是一个好的做法。

2-)如果该类没有继承JComponent,那么它将无法重写paint或paintComponent方法,因为它没有它们。

3-)类名的首字母大写,并使用有意义的名称。

4-)修改您的代码,如下所示:

public class MazeApp extends JFrame {

public static void main(String[] args) {

JFrame frame = new JFrame("Maze");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(1000, 1000);
Maze brd = new Maze();
frame.add(brd);
frame.setVisible(true);
}
}


class Maze extends JPanel {

public Maze() {
}

protected void paintComponent(Graphics g) {
int width = 1;
int height = 1;

int[][] map = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{ 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, },
{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, },
{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, },
{ 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, },
{ 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, },
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, } };

for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map.length; j++) {
int factori = i * 50;
int factorj = j * 50;
switch (map[i][j]) {
case 0: {
g.setColor(Color.red);
g.fillRect(factori, factorj, 2, 2);

}
break;
case 1: {
g.setColor(Color.yellow);
g.fillRect(factori, factorj, 2, 2);

}
break;
case 2: {
g.setColor(Color.blue);
g.fillRect(factori, factorj, 2, 2);

}
break;
}
}
}
}
}

关于java - 使用矩阵创建迷宫(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37139906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com