Advertisement
votako

%u0422.%u0422.%u0422.

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