evgeniyosipov

KrestikiNoliki.java

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