import java.awt.*; import javax.swing.*; import java.util.Random; import java.util.ArrayDeque; import java.util.Timer; public class JGrilleDeJeu extends JComponent { private static final int TAILLE_GRILLE = 25; private char[][] grille; private ArrayDeque coordSnake; public JGrilleDeJeu(ArrayDeque coordSnake) { this.grille = new char[TAILLE_GRILLE][TAILLE_GRILLE]; this.coordSnake = coordSnake; for (int i = 0; i != TAILLE_GRILLE; i++) { for (int j = 0; j != TAILLE_GRILLE; j++) { this.grille[i][j] = 'g'; } } for (Point point : coordSnake) { this.grille[point.x][point.y] = 'o'; } Random r = new Random(); int coordXPomme = Math.abs(r.nextInt() % TAILLE_GRILLE); int coordYPomme = Math.abs(r.nextInt() % TAILLE_GRILLE); this.grille[coordXPomme][coordYPomme] = 'r'; Timer timer = new Timer(); while (true) { timer.wait(1000L); this.avancerSnake(); } } @Override public void paintComponent(Graphics pinceau) { Graphics secondPinceau = pinceau.create(); if (this.isOpaque()) { secondPinceau.setColor(this.getBackground()); secondPinceau.fillRect(0, 0, this.getWidth(), this.getHeight()); } for (int i = 0; i != TAILLE_GRILLE; i++) { for (int j = 0; j != TAILLE_GRILLE; j++) { switch (grille[i][j]) { case 'g': secondPinceau.setColor(Color.GREEN); break; case 'r': secondPinceau.setColor(Color.RED); break; case 'o': secondPinceau.setColor(Color.ORANGE); } secondPinceau.fillRect( this.getWidth()/TAILLE_GRILLE*i, this.getHeight()/TAILLE_GRILLE*j, this.getWidth()/TAILLE_GRILLE, this.getHeight()/TAILLE_GRILLE ); } } } public void avancerSnake() { this.coordSnake.removeFirst(); this.coordSnake.addLast(new Point(this.coordSnake.getLast().x+1, this.coordSnake.getLast().y)); } }