J'essaie de faire afficher mon programme (en testant dans la console d'abord) le nombre de comptage à chaque étape où la cellule change de forme. Donc, le nombre devrait commencer à partir de 0 et augmenter chaque fois que la cellule change de forme. J'ai essayé ceci, en utilisant count ++ mais il ne s'incrémente pas de 1 mais me donne des nombres aléatoires. Toute aide sera très appréciée.Comment est-ce que j'ajoute une fonctionnalité où je peux obtenir la génération dans mon programme de jeu de la vie?
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;
// top-left row-1,col-1
if (currentMove[getTopRow(i - 1)][getLeftCol(j - 1)]) neighbors++; //Uses getTopRow and getLeftCol methods to determine the indices of the top left cell
// left row,col-1
if (currentMove[i][getLeftCol(j - 1)]) neighbors++;
// bottom left row+1,col-1
if (currentMove[getBottomRow(i + 1)][getLeftCol(j - 1)]) neighbors++;
// bottom row+1,col
if (currentMove[getBottomRow(i + 1)][j]) neighbors++;
// bottom right row+1,col+1
if (currentMove[getBottomRow(i + 1)][getRightCol(j + 1)]) neighbors++;
// right row,col+1
if (currentMove[i][getRightCol(j + 1)]) neighbors++;
// top-right row-1,col+1
if (currentMove[getTopRow(i - 1)][getRightCol(j + 1)])neighbors++;
// top row-1, col
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; //If the index of leftCol is less than 0, it uses the right most col (columns - 1)
}
private int getRightCol(int neighbourCol) {
return neighbourCol > (wid-1) ? 0 : neighbourCol;
}
private int getTopRow(int neighbourRow) {
return neighbourRow < 0 ? (hei - 1) : neighbourRow; //If the index of topRow is less than 0, it uses the bottom last row (rows - 1)
}
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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
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();
}// </editor-fold>//GEN-END:initComponents
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked
}//GEN-LAST:event_jPanel1MouseClicked
private void jPanel1ComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jPanel1ComponentResized
offScrImg = createImage(jPanel1.getWidth(), jPanel1.getHeight());
offScrGraph = offScrImg.getGraphics();
repain();
}//GEN-LAST:event_jPanel1ComponentResized
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
play = !play;
if(play) jButton1.setText("Pause");
else jButton1.setText("Play");
repain();
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
currentMove = new boolean[hei][wid];
repain();
}//GEN-LAST:event_jButton2ActionPerformed
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseDragged
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();
}//GEN-LAST:event_jPanel1MouseDragged
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GameOfLife().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
@AndrewThompson Done –
J'ai utilisé repain car il existe déjà une méthode intégrée appelée repaint. Donc je ne voulais pas entrer en conflit. –
Nice edit. :) BTW - N'a pas examiné de près votre code, mais vérifié que [ce code] (http://stackoverflow.com/a/8200046/418556) pourrait implémenter un compteur de génération dans une poignée de lignes de code. Serait-il utile que vous voyiez cela? –