[英]Lights out game using 2d arrays
我正在嘗試制作一款燈光游戲,我簡化了游戲,一次只能更改一個圖塊,但我仍然遇到一個錯誤。 我可以單擊以將黃色從黃色更改為黑色,但是我不能單擊而發生相反的情況。 如果您不熟悉,這里是游戲: http : //www.logicgamesonline.com/lightsout/
我的代碼:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
public class LightsOutPanel extends JPanel implements MouseListener {
private boolean[][] lights;
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Lights Out!");
frame.setResizable(false);
frame.setVisible(true);
LightsOutPanel panel = new LightsOutPanel();
if (panel.lights == null) {
System.out.println("You did not initialize your light array!" +
"It's still null...");
System.exit(-1);
}
panel.addMouseListener(panel);
panel.setPreferredSize(new Dimension(601, 501));
panel.setMinimumSize(new Dimension(601, 501));
Container c = frame.getContentPane();
c.setLayout(new BorderLayout());
c.add(panel, BorderLayout.CENTER);
frame.pack();
}
public LightsOutPanel() {
lights = new boolean[5][6];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
lights[i][j] = true;
}
}
}
// unused methods
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void paint(Graphics g) {
int boxWidth = 600 / 6;
int boxHeight = 500 / 5;
int y = 0;
for (int row = 0; row < 5; row++) {
int x = 0;
for (int col = 0; col < 6; col++) {
if (lights[row][col]==true) {
g.setColor(Color.YELLOW);
} else {
g.setColor(Color.BLACK);
}
g.fillRect(x, y, boxWidth, boxHeight);
g.setColor(Color.BLUE);
g.drawRect(x, y, boxWidth, boxHeight);
x += boxWidth;
}
y += boxHeight;
}
}
// called when the mouse is pressed - determines what row/column the user
// has clicked
public void mousePressed(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
int panelWidth = getWidth();
int panelHeight = getHeight();
int boxWidth = panelWidth / lights[0].length;
int boxHeight = panelHeight / lights.length;
int col = mouseX / boxWidth;
int row = mouseY / boxHeight;
toggle(row, col);
repaint();
}
// called to "toggle" the selected row and column, as well as the four
// adjacent lights
public void toggle(int row, int col) {
if (row >= 0 && col >= 0 && row < lights.length &&
col < lights[0].length)
{
if (lights[row][col] = true) {
lights[row][col] = false;
} else {
lights[row][col] = true;
}
}
}
}
您的“核心”問題出在您的toggle
方法中...
if (lights[row][col] = true) {
=
是一項賦值,因此您說將true
賦給lights[row][col]
,如果lights[row][col] == true
請執行以下操作……所以它始終是true。
一種更簡單的方法是...
lights[row][col] = !lights[row][col];
不,如果是,很簡單。
您還應該查看AWT中的繪畫和Swing和執行自定義繪畫 。 您違反了paint方法的鏈式合同(未調用super.paint
)
而不是覆蓋paint
,您應該使用paintComponent
,並且應該在執行任何自定義繪制之前調用super.paintComponent
,這將確保為您准備好Graphics
上下文
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.