1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class InterfaceSnake extends JFrame{
private Color[][] g;
private Graphic p;
private int bordure = 5,cell = 10;
private KeyEvent ke;
private class KEDispatcher implements KeyEventDispatcher {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_PAUSE) ke = e;
}
return false;
}
}
public InterfaceSnake(Color[][] grille){
super("Snake");
this.g = grille;
this.p = new Graphic();
this.p.setPreferredSize(new Dimension(2*this.bordure+(this.g.length-1)*this.cell, 2*this.bordure+(this.g[0].length-1)*this.cell));
this.getContentPane().add(this.p);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setResizable(false);
this.setVisible(true);
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new KEDispatcher());
}
public void changeGrille(Color[][] grille){
this.g = grille;
this.refresh();
}
public int pressedKey(){
if(this.ke == null) return 0;
else{
int result = 0;
if(this.ke.getKeyCode() == KeyEvent.VK_RIGHT) result = 2;
if(this.ke.getKeyCode() == KeyEvent.VK_LEFT) result = 1;
if(this.ke.getKeyCode() == KeyEvent.VK_DOWN) result = 3;
if(this.ke.getKeyCode() == KeyEvent.VK_UP) result = 4;
if(this.ke.getKeyCode() == KeyEvent.VK_PAUSE) result = 5;
this.ke = null;
return result;
}
}
public void refresh(){
this.p.repaint();
}
private class Graphic extends JPanel{
public void paint(Graphics gr){
gr.setColor(Color.WHITE);
gr.fillRect(0,0,this.getWidth(),this.getHeight());
for(int i=0;i<g.length;i++){
for(int j=0;j<g[i].length;j++){
gr.setColor(g[i][j]);
gr.fillRect(bordure+cell*i,bordure+cell*j,cell,cell);
}
}
}
}
/** Affiche le message m dans une boite de dialogue. */
public void afficheMessage(String m){
JOptionPane.showMessageDialog(this,m);
}
} |
Partager