Форум программистов, компьютерный форум, киберфорум
Java: GUI, графика
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/15: Рейтинг темы: голосов - 15, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 18.05.2015
Сообщений: 2
1

Реализовать ничью в игре Крестики-Нолики

14.11.2015, 21:57. Показов 2941. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Помогите сделать, чтоб в форме выводились не только победы крестиков и ноликов, но еще и ничья
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
 
public class KrestikiNoliki {
    public static void main(String[] args) {
        KOFrame frame = new KOFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.show();               
    }
}
 
class KOFrame extends JFrame {
 
    JLabel score;
 
    public KOFrame() {
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension ss = kit.getScreenSize();
        int scrW = ss.width;
        int scrH = ss.height;
 
        int fW = 300;
        int fH = 350;
    //  System.out.println((scrW - fW) / 2 +"    " + (scrH - fH) / 2);
 
        JFrame frame = new JFrame();
 
        score = new JLabel();
 
        setSize(fW, fH);
        setLocation((scrW - fW) / 2, (scrH - fH) / 2);
        setTitle("Крестики-нолики Баранова Е.");
        setCursor(Cursor.HAND_CURSOR);
 
        KOPanel panel = new KOPanel(this);
        Container contain = getContentPane();
        contain.add(panel);
        ExitPanel exit_panel = new ExitPanel(panel);
        contain.add(exit_panel, "South");
        add(score, BorderLayout.NORTH);
        refreshScore(0, 0);
    }
 
    public void refreshScore(int x, int o) {
        score.setText("     Крестики: " + x
                + "                                         Нолики: " + o);
    }
 
}
 
class ExitPanel extends JPanel {
    KOPanel koPanel;
 
    public ExitPanel(final KOPanel koPanel) {
        setLayout(new GridLayout(1, 2));
        KOButton exit = new KOButton(4, 4);
        KOButton restart = new KOButton(5, 5);
        this.koPanel = koPanel;
        add(restart);
        add(exit);
        exit.setText("Выход");
        restart.setText("Рестарт");
 
        exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
 
                System.exit(0);
            }
        });
 
        restart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
 
                koPanel.clear();
                koPanel.clearGameScreen();
            }
        });
 
    }
}
 
class KOPanel extends JPanel {
    char[][] game_arr = new char[3][3];
    {
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                game_arr[i][j] = ' ';
            }
        }
    }
 
    KOButton[][] buttons = new KOButton[3][3];
    public int cout = 0;
 
    ImageIcon krest = new ImageIcon("krestik i nolik/x.jpg");
    ImageIcon nol = new ImageIcon("krestik i nolik/o.jpg");
    ImageIcon start = new ImageIcon("/start_image.jpg");
 
    KOFrame koFrame; // ссылка на главный фрейм
    int xCount = 0; // победы Х
    int oCount = 0; // победы О
 
    public KOPanel(KOFrame koFrame) {
        this.koFrame = koFrame;
        setLayout(new GridLayout(3, 3));
 
        {
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
        buttons[i][j] = new KOButton(i, j);
        buttons[i][j].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                KOButton sourceOfAction = (KOButton) event
                    .getSource();
            if (cout % 2 == 0
                && game_arr[sourceOfAction.getRow()][sourceOfAction
                    .getColumn()] == ' ') {
                game_arr[sourceOfAction.getRow()][sourceOfAction
                    .getColumn()] = 'x';
                sourceOfAction.setIcon(krest);
                chek();
                cout++;
 
                    } else if (cout % 2 == 1
                    && game_arr[sourceOfAction.getRow()][sourceOfAction
                        .getColumn()] == ' ') {
                game_arr[sourceOfAction.getRow()][sourceOfAction
                        .getColumn()] = 'o';
                    sourceOfAction.setIcon(nol);
                    chek();
                    cout++;
                            }
                        }
                    });
            add(buttons[i][j]);
                }
            }
        }
    }
 
    public void chek() {
        String exit_option_string;
        int exit_option = 0;
 
        if ((game_arr[0][0] == 'x' && game_arr[0][1] == 'x' && game_arr[0][2] == 'x')
                || (game_arr[1][0] == 'x' && game_arr[1][1] == 'x' && game_arr[1][2] == 'x')
                || (game_arr[2][0] == 'x' && game_arr[2][1] == 'x' && game_arr[2][2] == 'x')
                || (game_arr[0][0] == 'x' && game_arr[1][0] == 'x' && game_arr[2][0] == 'x')
                || (game_arr[0][1] == 'x' && game_arr[1][1] == 'x' && game_arr[2][1] == 'x')
                || (game_arr[0][2] == 'x' && game_arr[1][2] == 'x' && game_arr[2][2] == 'x')
                || (game_arr[0][0] == 'x' && game_arr[1][1] == 'x' && game_arr[2][2] == 'x')
                || (game_arr[2][0] == 'x' && game_arr[1][1] == 'x' && game_arr[0][2] == 'x')) {
            JOptionPane.showMessageDialog(null, "Выиграли крестики!");
            clear();
            clearGameScreen();
            xCount++;
            koFrame.refreshScore(xCount, oCount);
        }
             
        
                
 
        if ((game_arr[0][0] == 'o' && game_arr[0][1] == 'o' && game_arr[0][2] == 'o')
                || (game_arr[1][0] == 'o' && game_arr[1][1] == 'o' && game_arr[1][2] == 'o')
                || (game_arr[2][0] == 'o' && game_arr[2][1] == 'o' && game_arr[2][2] == 'o')
                || (game_arr[0][0] == 'o' && game_arr[1][0] == 'o' && game_arr[2][0] == 'o')
                || (game_arr[0][1] == 'o' && game_arr[1][1] == 'o' && game_arr[2][1] == 'o')
                || (game_arr[0][2] == 'o' && game_arr[1][2] == 'o' && game_arr[2][2] == 'o')
                || (game_arr[0][0] == 'o' && game_arr[1][1] == 'o' && game_arr[2][2] == 'o')
                || (game_arr[2][0] == 'o' && game_arr[1][1] == 'o' && game_arr[0][2] == 'o')) {
            JOptionPane.showMessageDialog(null, "Выиграли нолики!");
            clear();
            clearGameScreen();
            oCount++;
            koFrame.refreshScore(xCount, oCount);
        }
            
                
    }
 
    public void clear() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                game_arr[i][j] = ' ';
            }
        }
    }
 
    public void clearGameScreen() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                buttons[i][j].setIcon(start);
            }
        }
    }
 
}
 
class KOButton extends JButton {
    public KOButton(int r, int c) {
        super();
        row = r;
        column = c;
    }
 
    public int getRow() {
        return row;
    }
 
    public int getColumn() {
        return column;
    }
 
    private int row, column;
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
14.11.2015, 21:57
Ответы с готовыми решениями:

Крестики нолики
Из ряда: &quot;Старые песни о главном&quot;. Посмотрел по поиску темы, не нашел что надо. Может кто-то идею...

Крестики-Нолики
Привет. Столкнулся с проблемой в скрипте. Не могу правильно присвоить каждой кнопки значение &quot;x&quot;...

Крестики-нолики
нужно переделать данный проект для поля 5х5, победа 3 в ряд

Крестики-нолики
Помогите доделать программу: 1.Добавьте на верхнюю панель класса TicTacToe две надписи для...

2
53 / 53 / 39
Регистрация: 05.12.2010
Сообщений: 261
16.11.2015, 10:07 2
Цитата Сообщение от Inferior Посмотреть сообщение
Java
1
2
3
4
5
6
7
8
if ((game_arr[0][0] == 'x' && game_arr[0][1] == 'x' && game_arr[0][2] == 'x')
  || (game_arr[1][0] == 'x' && game_arr[1][1] == 'x' && game_arr[1][2] == 'x')
  || (game_arr[2][0] == 'x' && game_arr[2][1] == 'x' && game_arr[2][2] == 'x')
  || (game_arr[0][0] == 'x' && game_arr[1][0] == 'x' && game_arr[2][0] == 'x')
  || (game_arr[0][1] == 'x' && game_arr[1][1] == 'x' && game_arr[2][1] == 'x')
  || (game_arr[0][2] == 'x' && game_arr[1][2] == 'x' && game_arr[2][2] == 'x')
  || (game_arr[0][0] == 'x' && game_arr[1][1] == 'x' && game_arr[2][2] == 'x')
  || (game_arr[2][0] == 'x' && game_arr[1][1] == 'x' && game_arr[0][2] == 'x')) {
Что за индусский код?)
А вообще - вы делаете проверку на выигрыш крестиков и выигрыш ноликов. Сделайте проверку на то, все ли элементы game_arr[i][j] заполнены, если все и при этом не наступил выигрыш крестиков или ноликов - значит ничья.

Добавлено через 8 минут
Например, как-нибудь так (код не компилил):
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public void chek() {
        String exit_option_string;
        int exit_option = 0;
 
        if ((game_arr[0][0] == 'x' && game_arr[0][1] == 'x' && game_arr[0][2] == 'x')
                || (game_arr[1][0] == 'x' && game_arr[1][1] == 'x' && game_arr[1][2] == 'x')
                || (game_arr[2][0] == 'x' && game_arr[2][1] == 'x' && game_arr[2][2] == 'x')
                || (game_arr[0][0] == 'x' && game_arr[1][0] == 'x' && game_arr[2][0] == 'x')
                || (game_arr[0][1] == 'x' && game_arr[1][1] == 'x' && game_arr[2][1] == 'x')
                || (game_arr[0][2] == 'x' && game_arr[1][2] == 'x' && game_arr[2][2] == 'x')
                || (game_arr[0][0] == 'x' && game_arr[1][1] == 'x' && game_arr[2][2] == 'x')
                || (game_arr[2][0] == 'x' && game_arr[1][1] == 'x' && game_arr[0][2] == 'x')) {
            JOptionPane.showMessageDialog(null, "Выиграли крестики!");
            clear();
            clearGameScreen();
            xCount++;
            koFrame.refreshScore(xCount, oCount);
        }
             
        
                
 
        else if ((game_arr[0][0] == 'o' && game_arr[0][1] == 'o' && game_arr[0][2] == 'o')
                || (game_arr[1][0] == 'o' && game_arr[1][1] == 'o' && game_arr[1][2] == 'o')
                || (game_arr[2][0] == 'o' && game_arr[2][1] == 'o' && game_arr[2][2] == 'o')
                || (game_arr[0][0] == 'o' && game_arr[1][0] == 'o' && game_arr[2][0] == 'o')
                || (game_arr[0][1] == 'o' && game_arr[1][1] == 'o' && game_arr[2][1] == 'o')
                || (game_arr[0][2] == 'o' && game_arr[1][2] == 'o' && game_arr[2][2] == 'o')
                || (game_arr[0][0] == 'o' && game_arr[1][1] == 'o' && game_arr[2][2] == 'o')
                || (game_arr[2][0] == 'o' && game_arr[1][1] == 'o' && game_arr[0][2] == 'o')) {
            JOptionPane.showMessageDialog(null, "Выиграли нолики!");
            clear();
            clearGameScreen();
            oCount++;
            koFrame.refreshScore(xCount, oCount);
        }
 
        else {
                boolean isEmpty = true;
                for (int i = 0; i < 3; i++) {
                        for (int j = 0; j < 3; j++) {
                                if (game_arr[i][j] == ' ')
                                        isEmpty = false;
                        }
                }
                if (isEmpty) {
                        JOptionPane.showMessageDialog(null, "Ничья!");
                        clear();
                        clearGameScreen();
                }
        }
    }
1
0 / 0 / 0
Регистрация: 18.05.2015
Сообщений: 2
21.11.2015, 20:02  [ТС] 3
Спасибо большое)
0
21.11.2015, 20:02
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.11.2015, 20:02
Помогаю со студенческими работами здесь

Крестики-нолики
Здравствуйте, уважаемые форумчане! Нужна помощь в реализации всем известной игры крестики-нолики....

Создание web-апплета Крестики-нолики
Здравствуйте, всем! Создал тему в общей ветке, так как не знаю к какому разделу ее отнести. Я...

Игра крестики - нолики. Установка шрифта, текстового поля
Здравствуйте! С недавнего времени занялся программированием на Java, читаю лекции в инете на...

Приложение "Крестики-нолики"
напишите программу на java крестники нолики AWT


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru