Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.awt.event.*;
- import java.applet.Applet;
- public class KrestikiNoliki extends Applet implements ActionListener{
- Button squares[];
- Button newGameButton;
- Label score;
- Label labWin;
- Label labLoose;
- int win = 0;
- int loose = 0;
- int emptySquaresLeft = 9;
- public void init(){
- // Менеджер расположения апплета, шрифт и цвет
- this.setLayout(new BorderLayout());
- this.setBackground(Color.WHITE);
- // Крифт апплета
- Font appletFont=new Font("Monospased",Font.BOLD, 20);
- this.setFont(appletFont);
- // Кнопка “New Game” и слушатель действия
- labWin=new Label("ВЫ: " + win);
- labLoose=new Label("ПК: " + loose);
- newGameButton=new Button("Новая Игра");
- newGameButton.addActionListener(this);
- Panel topPanel=new Panel();
- topPanel.setLayout(new BorderLayout());
- topPanel.add(newGameButton,"North");
- topPanel.add(labWin,"West");
- topPanel.add(labLoose, "East");
- this.add(topPanel,"North");
- Panel centerPanel=new Panel();
- centerPanel.setLayout(new GridLayout(3,3));
- this.add(centerPanel,"Center");
- score=new Label("Ваш ход");
- this.add(score,"South");
- // Массив для хранения ссылок на 9 кнопок
- squares=new Button[9];
- // Кнопки
- for(int i=0;i<9;i++){
- squares[i]=new Button();
- squares[i].addActionListener(this);
- squares[i].setBackground(Color.blue);
- centerPanel.add(squares[i]);
- }
- }
- /**
- * @param ActionEvent объект
- */
- public void actionPerformed(ActionEvent e) {
- Button theButton = (Button) e.getSource();
- // Кнопка New Game
- if (theButton ==newGameButton){
- for(int i=0;i<9;i++){
- squares[i].setEnabled(true);
- squares[i].setLabel("");
- squares[i].setBackground(Color.blue);
- }
- emptySquaresLeft=9;
- score.setText("Ваш ход");
- newGameButton.setEnabled(true);
- return;
- }
- String winner = "";
- // Одна из клеток
- metka:
- for ( int i=0; i<9; i++ ) {
- if ( theButton == squares[i] ) {
- if (squares[i].getLabel()!="X" && squares[i].getLabel()!="O"){
- squares[i].setLabel("X");
- winner = lookForWinner();}
- else { continue metka;}
- if(!"".equals(winner)){
- endTheGame();
- } else {
- computerMove();
- winner = lookForWinner();
- if ( !"".equals(winner)){
- endTheGame();
- }
- }
- break;
- }
- }
- if ( winner.equals("X") ) {
- ++win;
- labWin.setText("ВЫ: " + win);
- score.setText("Вы победили!");
- } else if (winner.equals("O")){
- ++loose;
- score.setText("Вы проиграли...");
- labLoose.setText("ПК: " + loose);
- } else if (winner.equals("T")){
- score.setText("Ничья");
- }
- } // Конец метода actionPerformed
- /**
- * @return "X", "O", "T" – ничья, "" - еще нет победителя
- */
- String lookForWinner() {
- String theWinner = "";
- emptySquaresLeft--;
- if (emptySquaresLeft==0){
- return "T";
- }
- // Проверка ряд 1 – элементы массива 0,1,2
- if (!squares[0].getLabel().equals("") &&
- squares[0].getLabel().equals(squares[1].getLabel()) &&
- squares[0].getLabel().equals(squares[2].getLabel())) {
- theWinner = squares[0].getLabel();
- highlightWinner(0,1,2);
- // Проверка ряд 2 – элементы массива 3,4,5
- } else if (!squares[3].getLabel().equals("") &&
- squares[3].getLabel().equals(squares[4].getLabel()) &&
- squares[3].getLabel().equals(squares[5].getLabel())) {
- theWinner = squares[3].getLabel();
- highlightWinner(3,4,5);
- // Проверка ряд 3 – элементы массива 6,7,8
- } else if ( ! squares[6].getLabel().equals("") &&
- squares[6].getLabel().equals(squares[7].getLabel()) &&
- squares[6].getLabel().equals(squares[8].getLabel())) {
- theWinner = squares[6].getLabel();
- highlightWinner(6,7,8);
- // Проверка колонки 1 – элементы массива 0,3,6
- } else if ( ! squares[0].getLabel().equals("") &&
- squares[0].getLabel().equals(squares[3].getLabel()) &&
- squares[0].getLabel().equals(squares[6].getLabel())) {
- theWinner = squares[0].getLabel();
- highlightWinner(0,3,6);
- // Проверка колонки 2 – элементы массива 1,4,7
- } else if ( ! squares[1].getLabel().equals("") &&
- squares[1].getLabel().equals(squares[4].getLabel()) &&
- squares[1].getLabel().equals(squares[7].getLabel())) {
- theWinner = squares[1].getLabel();
- highlightWinner(1,4,7);
- // Проверка колонки 3 – элементы массива 2,5,8
- } else if ( ! squares[2].getLabel().equals("") &&
- squares[2].getLabel().equals(squares[5].getLabel()) &&
- squares[2].getLabel().equals(squares[8].getLabel())) {
- theWinner = squares[2].getLabel();
- highlightWinner(2,5,8);
- // Проверка первой диагонали – элементы массива 0,4,8
- } else if ( ! squares[0].getLabel().equals("") &&
- squares[0].getLabel().equals(squares[4].getLabel()) &&
- squares[0].getLabel().equals(squares[8].getLabel())) {
- theWinner = squares[0].getLabel();
- highlightWinner(0,4,8);
- // Проверка второй диагонали – элементы массива 2,4,6
- } else if ( ! squares[2].getLabel().equals("") &&
- squares[2].getLabel().equals(squares[4].getLabel()) &&
- squares[2].getLabel().equals(squares[6].getLabel())) {
- theWinner = squares[2].getLabel();
- highlightWinner(2,4,6);
- }
- return theWinner;
- }
- /**
- * Метод применяет набор правил, чтобы найти
- * лучший компьютерный ход.
- * если не найден, выбирается случайная клетка.
- */
- void computerMove() {
- int selectedSquare;
- selectedSquare = findEmptySquare("O");
- if ( selectedSquare == -1 )
- selectedSquare = findEmptySquare("X");
- if ( (selectedSquare == -1)
- &&(squares[4].getLabel().equals("")) ){
- selectedSquare=4;
- }
- if ( selectedSquare == -1 ){
- selectedSquare = getRandomSquare();
- }
- squares[selectedSquare].setLabel("O");
- }
- /**
- * Метод проверяет каждый ряд, колонку и диагональ
- * чтобы узнать, есть ли в ней две клетки
- * с одинаковыми надписями и пустой клеткой.
- * @param передается X – для пользователя и O – для ПК
- * @return количество свободных клеток,
- * или -1, если не найдено две клетки
- * с одинаковыми надписями
- */
- int findEmptySquare(String player) {
- int weight[] = new int[9];
- for ( int i = 0; i < 9; i++ ) {
- if ( squares[i].getLabel().equals("O") )
- weight[i] = -1;
- else if ( squares[i].getLabel().equals("X") )
- weight[i] = 1;
- else
- weight[i] = 0;
- }
- int twoWeights = player.equals("O") ? -2 : 2;
- if ( weight[0] + weight[1] + weight[2] == twoWeights ) {
- if ( weight[0] == 0 )
- return 0;
- else if ( weight[1] == 0 )
- return 1;
- else
- return 2;
- }
- if (weight[3] +weight[4] + weight[5] == twoWeights) {
- if ( weight[3] == 0 )
- return 3;
- else if ( weight[4] == 0 )
- return 4;
- else
- return 5;
- }
- if (weight[6] + weight[7] +weight[8] == twoWeights ) {
- if ( weight[6] == 0 )
- return 6;
- else if ( weight[7] == 0 )
- return 7;
- else
- return 8;
- }
- if (weight[0] + weight[3] + weight[6] == twoWeights) {
- if ( weight[0] == 0 )
- return 0;
- else if ( weight[3] == 0 )
- return 3;
- else
- return 6;
- }
- if (weight[1] +weight[4] + weight[7] == twoWeights ) {
- if ( weight[1] == 0 )
- return 1;
- else if ( weight[4] == 0 )
- return 4;
- else
- return 7;
- }
- if (weight[2] + weight[5] + weight[8] == twoWeights ){
- if ( weight[2] == 0 )
- return 2;
- else if ( weight[5] == 0 )
- return 5;
- else
- return 8;
- }
- if (weight[0] + weight[4] + weight[8] == twoWeights ){
- if ( weight[0] == 0 )
- return 0;
- else if ( weight[4] == 0 )
- return 4;
- else
- return 8;
- }
- if (weight[2] + weight[4] + weight[6] == twoWeights ){
- if ( weight[2] == 0 )
- return 2;
- else if ( weight[4] == 0 )
- return 4;
- else
- return 6;
- }
- // Не найдено двух одинаковых соседних клеток
- return -1;
- }
- /**
- * Метод выбирает любую пустую клетку
- * @return случайно выбранный номер клетки
- */
- int getRandomSquare() {
- boolean gotEmptySquare = false;
- int selectedSquare = -1;
- do {
- selectedSquare = (int) (Math.random() * 9 );
- if (squares[selectedSquare].getLabel().equals("")){
- gotEmptySquare = true;
- }
- } while (!gotEmptySquare );
- return selectedSquare;
- }
- /**
- * Метод выделяет выигравшую линию.
- * @param первая, вторая и третья клетки для выделения
- */
- void highlightWinner(int win1, int win2, int win3) {
- squares[win1].setBackground(Color.RED);
- squares[win2].setBackground(Color.RED);
- squares[win3].setBackground(Color.RED);
- }
- void endTheGame(){
- newGameButton.setEnabled(true);
- for(int i=0;i<9;i++){
- squares[i].setEnabled(false);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment