本文介绍了如何添加可以在我的生命
游戏程序中获取生成的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试让我的程序在单元格更改其形式的每个步骤中显示(首先在控制台中测试)计数.因此,计数应该从 0 开始,并在每次单元格更改其形式时递增.我试过这个,使用count++但是它不会增加1,而是给我随机数.任何帮助都感激不尽.
解决方案
使用
I'm trying to make my program display (testing in console first) the count number at each step where the cell changes its form. So the count should start from 0 and increment each time the cell changes its form. I tried this, using count++ however it doesn't increment by 1 but instead gives me random numbers. Any help will be much appreciated.
import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Image;
import java.awt.Graphics;
import javax.swing.SwingUtilities;
public class GameOfLife extends javax.swing.JFrame {
final int wid = 100, hei = 50;
public static int count;
boolean[][] currentMove = new boolean[hei][wid], nextMove = new boolean[hei][wid];
boolean play;
Image offScrImg;
Graphics offScrGraph;
public GameOfLife() {
initComponents();
offScrImg = createImage(jPanel1.getWidth(), jPanel1.getHeight());
offScrGraph = offScrImg.getGraphics();
Timer time = new Timer();
TimerTask task = new TimerTask(){
public void run(){
if(play){
System.out.println(count);
for(int i = 0; i < hei; i++){
for(int j = 0; j < wid; j++){
nextMove[i][j] = decide(i,j);
}
}
for(int i = 0; i < hei; i++){
for(int j = 0; j < wid; j++){
currentMove[i][j] = nextMove[i][j];
}
}
repain();
}
}
};
time.scheduleAtFixedRate(task, 0, 100);
repain();
}
private boolean decide(int i, int j){
int neighbors = 0;
if (currentMove[getTopRow(i - 1)][getLeftCol(j - 1)]) neighbors++;
if (currentMove[i][getLeftCol(j - 1)]) neighbors++;
if (currentMove[getBottomRow(i + 1)][getLeftCol(j - 1)] ) neighbors++;
if (currentMove[getBottomRow(i + 1)][j]) neighbors++;
if (currentMove[getBottomRow(i + 1)][getRightCol(j + 1)]) neighbors++;
if (currentMove[i][getRightCol(j + 1)]) neighbors++;
if (currentMove[getTopRow(i - 1)][getRightCol(j + 1)])neighbors++;
if(currentMove[getTopRow(i - 1)][j]) neighbors++;
if(neighbors == 3) {
count++;
return true;
}
if(currentMove[i][j] && neighbors == 2){
count++;
return true;
}
return false;
}
private int getLeftCol(int neighbourCol) {
return neighbourCol < 0 ? (wid-1) : neighbourCol;
}
private int getRightCol(int neighbourCol) {
return neighbourCol > (wid-1) ? 0 : neighbourCol;
}
private int getTopRow(int neighbourRow) {
return neighbourRow < 0 ? (hei - 1) : neighbourRow;
}
private int getBottomRow(int neighbourRow) {
return neighbourRow > (hei - 1) ? 0 : neighbourRow;
}
private void repain(){
offScrGraph.setColor(Color.RED);
offScrGraph.fillRect(0, 0, jPanel1.getWidth(), jPanel1.getHeight());
for(int i = 0 ; i < hei ; i++){
for(int j = 0 ; j < wid; j++){
if(currentMove[i][j]){
offScrGraph.setColor(Color.GREEN);
int x = j * jPanel1.getWidth()/wid;
int y = i * jPanel1.getHeight()/hei;
offScrGraph.fillRect(x, y, jPanel1.getWidth()/wid, jPanel1.getHeight()/hei);
}
}
}
offScrGraph.setColor(Color.BLACK);
for(int i = 1; i < hei;i++){
int y = i * jPanel1.getHeight()/hei;
offScrGraph.drawLine(0, y, jPanel1.getWidth(), y);
}
for(int j = 1; j < wid;j++){
int x = j * jPanel1.getWidth()/wid;
offScrGraph.drawLine(x, 0, x, jPanel1.getHeight());
}
jPanel1.getGraphics().drawImage(offScrImg, 0, 0, jPanel1);
}
@SuppressWarnings("unchecked")
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(102, 102, 102));
jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
jPanel1MouseDragged(evt);
}
});
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jPanel1MouseClicked(evt);
}
});
jPanel1.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
jPanel1ComponentResized(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 293, Short.MAX_VALUE)
);
jButton1.setText("Play");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Reset");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 323, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap())
);
pack();
}
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
}
private void jPanel1ComponentResized(java.awt.event.ComponentEvent evt) {
offScrImg = createImage(jPanel1.getWidth(), jPanel1.getHeight());
offScrGraph = offScrImg.getGraphics();
repain();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
play = !play;
if(play) jButton1.setText("Pause");
else jButton1.setText("Play");
repain();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
currentMove = new boolean[hei][wid];
repain();
}
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {
int j = wid * evt.getX() / jPanel1.getWidth();
int i = hei * evt.getY() / jPanel1.getHeight();
if(SwingUtilities.isLeftMouseButton(evt)){
currentMove[i][j] = true;
}else currentMove[i][j] = false;
repain();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GameOfLife().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
}
解决方案
This is how it can be done using a related code example.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GameOfLife extends JPanel {
private int row, col;
private boolean isLiving;
private static int generation = 0;
public static Random random = new Random();
public GameOfLife(int r, int c) {
this.row = r;
this.col = c;
MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
isLiving = !isLiving;
repaint();
}
};
this.addMouseListener(listener);
isLiving = random.nextBoolean();
}
public boolean isAlive(int neighbors) {
boolean alive = false;
if (this.isLiving) {
if (neighbors < 2) {
alive = false;
} else if (neighbors == 2 || neighbors == 3) {
alive = true;
} else if (neighbors > 3) {
alive = false;
}
} else {
if (neighbors == 3) {
alive = true;
}
}
return alive;
}
public void setAlive(boolean alive) {
isLiving = alive;
}
public boolean isLiving() {
return this.isLiving;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.isLiving) {
g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
} else {
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
public static void main(String[] args) {
final int s = 40;
JPanel ui = new JPanel(new BorderLayout(4, 4));
final JLabel generationLabel = new JLabel("0", JLabel.CENTER);
ui.add(generationLabel, BorderLayout.PAGE_START);
final GameOfLife[][] biosphere = new GameOfLife[s][s];
final JPanel gui = new JPanel(new GridLayout(s, s, 2, 2));
ui.add(gui);
for (int ii = 0; ii < s; ii++) {
for (int jj = 0; jj < s; jj++) {
GameOfLife cell = new GameOfLife(ii, jj);
cell.setPreferredSize(new Dimension(10, 10));
gui.add(cell);
biosphere[ii][jj] = cell;
}
}
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
boolean[][] living = new boolean[s][s];
for (int ii = 0; ii < s; ii++) {
for (int jj = 0; jj < s; jj++) {
int top = (jj > 0 ? jj - 1 : s - 1);
int btm = (jj < s - 1 ? jj + 1 : 0);
int lft = (ii > 0 ? ii - 1 : s - 1);
int rgt = (ii < s - 1 ? ii + 1 : 0);
int neighbors = 0;
if (biosphere[ii][top].isLiving()) {
neighbors++;
}
if (biosphere[ii][btm].isLiving()) {
neighbors++;
}
if (biosphere[lft][top].isLiving()) {
neighbors++;
}
if (biosphere[lft][btm].isLiving()) {
neighbors++;
}
if (biosphere[lft][jj].isLiving()) {
neighbors++;
}
if (biosphere[rgt][jj].isLiving()) {
neighbors++;
}
if (biosphere[rgt][top].isLiving()) {
neighbors++;
}
if (biosphere[rgt][btm].isLiving()) {
neighbors++;
}
living[ii][jj] = biosphere[ii][jj].isAlive(neighbors);
}
}
for (int ii = 0; ii < s; ii++) {
for (int jj = 0; jj < s; jj++) {
biosphere[ii][jj].setAlive(living[ii][jj]);
}
}
generationLabel.setText("Generation: " + generation++);
gui.repaint();
}
};
Timer timer = new Timer(50, al);
timer.start();
JOptionPane.showMessageDialog(null, ui);
timer.stop();
}
}
这篇关于如何添加可以在我的生命游戏程序中获取生成的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!