votako

TicTacToe

May 23rd, 2013
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.04 KB | None | 0 0
  1.  
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import java.applet.Applet;
  5. public class TicTacToe extends Applet implements ActionListener{
  6.  
  7.     /**
  8.      *
  9.      */
  10.     private static final long serialVersionUID = 7828407597610900234L;
  11.     Button squares[];
  12.     Button newGameButton;
  13.     Label score;
  14.     int emptySquaresLeft=9;
  15. /**
  16. * Метод init – это конструктор апплета
  17. */
  18.     public void init(){
  19. //Устанавливаем менеджер расположения апплета, шрифт и цвет
  20.         this.setLayout(new BorderLayout());
  21.         this.setBackground(Color.CYAN);
  22. // Изменяем шрифт апплета так, чтобы он был жирным
  23. // и имел размер 20
  24.         Font appletFont=new Font("Monospased",Font.BOLD, 20);
  25.         this.setFont(appletFont);
  26. // Создаем кнопку “New Game” и регистрируем в ней
  27. // слушатель действия
  28.         newGameButton=new Button("New Game");
  29.         newGameButton.addActionListener(this);
  30.         Panel topPanel=new Panel();
  31.         topPanel.add(newGameButton);
  32.         this.add(topPanel,"North");
  33.         Panel centerPanel=new Panel();
  34.         centerPanel.setLayout(new GridLayout(3,3));
  35.         this.add(centerPanel,"Center");
  36.         score=new Label("Your turn!");
  37.         this.add(score,"South");
  38. // создаем массив, чтобы хранить ссылки на 9 кнопок
  39.         squares=new Button[9];
  40. // Создаем кнопки, сохраняем ссылки на них в массиве
  41. // регистрируем в них слушатель, красим их
  42. // в оранжевый цвет и добавляем на панель
  43.         for(int i=0;i<9;i++){
  44.             squares[i]=new Button();
  45.             squares[i].addActionListener(this);
  46.             squares[i].setBackground(Color.ORANGE);
  47.             centerPanel.add(squares[i]);
  48.         }
  49.     }
  50. /**
  51. * Этот метод будет обрабатывать все события
  52. * @param ActionEvent объект
  53. */
  54.     public void actionPerformed(ActionEvent e) {
  55.         Button theButton = (Button) e.getSource();
  56. // Это кнопка New Game ?
  57.         if (theButton ==newGameButton){
  58.             for(int i=0;i<9;i++){
  59.                 squares[i].setEnabled(true);
  60.                 squares[i].setLabel("");
  61.                 squares[i].setBackground(Color.ORANGE);
  62.             }
  63.             emptySquaresLeft=9;
  64.             score.setText("Your turn!");
  65.             newGameButton.setEnabled(false);
  66.             return;
  67.         }
  68.  
  69. // выходим из метода
  70.         String winner = "";
  71. // Это одна из клеток?
  72.         for ( int i=0; i<9; i++ ) {
  73.             if (theButton == squares[i] ) {
  74.                 squares[i].setLabel("X");
  75.                 winner = lookForWinner();
  76.                 if(!"".equals(winner)){
  77.                     endTheGame();
  78.                 } else {
  79.                     computerMove();
  80.                     winner = lookForWinner();
  81.                 }
  82.                 if ( !"".equals(winner)){
  83.                     endTheGame();
  84.                 }
  85.                 break;
  86.             }
  87.         } // конец цикла for
  88.         if ( winner.equals("X") ) {
  89.             score.setText("You won!");
  90.         } else if (winner.equals("O")){
  91.             score.setText("You lost!");
  92.         } else if (winner.equals("T")){
  93.             score.setText("It's a tie!");
  94.         }
  95.     } // конец метода actionPerformed
  96. /**
  97. *
  98. *
  99. *
  100. *
  101. *
  102. */
  103.  
  104.  
  105.     String lookForWinner() {
  106.         String theWinner = "";
  107.         emptySquaresLeft--;
  108.         if (emptySquaresLeft==0){
  109.             return "T"; // это ничья. T от английского слова tie
  110.         }
  111. // Проверяем ряд 1 – элементы массива 0,1,2
  112.         if (!squares[0].getLabel().equals("") &&
  113.                 squares[0].getLabel().equals(squares[1].getLabel()) &&
  114.                 squares[0].getLabel().equals(squares[2].getLabel())) {
  115.             theWinner = squares[0].getLabel();
  116.             highlightWinner(0,1,2);
  117. // Проверяем ряд 2 – элементы массива 3,4,5
  118.         } else if (!squares[3].getLabel().equals("")
  119.                 &&
  120.                 squares[3].getLabel().equals(squares[4].getLabel()) &&
  121.                 squares[3].getLabel().equals(squares[5].getLabel())) {
  122.             theWinner = squares[3].getLabel();
  123.             highlightWinner(3,4,5);
  124. // Проверяем ряд 3 – элементы массива 6,7,8
  125.         } else if ( ! squares[6].getLabel().equals("") &&
  126.                 squares[6].getLabel().equals(squares[7].getLabel()) &&
  127.                 squares[6].getLabel().equals(squares[8].getLabel())) {
  128.             theWinner = squares[6].getLabel();
  129.             highlightWinner(6,7,8);
  130. // Проверяем колонку 1 – элементы массива 0,3,6
  131.         } else if ( ! squares[0].getLabel().equals("") &&
  132.                 squares[0].getLabel().equals(squares[3].getLabel()) &&
  133.                 squares[0].getLabel().equals(squares[6].getLabel())) {
  134.             theWinner = squares[0].getLabel();
  135.             highlightWinner(0,3,6);
  136.             // Проверяем колонку 2 – элементы массива 1,4,7
  137.         } else if ( ! squares[1].getLabel().equals("") &&
  138.                 squares[1].getLabel().equals(squares[4].getLabel()) &&
  139.                 squares[1].getLabel().equals(squares[7].getLabel())) {
  140.             theWinner = squares[1].getLabel();
  141.             highlightWinner(1,4,7);
  142.             // Проверяем колонку 3 – элементы массива 2,5,8
  143.         } else if ( ! squares[2].getLabel().equals("") &&
  144.                 squares[2].getLabel().equals(squares[5].getLabel()) &&
  145.                 squares[2].getLabel().equals(squares[8].getLabel())) {
  146.             theWinner = squares[2].getLabel();
  147.             highlightWinner(2,5,8);
  148.             // Проверяем первую диагональ – элементы массива 0,4,8
  149.         } else if ( ! squares[0].getLabel().equals("") &&
  150.                 squares[0].getLabel().equals(squares[4].getLabel()) &&
  151.                 squares[0].getLabel().equals(squares[8].getLabel())) {
  152.             theWinner = squares[0].getLabel();
  153.             highlightWinner(0,4,8);
  154. // Проверяем вторую диагональ – элементы массива 2,4,6
  155.         } else if ( ! squares[2].getLabel().equals("") &&
  156.                 squares[2].getLabel().equals(squares[4].getLabel()) &&
  157.                 squares[2].getLabel().equals(squares[6].getLabel())) {
  158.             theWinner = squares[2].getLabel();
  159.             highlightWinner(2,4,6);
  160.         }
  161.         return theWinner;
  162.     }
  163.     /**
  164.      * Этот метод применяет набор правил, чтобы найти
  165.      * лучший компьютерный ход. Если хороший ход
  166.      * не найден, выбирается случайная клетка.
  167. */
  168.     void computerMove() {
  169.         int selectedSquare;
  170.         // Сначала компьютер пытается найти пустую клетку
  171. // рядом с двумя клетками с ноликами, чтобы выиграть
  172.         selectedSquare = findEmptySquare("O");
  173. //
  174. //
  175. //
  176.         if( selectedSquare == -1 ){
  177.             selectedSquare =findEmptySquare("X");
  178.         }
  179. // если selectedSquare все еще равен -1, то
  180. // попытается занять центральную клетку
  181.         if ( (selectedSquare == -1)
  182.                 &&(squares[4].getLabel().equals("")) ){
  183.             selectedSquare=4;
  184.         }
  185.         // не повезло с центральной клеткой...
  186. // просто занимаем случайную клетку
  187.         if ( selectedSquare == -1 ){
  188.             selectedSquare = getRandomSquare();
  189.         }
  190.         squares[selectedSquare].setLabel("O");
  191.     }
  192.     /**
  193. * Этот метод проверяет каждый ряд, колонку и диагональ
  194. * чтобы узнать, есть ли в ней две клетки
  195. * с одинаковыми надписями и пустой клеткой.
  196. * @param
  197. передается X – для пользователя и O – для компа
  198. * @return количество свободных клеток,
  199. *
  200. или -1, если не найдено две клетки
  201. *
  202. с одинаковыми надписями
  203. */
  204.     int findEmptySquare(String player) {
  205.         int weight[] = new int[9];
  206.         for ( int i = 0; i < 9; i++ ) {
  207.             if ( squares[i].getLabel().equals("O") )
  208.                 weight[i] = -1;
  209.             else if ( squares[i].getLabel().equals("X") )
  210.                 weight[i] = 1;
  211.             else
  212.                 weight[i] = 0;
  213.         }
  214.         int twoWeights = player.equals("O") ? -2 : 2;
  215. // Проверим, есть ли в ряду 1 две одинаковые клетки и
  216. // одна пустая.
  217.         if ( weight[0] + weight[1] + weight[2] == twoWeights ) {
  218.             if ( weight[0] == 0 )
  219.                 return 0;
  220.             else if ( weight[1] == 0 )
  221.                 return 1;
  222.             else
  223.                 return 2;
  224.         }  
  225. // Проверим, есть ли в ряду 2 две одинаковые клетки и
  226. // одна пустая.
  227.         if (weight[3] +weight[4] + weight[5] == twoWeights) {
  228.             if ( weight[3] == 0 )
  229.                 return 3;
  230.             else if ( weight[4] == 0 )
  231.                 return 4;
  232.             else
  233.                 return 5;
  234.         }
  235. // Проверим, есть ли в ряду 3 две одинаковые клетки и
  236. // одна пустая.
  237.         if (weight[6] + weight[7] +weight[8] == twoWeights ) {
  238.        
  239.         if ( weight[6] == 0 )
  240.             return 6;
  241.         else if ( weight[7] == 0 )
  242.             return 7;
  243.         else
  244.             return 8;
  245.         }
  246. // Проверим, есть ли в колонке 1 две одинаковые клетки и
  247. // одна пустая.
  248.         if (weight[0] + weight[3] + weight[6] == twoWeights) {
  249.             if ( weight[0] == 0 )
  250.                 return 0;
  251.            
  252.             else if ( weight[3] == 0 )
  253.                 return 3;
  254.            
  255.             else
  256.                 return 6;
  257.            
  258.         }
  259. // Проверим, есть ли в колонке 2 две одинаковые клетки
  260. // и одна пустая.
  261.         if (weight[1] +weight[4] + weight[7] == twoWeights ) {
  262.             if ( weight[1] == 0 )
  263.                 return 1;
  264.             else if ( weight[4] == 0 )
  265.                 return 4;
  266.             else
  267.                 return 7;
  268.         }
  269.        
  270. // Проверим, есть ли в колонке 3 две одинаковые клетки
  271. // и одна пустая.
  272.         if (weight[2] + weight[5] + weight[8] == twoWeights ){
  273.             if ( weight[2] == 0 )
  274.                 return 2;
  275.             else if ( weight[5] == 0 )
  276.                 return 5;
  277.             else
  278.                 return 8;
  279.         }
  280. // Проверим, есть ли в диагонали 1 две одинаковые клетки
  281. // и одна пустая.
  282.         if (weight[0] + weight[4] + weight[8] == twoWeights ){
  283.             if ( weight[0] == 0 )
  284.                 return 0;
  285.             else if ( weight[4] == 0 )
  286.                 return 4;
  287.             else
  288.                 return 8;
  289.         }
  290. // Проверим, есть ли в диагонали 2 две одинаковые клетки
  291. // и одна пустая.
  292.         if (weight[2] + weight[4] + weight[6] == twoWeights ){
  293.             if ( weight[2] == 0 )
  294.                 return 2;
  295.             else if ( weight[4] == 0 )
  296.                 return 4;
  297.             else
  298.                 return 6;
  299.         }
  300. // Не найдено двух одинаковых соседних клеток
  301.         return -1;
  302.        
  303.     } // конец метода findEmptySquare()
  304. /**
  305. * Этот метод выбирает любую пустую клетку
  306. * @return случайно выбранный номер клетки
  307. */
  308.     int getRandomSquare() {
  309.         boolean gotEmptySquare = false;
  310.         int selectedSquare = -1;
  311.         do {
  312.             selectedSquare = (int) (Math.random() * 9 );
  313.             if (squares[selectedSquare].getLabel().equals("")){
  314.                 gotEmptySquare = true; // чтобы закончить цикл
  315.             }
  316.         } while (!gotEmptySquare );
  317.         return selectedSquare;
  318.     } // конец метода getRandomSquare()
  319. /**
  320. * Этот метод выделяет выигравшую линию.
  321. * @param первая, вторая и третья клетки для выделения
  322. */
  323.     void highlightWinner(int win1, int win2, int win3) {
  324.         squares[win1].setBackground(Color.CYAN);
  325.         squares[win2].setBackground(Color.CYAN);
  326.         squares[win3].setBackground(Color.CYAN);
  327.     }
  328. // Делаем недоступными клетки и доступной кнопку ”New Game”
  329.     void endTheGame(){
  330.         newGameButton.setEnabled(true);
  331.         for(int i=0;i<9;i++){
  332.             squares[i].setEnabled(false);
  333.         }
  334.     }
  335. } // конец класса
Advertisement
Add Comment
Please, Sign In to add comment