Advertisement
Guest User

Untitled

a guest
May 5th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.07 KB | None | 0 0
  1. package lab;
  2.  
  3.  
  4. import java.awt.*;
  5. import java.awt.geom.*;
  6. import java.awt.event.*;
  7. import javax.swing.*;
  8. import java.util.*;
  9.  
  10. /**
  11.  *  Classe principale, initialisation du moele, et mise en place du controleur
  12.  *  et de la vue.
  13.  */
  14.  
  15. public class Laby {
  16.  
  17.     public static void main(String[] args) {
  18.  
  19.     // Initialisation du schema MVC.
  20.     Model laby = new Model(10, 12);
  21.     JFrame frame = new JFrame();
  22.     Controller controller = new Controller(laby, frame);
  23.     View view = new View(laby, frame);
  24.     // -- Schema MVC initialie.
  25.  
  26.     // Configuration de la fenetre graphique.
  27.     frame.setTitle("Laby");
  28.     frame.pack();
  29.     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  30.     frame.setVisible(true);
  31.     // -- Fenetre graphique configuree.
  32.    
  33.     // Configuration du labyrinthe.
  34.     //Premiere section de configuration.
  35.      for (int i=0; i<10; i++) {
  36.          laby.putWall(i, 0);
  37.         laby.putWall(i, 11);
  38.      }
  39.      for (int j=0; j<12; j++) {
  40.          laby.putWall(0, j);
  41.          laby.putWall(9, j);
  42.      }
  43.      for (int i=0; i<7; i++) {
  44.         laby.putWall(i, 4);
  45.      }
  46.      for (int i=8; i<10; i++) {
  47.          laby.putWall(i, 4);
  48.     }
  49.      for (int j=4; j<7; j++) {
  50.          laby.putWall(3, j);
  51.      }
  52.      for (int j=8; j<12; j++) {
  53.         laby.putWall(3, j);
  54.      }
  55.      laby.putExit(0, 1);
  56.     // // -- Fin de la premere section.
  57.     // // Deuxieme section de configuration.
  58.     laby.putHero(1,6);
  59.     // // -- Fin de la deuxieme section.
  60.     // // Troisieme section de configuration.
  61.      laby.putMonster(6, 8);
  62.      laby.putMonster(4, 2);
  63.     // // -- Fin de la troisieme section.
  64.     // // Quatrieme section de configuration.
  65.      laby.putOpenDoor(3, 7);
  66.      laby.putClosedDoor(7, 4);
  67.     // // -- Fin de la quatrieme section.
  68.     // -- Labyrinthe configure.
  69.      
  70.     }
  71.  
  72. }
  73.  
  74. /**
  75.  *  Le labyrinthe proprement dit.
  76.  */
  77.  
  78. class Model extends Observable {
  79.     // Un labyrinthe a : une hauteur, une largeur, un tableau de cellules,
  80.     // un heros et une liste de monstres.
  81.     private final int h, w;
  82.     private Cell[][] laby;
  83.     private Hero hero = null;
  84.     private ArrayList<Monster>monsters ;
  85.     public Cell get(int i, int j) { return laby[i][j]; }
  86.     public int  getH()            { return h; }
  87.     public int  getW()            { return w; }
  88.  
  89.     // Construction d'un labyrinthe aux dimensions donnees.
  90.     // A l'origine, il n'y a ni heros ni monstre, et toutes les cases
  91.     // sont libres.
  92.     public Model(int h, int w) {
  93.         this.h = h;
  94.         this.w = w;
  95.         laby = new Cell[h][w];
  96.         for (int i=0; i< h ;i++){
  97.             for (int j=0; j< w ;j++){
  98.                 putCell(i,j);
  99.             }
  100.         }
  101.         this.monsters = new ArrayList<Monster>();
  102.     }
  103.  
  104.     // Methode pour les deplacements du monstre.
  105.     // Deplacement d'une case dans une direction, puis notification de la vue.
  106.     public void monsterMove() throws NotTraversableCell {
  107.         for(Monster m : this.monsters){
  108.             m.move(Direction.random());
  109.         }
  110.     }
  111.     // Methode pour les deplacements du heros.
  112.     // Deplacement d'une case dans une direction, puis notification de la vue.
  113.     public void heroMove(Direction dir) throws NotTraversableCell {
  114.     hero.move(dir);
  115.     setChanged();
  116.     notifyObservers();
  117.     }
  118.  
  119.     // Methodes pour la configuration du labyrinthe.
  120.     public void putCell(int i, int j) {
  121.         laby[i][j] = new Cell(this, i, j);
  122.     }
  123.      public void putWall(int i, int j) {
  124.         laby[i][j] = new Wall(this, i, j);
  125.      }
  126.      public void putExit(int i, int j) {
  127.         laby[i][j] = new Exit(this, i, j);
  128.      }
  129.      public void putHero(int i, int j) {
  130.         if (this.hero == null) {
  131.             hero = new Hero(laby[i][j]);
  132.         }
  133.      }
  134.      
  135.      public void putMonster(int i, int j) {
  136.         monsters.add(new Monster(laby[i][j]));
  137.      }
  138.    
  139.     public void putOpenDoor(int i, int j) {
  140.         laby[i][j] = Door.openDoorFactory(this, i, j);
  141.      }
  142.      public void putClosedDoor(int i, int j) {
  143.         laby[i][j] = Door.closedDoorFactory(this, i, j);
  144.      }
  145.     // -- Fin des methodes de configuration.
  146.  
  147. }
  148.  
  149.  
  150. /**
  151.  * La vue principale du labyrinthe, qui affiche l'ensemble de la structure
  152.  * et ses occupants.
  153.  */
  154.  
  155. class View extends JComponent implements Observer {
  156.     // La vue memorise une rerence au labyrinthe et a  la fenetre graphique.
  157.     // On enregistre aussi la dimension et le cete de chaque case en pixels.
  158.     private static final int SCALE = 40;
  159.     private Model laby;
  160.     private JFrame frame;
  161.     private Dimension dim;
  162.  
  163.     // Constructeur, a  la vue s'enregistre comme un deplacment de la fenetre
  164.     // graphique et comme un observateur des modifications du labyrinthe.
  165.     public View(Model laby, JFrame frame) {
  166.     this.laby = laby;
  167.     this.frame = frame;
  168.     this.dim = new Dimension(SCALE*laby.getW(),SCALE*laby.getH());
  169.     this.setPreferredSize(dim);
  170.     laby.addObserver(this);
  171.     frame.add(this);
  172.     }
  173.  
  174.     // Methode de mise a jour pour reagir aux modification du modele.
  175.     public void update(Observable o, Object arg) {
  176.     repaint();
  177.     }
  178.  
  179.     // Methode d'affichage du labyrinthe.
  180.     public void paintComponent(Graphics g) {
  181.     Graphics2D g2 = (Graphics2D)g;
  182.     for (int i=0; i<this.laby.getH(); i++){
  183.         for (int j=0; j<this.laby.getW(); j++){
  184.             this.laby.get(i, j).paintCell(g2,j*SCALE,i*SCALE, SCALE);
  185.         }
  186.     }
  187.     }
  188. }
  189.  
  190. /**
  191.  * Le controleur des entrees du clavier. Il reagit aussi a la souris pour
  192.  * recuperer le focus.
  193.  */
  194.  
  195. class Controller extends JComponent implements KeyListener, MouseListener {
  196.     // Le controleur garde une reference au labyrinthe.
  197.     private Model laby;
  198.  
  199.     // Constructeur : le controleur s'enregistre comme un recepteur des entees
  200.     // clavier et souris, et comme un element graphique (necessaire pour
  201.     // recuperer le focus et les entrees).
  202.     public Controller(Model laby, JFrame frame) {
  203.     this.laby = laby;
  204.     addKeyListener(this);
  205.     addMouseListener(this);
  206.     setFocusable(true);
  207.     frame.add(this);
  208.     }
  209.  
  210.     // Methode qui recupere l'entree clavier et appelle l'action correspondante
  211.     // du heros. Si l'action du heros est valide, alors les monstres sont aussi
  212.     // deplaces.
  213.     public void keyTyped(KeyEvent e) {
  214.         Direction dir;
  215.         try{
  216.         switch (e.getKeyChar()){
  217.         case 'z' : dir = Direction.NORTH; break;
  218.         case 'q' : dir = Direction.WEST;  break;
  219.         case 's' : dir = Direction.SOUTH; break;
  220.         case 'd' : dir = Direction.EAST; break;
  221.         default: throw new NotADirectionException();
  222.         }
  223.        
  224.         laby.heroMove(dir);
  225.         laby.monsterMove();
  226.         }
  227.         catch (NotADirectionException e2){}
  228.         catch (ArrayIndexOutOfBoundsException e2){
  229.             System.out.println("gagné!");
  230.         }
  231.         catch (NotTraversableCell e2){}
  232.     }
  233.     // -- Fin de l'action du clavier.
  234.  
  235.     // Recupere le focus quand on clique dans la fenetre graphique.
  236.     public void mouseClicked(MouseEvent e) {
  237.     requestFocusInWindow();
  238.     }
  239.     // Pas de reaction aux autres stimuli.
  240.     public void keyPressed(KeyEvent e) {}
  241.     public void keyReleased(KeyEvent e) {}
  242.     public void mouseEntered(MouseEvent e) {}
  243.     public void mouseExited(MouseEvent e) {}
  244.     public void mousePressed(MouseEvent e) {}
  245.     public void mouseReleased(MouseEvent e) {}
  246. }
  247.  
  248. class NotADirectionException extends Exception{
  249.    
  250. }
  251.  
  252. /**
  253.  *a partir d'ici : les classes auxiliaires. Themes couverts dans l'ordre :
  254.  * Les directions.
  255.  * Les cases.
  256.  * Les portes.
  257.  * Les creatures.
  258.  */
  259.  
  260. /**
  261.  * Directions cardinales, et equivalents en differences de coordonnees.
  262.  */
  263.  
  264. enum Direction {
  265.     NORTH (-1, 0),
  266.     SOUTH ( 1, 0),
  267.     EAST  ( 0, 1),
  268.     WEST  ( 0,-1),
  269.     NORTHWEST (-1, 1),
  270.     NORTHEAST (1, 1),
  271.     SOUTHWEST (-1, -1),
  272.     SOUTHEAST (1, -1);
  273.     private final int dI, dJ;
  274.     private Direction(int di, int dj) { this.dI = di; this.dJ = dj; }
  275.     public int dI() { return dI; }
  276.     public int dJ() { return dJ; }
  277.     public static Direction random() {
  278.         return values()[(int) (Math.random() * values().length)];
  279.     }
  280. }
  281.  
  282. /**
  283.  * Cases principales du labyrinthe.
  284.  */
  285.  
  286. class Cell {
  287.     // On maintient une reference vers le labyrinthe et les coordonnees.
  288.     private final Model laby;
  289.     private final int i, j;
  290.     private Creature c = null ;
  291.    
  292.     // Constructeur.
  293.    
  294.     public Cell(Model laby, int i, int j) {
  295.         this.laby = laby;
  296.         this.i = i;
  297.         this.j = j;
  298.         this.c = null;
  299.         }
  300.    
  301.     public void setCreature(Creature c){
  302.         this.c = c;
  303.     }
  304.  
  305.     public Creature getCreature(){
  306.         return c;
  307.     }
  308.    
  309.     public Cell getNext (Direction dir){
  310.         return this.laby.get(this.i+dir.dI(), this.j+dir.dJ());
  311.     }
  312.  
  313.     // Partie dessin.
  314.     public void paintCell(Graphics2D g2d, int leftX, int topY, int scale) {
  315.     Rectangle2D rect = new Rectangle2D.Double(leftX, topY, scale, scale);
  316.     g2d.setPaint(getColor());
  317.     g2d.fill(rect);
  318.     if (c!= null){ c.paintCreature(g2d, leftX, topY, scale);}
  319.     }
  320.    
  321.    
  322.     public Color getColor(){
  323.         return Color.WHITE;
  324.     }
  325.    
  326.     public boolean isPassable(){
  327.         if(this.c != null){
  328.             return false;
  329.         } else if (this.getColor() == Color.RED){
  330.             return false;
  331.         }
  332.         else return true;
  333.     }
  334.     public void removeHero(){
  335.         c = null;
  336.     }
  337.    
  338. }
  339. /**
  340.  * La  classe Door
  341.  */
  342.  
  343. abstract class Door extends Cell{
  344.    
  345.     public Door(Model laby, int i, int j) {
  346.         super(laby, i, j);
  347.     }
  348.  
  349.     public static OpenDoor openDoorFactory(Model laby, int i, int j){
  350.         return new OpenDoor(laby, i ,j);
  351.     }
  352.    
  353.     public static ClosedDoor closedDoorFactory(Model laby, int i, int j){
  354.         return new ClosedDoor(laby, i, j);
  355.     }
  356.    
  357.     abstract public void changeState();
  358.    
  359.    
  360. }
  361.  
  362. class OpenDoor extends Door{
  363.    
  364.     public OpenDoor(Model laby, int i, int j){
  365.         super(laby, i, j);
  366.     }
  367.    
  368.     public Color getColor(){
  369.         return Color.GREEN;
  370.     }
  371.  
  372.     public void changeState() {
  373.        
  374.     }
  375.    
  376. }
  377.  
  378. class ClosedDoor extends Door{
  379.    
  380.     public ClosedDoor(Model laby, int i, int j){
  381.         super(laby, i, j);
  382.     }
  383.    
  384.     public Color getColor(){
  385.         return Color.RED;
  386.     }
  387.  
  388.     public void changeState() {
  389.        
  390.        
  391.     }
  392. }
  393.  
  394.  
  395. abstract class Creature{
  396.     private Cell cell = null;
  397.     protected boolean isHero;
  398.    
  399.     public Creature(Cell c ){cell = c; cell.setCreature(this); this.isHero = false;}
  400.    
  401.    
  402.     public void move(Direction dir) throws NotTraversableCell {
  403.         Cell c = this.cell.getNext(dir);
  404.         if(c.getCreature() != null){
  405.             this.cell.removeHero();
  406.             System.out.println("Perdu!");
  407.             System.exit(0);
  408.         } else if(c.isPassable()){
  409.         this.cell.setCreature(null);
  410.         c.setCreature(this);
  411.         this.cell = c;
  412.         } else if(this.isHero==true){
  413.             throw new NotTraversableCell(c);
  414.         }
  415.         else throw new NotTraversableCell();
  416.     }
  417.    
  418.     public Cell getCell(){
  419.         return cell;
  420.     }
  421.     public void paintCreature(Graphics2D g2d, int leftX, int topY, int scale){
  422.         Ellipse2D ell= new Ellipse2D.Double(leftX, topY, scale, scale);
  423.         g2d.setPaint(getColor());
  424.         g2d.fill(ell);
  425.         }
  426.    
  427.     abstract Color getColor();
  428.        
  429. }
  430.  
  431. class NotTraversableCell extends Exception {
  432.    
  433.     public NotTraversableCell(){
  434.     }
  435.    
  436.     public NotTraversableCell(Cell c){
  437.         if (c.getColor() == Color.BLACK){
  438.             System.out.println("c'est un mur! ce n'est pas traversable!");
  439.         }
  440.         if (c.getColor() == Color.RED){
  441.             System.out.println("la porte est fermee");
  442.         }
  443.     }
  444. }
  445. /**
  446.  * La classe du heros.
  447.  */
  448.  
  449. // Cette classe est a remanier, ce petit morceau est la  juste pour eviter
  450. // une erreur de compilation due a l'absence de la mathode [move].
  451.  
  452. class Hero extends Creature{
  453.    
  454.     public Hero(Cell c) {
  455.         super(c);
  456.         this.isHero = true;
  457.     }
  458.  
  459.     public Color getColor(){
  460.         return Color.blue;
  461.     }
  462.    
  463. }
  464. class Monster extends Creature{
  465.     public Monster(Cell c) {
  466.         super(c);
  467.     }
  468.  
  469.     public Color getColor(){
  470.         return Color.GRAY;
  471.     }
  472.    
  473. }
  474.    
  475. /**
  476.  * La classe Wall
  477.  */
  478. class Wall extends Cell {
  479.  
  480.     public Wall(Model laby, int i, int j) {
  481.         super(laby, i, j);
  482.        
  483.     }  
  484.         public Color getColor(){
  485.             return Color.BLACK;
  486.         }
  487.        
  488.         public boolean isPassable(){
  489.             return false;
  490.         }
  491.     }
  492. /**
  493.  * La classe Exit
  494.  */
  495. class Exit extends Cell {
  496.  
  497.         public Exit(Model laby, int i, int j) {
  498.             super(laby, i, j);
  499.         }
  500.         public Color getColor(){
  501.             return Color.BLUE;
  502.         }
  503.         public boolean isPassable(){
  504.             if (this.getCreature()!=null){
  505.                 return false;
  506.             }
  507.             else return true;
  508.         }
  509.  
  510. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement