Skip to content

Instantly share code, notes, and snippets.

@thieux
Created March 13, 2018 14:19
Show Gist options
  • Save thieux/945b0a5e82d45c1b41c6399deeedbbae to your computer and use it in GitHub Desktop.
Save thieux/945b0a5e82d45c1b41c6399deeedbbae to your computer and use it in GitHub Desktop.
Jeu de la vie en Swing à compléter
package com.mathieupauly.jeudelavie;
import javax.swing.*;
import java.awt.*;
import java.util.Arrays;
public class JeuDeLaVieIhm extends JFrame {
private static final int TAILLE_PLATEAU = 3;
private static final float TAILLE_POLICE = 50f;
private static final int PERIODE_RAFRACHISSEMENT_MILLI_SECONDE = 500;
private static final String CARACTERE_VIVANT = " O ";
private static final String CARACTERE_MORT = " . ";
private boolean[][] etat = plateauInitial();
private boolean[][] plateauInitial() {
boolean[][] booleans = new boolean[TAILLE_PLATEAU][TAILLE_PLATEAU];
for (int ligne = 0; ligne < TAILLE_PLATEAU; ligne++) {
for (int colonne = 0; colonne < TAILLE_PLATEAU; colonne++) {
booleans[ligne][colonne] = Math.random() > 0.8;
}
}
return booleans;
}
public static void main(String[] args) {
JeuDeLaVieIhm ihm = new JeuDeLaVieIhm();
ihm.demarre();
}
private void demarre() {
SwingUtilities.invokeLater(this::buildAndShow);
}
private void buildAndShow() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JTextArea comp = new JTextArea(prochainPlateau());
Font[] allFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
System.out.println(Arrays.toString(allFonts));
Font monospacedFont = Arrays.stream(allFonts)
.filter(f -> f.getName().equals("Courier New"))
.findFirst()
.orElse(comp.getFont());
comp.setFont(monospacedFont.deriveFont(TAILLE_POLICE));
add(comp);
pack();
Timer timer = new Timer(PERIODE_RAFRACHISSEMENT_MILLI_SECONDE, e -> afficherNouveauPlateau(comp));
//timer.start();
setVisible(true);
}
private void afficherNouveauPlateau(JTextArea comp) {
comp.setText(prochainPlateau());
comp.repaint();
}
private String prochainPlateau() {
boolean[][] nouvelEtat = new boolean[TAILLE_PLATEAU][TAILLE_PLATEAU];
for (int ligne = 0; ligne < TAILLE_PLATEAU; ligne++) {
System.arraycopy(etat[ligne], 0, nouvelEtat[ligne], 0, TAILLE_PLATEAU);
}
// calculer le nouvel état
etat = nouvelEtat;
String[][] textePlateau = new String[TAILLE_PLATEAU][TAILLE_PLATEAU];
for (int ligne = 0; ligne < TAILLE_PLATEAU; ligne++) {
for (int colonne = 0; colonne < TAILLE_PLATEAU; colonne++) {
textePlateau[ligne][colonne] = etat[ligne][colonne] ? CARACTERE_VIVANT : CARACTERE_MORT;
}
}
String[] elements = new String[TAILLE_PLATEAU];
for (int i = 0; i < TAILLE_PLATEAU; i++) {
elements[i] = String.join("", textePlateau[i]);
}
return String.join("\n", elements);
}
private int compterVoisinsVivants(int ligne, int colonne) {
???
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment