Sie sind auf Seite 1von 18

9.

import javax.swing.*;
10. import java.awt.*;
11. import java.awt.event.*;
12. import java.io.*;
13. import java.util.*;
14.
15. public cl*** TicTacToe implements ActionListener
{
16.
final String VERSION = "2.0";
17. //Setting up ALL the variables
18.
JFrame window = new JFrame("Tic-Tac-Toe " +
VERSION);
19.
20.
JMenuBar mnuMain = new JMenuBar();
21.
JMenuItem
mnuNewGame = new
JMenuItem("New Game"),
22.
mnuInstruction = new
JMenuItem("Instructions"),
23.
mnuExit = new
JMenuItem("Exit"),
24.
mnuAbout = new
JMenuItem("About");
25.
26.
JButton btn1v1 = new JButton("Player vs Player"),
27.
btn1vCPU = new JButton("Player vs
Computer"),
28.
btnQuit = new JButton("Quit"),
29.
btnSetName = new JButton("Set Player
Names"),
30.
btnContinue = new
JButton("Continue..."),
31.
btnTryAgain = new JButton("Try
Again?");
32.
JButton btnEmpty[] = new JButton[10];
33.
34.
JPanel
pnlNewGame = new JPanel(),

35.
pnlMenu = new JPanel(),
36.
pnlMain = new JPanel(),
37.
pnlTop = new JPanel(),
38.
pnlBottom = new JPanel(),
39.
pnlQuitNTryAgain = new JPanel(),
40.
pnlPlayingField = new JPanel();
41.
42.
JLabel
lblTitle = new JLabel("Tic-Tac-Toe"),
43.
lblTurn = new JLabel(),
44.
lblStatus = new JLabel("",
JLabel.CENTER);
45.
JTextArea txtMessage = new JTextArea();
46.
47.
final int winCombo[][] = new int[][] {
48.
{1, 2, 3},
{1, 4, 7},
{1, 5, 9},
49.
{4, 5, 6},
{2, 5, 8},
{3, 5, 7},
50.
{7, 8, 9},
{3, 6, 9}
51. /*Horizontal Wins*/ /*Vertical Wins*/ /*Diagonal Wins*/
52.
};
53.
final int X = 535, Y = 342,
54.
mainColorR = 190, mainColorG = 50, mainColorB
= 50,
55.
btnColorR = 70, btnColorG = 70, btnColorB = 70;
56.
Color clrBtnWonColor = new Color(190, 190, 190);
57.
int turn = 1,
58.
player1Won = 0,
59.
player2Won = 0,
60.
wonNumber1 = 1,
61.
wonNumber2 = 1,
62.
wonNumber3 = 1;
63.
int option;
64.
boolean inGame = false;
65.
boolean win = false;
66.
boolean btnEmptyClicked = false;
67.
String message, whoTurn,

68.
Player1 = "Player 1", Player2 = "Player 2";
69.
70.
71.
public TicTacToe() {
//Setting game properties
and layout and sytle...
72.
//Setting window properties:
73.
window.setSize(X, Y);
74.
window.setLocation(350, 260);
75.
window.setResizable(false);
76.
window.setLayout(new BorderLayout());
77.
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
78.
79.
//Setting Menu, Main, Top, Bottom Panel
Layout/Backgrounds
80.
pnlMenu.setLayout(new
FlowLayout(FlowLayout.CENTER));
81.
pnlTop.setLayout(new
FlowLayout(FlowLayout.CENTER));
82.
pnlBottom.setLayout(new
FlowLayout(FlowLayout.CENTER));
83.
84.
pnlNewGame.setBackground(new
Color(mainColorR - 50, mainColorG - 50, mainColorB- 50));
85.
pnlMenu.setBackground(new Color((mainColorR 50), (mainColorG - 50), (mainColorB- 50)));
86.
pnlMain.setBackground(new Color(mainColorR,
mainColorG, mainColorB));
87.
pnlTop.setBackground(new Color(mainColorR,
mainColorG, mainColorB));
88.
pnlBottom.setBackground(new Color(mainColorR,
mainColorG, mainColorB));
89.
90.
//Setting up Panel QuitNTryAgain

91.
pnlQuitNTryAgain.setLayout(new GridLayout(1,
2, 2, 2));
92.
pnlQuitNTryAgain.add(btnTryAgain);
93.
pnlQuitNTryAgain.add(btnQuit);
94.
95.
//Adding menu items to menu bar
96.
mnuMain.add(mnuNewGame);
97.
mnuMain.add(mnuInstruction);
98.
mnuMain.add(mnuAbout);
99.
mnuMain.add(mnuExit);// Menu Bar is Complete
100.
101.
//Adding buttons to NewGame panel
102.
pnlNewGame.setLayout(new GridLayout(4, 1, 2,
10));
103.
pnlNewGame.add(btnContinue);
104.
pnlNewGame.add(btn1v1);
105.
pnlNewGame.add(btn1vCPU);
106.
pnlNewGame.add(btnSetName);
107.
108.
//Setting Button propertied
109.
btnTryAgain.setEnabled(false);
110.
btnContinue.setEnabled(false);
111.
112.
//Setting txtMessage Properties
113.
txtMessage.setBackground(new
Color(mainColorR-30, mainColorG-30, mainColorB-30));
114.
txtMessage.setForeground(Color.white);
115.
txtMessage.setEditable(false);
116.
117.
//Adding Action Listener to all the Buttons and Menu
Items
118.
mnuNewGame.addActionListener(this);
119.
mnuExit.addActionListener(this);
120.
mnuInstruction.addActionListener(this);
121.
mnuAbout.addActionListener(this);

122.
btn1v1.addActionListener(this);
123.
btn1vCPU.addActionListener(this);
124.
btnQuit.addActionListener(this);
125.
btnSetName.addActionListener(this);
126.
btnContinue.addActionListener(this);
127.
btnTryAgain.addActionListener(this);
128.
129.
//Setting up the playing field
130.
pnlPlayingField.setLayout(new GridLayout(3, 3, 2,
2));
131.
pnlPlayingField.setBackground(Color.black);
132.
for(int i=1; i<=9; i++) {
133.
btnEmpty[i] = new JButton();
134.
btnEmpty[i].setBackground(new
Color(btnColorR, btnColorG, btnColorB));
135.
btnEmpty[i].addActionListener(this);
136.
pnlPlayingField.add(btnEmpty[i]);//
Playing Field is Compelte
137.
}
138.
139.
//Adding everything needed to pnlMenu and pnlMain
140.
pnlMenu.add(mnuMain);
141.
pnlMain.add(lblTitle);
142.
143.
//Adding to window and Showing window
144.
window.add(pnlMenu, BorderLayout.NORTH);
145.
window.add(pnlMain, BorderLayout.CENTER);
146.
window.setVisible(true);
147.
}
148.
149.
public static void main(String[] args) {
150.
new TicTacToe();// Calling the cl*** construtor.
151.
//
PROGRAM STARTS HERE!
152.
}

153.
154.
155.
156. /*
157.
------------------------158.
Start of all METHODS.
|
159.
------------------------160. */
161.
public void showGame() {
//
Shows the
Playing Field
162.
//
*IMPORTANT*- Does not start out brand new (meaning just
shows what it had before)
163.
clearPanelSouth();
164.
pnlMain.setLayout(new BorderLayout());
165.
pnlTop.setLayout(new BorderLayout());
166.
pnlBottom.setLayout(new BorderLayout());
167.
pnlTop.add(pnlPlayingField);
168.
pnlBottom.add(lblTurn, BorderLayout.WEST);
169.
pnlBottom.add(lblStatus, BorderLayout.CENTER);
170.
pnlBottom.add(pnlQuitNTryAgain,
BorderLayout.EAST);
171.
pnlMain.add(pnlTop, BorderLayout.CENTER);
172.
pnlMain.add(pnlBottom, BorderLayout.SOUTH);
173.
pnlPlayingField.requestFocus();
174.
inGame = true;
175.
checkTurn();
176.
checkWinStatus();
177.
}
178. //---------------------------------------------------------------------------------------------------------------------------------179.
public void new1v1Game() {
//
Sets all the game
required variables to default
180.
//
and then shows the playing field.

181.
//

(Basically: Starts a new 1v1 Game)


182.
btnEmpty[wonNumber1].setBackground(new
Color(btnColorR, btnColorG, btnColorB));
183.
btnEmpty[wonNumber2].setBackground(new
Color(btnColorR, btnColorG, btnColorB));
184.
btnEmpty[wonNumber3].setBackground(new
Color(btnColorR, btnColorG, btnColorB));
185.
for(int i=1; i<10; i++) {
186.
btnEmpty[i].setText("");
187.
btnEmpty[i].setEnabled(true);
188.
}
189.
turn = 1;
190.
win = false;
191.
showGame();
192.
}
193. //---------------------------------------------------------------------------------------------------------------------------------194.
public void goBack() {
195.
clearPanelSouth();
196.
pnlMain.setLayout(new
FlowLayout(FlowLayout.CENTER));
197.
pnlMain.add(lblTitle);
198.
}
199. //---------------------------------------------------------------------------------------------------------------------------------200.
public void checkWin()
{
//
checks if there
are 3 symbols in a row vertically, diagonally, or horizontally.
201.
//
then shows a message and disables buttons. If the game is over
then it asks
202.
//
if you want to play again.
203.
for(int i=0; i<8; i++) {
204.
if(

205.
!btnEmpty[winCombo[i]
[0]].getText().equals("") &&
206.
btnEmpty[winCombo[i]
[0]].getText().equals(btnEmpty[winCombo[i][1]].getText()) &&
207.
//
if {1 == 2 && 2 == 3}
208.
btnEmpty[winCombo[i]
[1]].getText().equals(btnEmpty[winCombo[i][2]].getText())) {
209.
/*
210.
The way this checks the if
someone won is:
211.
First: it checks if the btnEmpty[x]
is not equal to an empty string- x being the array number
212.
inside the multidementional array winCombo[checks inside each of the 7 sets][the
first number]
213.
Secong: it checks if btnEmpty[x]
is equal to btnEmpty[y]- x being winCombo[each set][the first
number]
214.
y being winCombo[each set
the same as x][the second number] (So basically checks if the first
and
215.
second number in each set is
equal to each other)
216.
Third: it checks if btnEmtpy[y] is
eual to btnEmpty[z]- y being the same y as last time and z being
217.
winCombo[each set as y]
[the third number]
218.
Conclusion:
So basically it
checks if it is equal to the btnEmpty is equal to each set of numbers
219.
*/
220.
win = true;
221.
wonNumber1 = winCombo[i][0];
222.
wonNumber2 = winCombo[i][1];
223.
wonNumber3 = winCombo[i][2];

224.
btnEmpty[wonNumber1].setBackground(clrBtnWonColor);
225.
btnEmpty[wonNumber2].setBackground(clrBtnWonColor);
226.
btnEmpty[wonNumber3].setBackground(clrBtnWonColor);
227.
break;
228.
}
229.
}
230.
if(win || (!win && turn>9)) {
231.
if(win)
{
232.
if(turn % 2 == 0){
233.
message = Player1 + " has won";
234.
player1Won++;
235.
}
236.
else {
237.
message = Player2 + " has won";
238.
player2Won++;
239.
}
240.
win = false;
241.
}
else if(!win && turn>9)
242.
message = "Both players have
tied!\nBetter luck next time.";
243.
showMessage(message);
244.
for(int i=1; i<=9; i++) {
245.
btnEmpty[i].setEnabled(false);
246.
}
247.
btnTryAgain.setEnabled(true);
248.
checkWinStatus();
249.
} else
250.
checkTurn();
251.
}
252. //---------------------------------------------------------------------------------------------------------------------------------253.
public void checkTurn()
{

254.
if(!(turn % 2 == 0)) {
255.
whoTurn = Player1 + " [X]";
256.
}
else {
257.
whoTurn = Player2 + " [O]";
258.
}
259.
lblTurn.setText("Turn: " + whoTurn);
260.
}
261. //---------------------------------------------------------------------------------------------------------------------------------262.
public void checkWinStatus()
{
263.
lblStatus.setText(Player1 + ": " + player1Won + " |
" + Player2 + ": " + player2Won);
264.
}
265. //---------------------------------------------------------------------------------------------------------------------------------266.
public void askUserForPlayerNames() {
267.
String temp = Player2;
268.
269.
temp = getInput("Enter player 1 name:", Player1);
270.
if(temp == null) {/*Do Nothing*/}
271.
else if(temp.equals(""))
272.
showMessage("Invalid Name!");
273.
else if(temp.equals(Player2))
{
274.
option = askMessage("Player 1 name
matches Player 2's\nDo you want to continue?", "Name Match",
JOptionPane.YES_NO_OPTION);
275.
if(option == JOptionPane.YES_OPTION)
276.
Player1 = temp;
277.
} else if(temp != null) {
278.
Player1 = temp;
279.
}
280.
281.
temp = getInput("Enter player 2 name:", Player2);
282.
if(temp == null) {/*Do Nothing*/}
283.
else if(temp.equals(""))

284.
showMessage("Invalid Name!");
285.
else if(temp.equals(Player1))
{
286.
option = askMessage("Player 2 name
matches Player 1's\nDo you want to continue?", "Name Match",
JOptionPane.YES_NO_OPTION);
287.
if(option == JOptionPane.YES_OPTION)
288.
Player2 = temp;
289.
} else if(temp != null) {
290.
Player2 = temp;
291.
}
292.
}
293. //---------------------------------------------------------------------------------------------------------------------------------294.
public void setDefaultLayout() {
295.
pnlMain.setLayout(new GridLayout(2, 1, 2, 5));
296.
pnlTop.setLayout(new
FlowLayout(FlowLayout.CENTER));
297.
pnlBottom.setLayout(new
FlowLayout(FlowLayout.CENTER));
298.
}
299. //---------------------------------------------------------------------------------------------------------------------------------300.
public int askMessage(String message, String title, int
option)
{
301.
return JOptionPane.showConfirmDialog(null,
message, title, option);
302.
}
303. //---------------------------------------------------------------------------------------------------------------------------------304.
public String getInput(String message, String setText)
{
305.
return JOptionPane.showInputDialog(null,
message, setText);
306.
}

307. //---------------------------------------------------------------------------------------------------------------------------------308.
public void showMessage(String message) {
309.
JOptionPane.showMessageDialog(null, message);
310.
}
311. //---------------------------------------------------------------------------------------------------------------------------------312.
public void clearPanelSouth()
{
//Removes all
the possible panels
313.
//that pnlMain, pnlTop, pnlBottom
314.
//could have.
315.
pnlMain.remove(lblTitle);
316.
pnlMain.remove(pnlTop);
317.
pnlMain.remove(pnlBottom);
318.
pnlTop.remove(pnlNewGame);
319.
pnlTop.remove(txtMessage);
320.
pnlTop.remove(pnlPlayingField);
321.
pnlBottom.remove(lblTurn);
322.
pnlBottom.remove(pnlQuitNTryAgain);
323.
}
324. /*
325.
------------------------------------326.
End of all non-Abstract METHODS.
|
327.
------------------------------------328. */
329.
330. //-------------------ACTION PERFORMED METHOD (Button
Click --> Action?)-------------------------//
331.
public void actionPerformed(ActionEvent click) {
332.
Object source = click.getSource();
333.
for(int i=1; i<=9; i++) {
334.
if(source == btnEmpty[i] && turn < 10)
{

335.
btnEmptyClicked = true;
336.
if(!(turn % 2 == 0))
337.
btnEmpty[i].setText("X");
338.
else
339.
btnEmpty[i].setText("O");
340.
btnEmpty[i].setEnabled(false);
341.
pnlPlayingField.requestFocus();
342.
turn++;
343.
}
344.
}
345.
if(btnEmptyClicked) {
346.
checkWin();
347.
btnEmptyClicked = false;
348.
}
349.
if(source == mnuNewGame || source ==
mnuInstruction || source == mnuAbout) {
350.
clearPanelSouth();
351.
setDefaultLayout();
352.
353.
if(source == mnuNewGame)
{//NewGame
354.
pnlTop.add(pnlNewGame);
355.
}
356.
else if(source == mnuInstruction || source ==
mnuAbout)
{
357.
if(source == mnuInstruction)
{//
Instructions
358.
message = "Instructions:\n\n" +
359.
"Your goal
is to be the first player to get 3 X's or O's in a\n" +
360.
"row.
(horizontally, diagonally, or vertically)\n" +
361.
Player1 +
": X\n" +

362.
Player2 +
": O\n";
363.
} else{//About
364.
message = "About:\n\n" +
365.
"Title: TicTac-Toe\n" +
366.
"Creator:
Blmaster\n" +
367.
"Version: "
+ VERSION + "\n";
368.
}
369.
txtMessage.setText(message);
370.
pnlTop.add(txtMessage);
371.
}
372.
pnlMain.add(pnlTop);
373.
}
374.
else if(source == btn1v1 || source == btn1vCPU)
{
375.
if(inGame) {
376.
option = askMessage("If you start a
new game," +
377.
"your current game will be lost..."
+ "\n" +
378.
"Are you sure you want to
continue?",
379.
"Quit Game?"
,JOptionPane.YES_NO_OPTION
380.
);
381.
if(option ==
JOptionPane.YES_OPTION)
382.
inGame = false;
383.
}
384.
if(!inGame)
{
385.
if(source == btn1v1) {// 1 v 1 Game
386.
btnContinue.setEnabled(true);

387.
new1v1Game();
388.
} else{// 1 v CPU Game
389.
showMessage("Coming Soon!");
390.
}
391.
}
392.
}
393.
else if(source == btnContinue) {
394.
checkTurn();
395.
showGame();
396.
}
397.
else if(source == btnSetName) {
398.
askUserForPlayerNames();
399.
}
400.
else if(source == mnuExit) {
401.
option = askMessage("Are you sure you want
to exit?", "Exit Game", JOptionPane.YES_NO_OPTION);
402.
if(option == JOptionPane.YES_OPTION)
403.
System.exit(0);
404.
}
405.
else if(source == btnTryAgain) {
406.
new1v1Game();
407.
btnTryAgain.setEnabled(false);
408.
}
409.
else if(source == btnQuit) {
410.
inGame = false;
411.
btnContinue.setEnabled(false);
412.
goBack();
413.
}
414.
pnlMain.setVisible(false);
415.
pnlMain.setVisible(true);
416.
}
417. //-------------------END OF ACTION PERFORMED
METHOD-------------------------//
418. }
419. /* Future Plans:

420.
421. */
422. /*
423.
424.
Label
425.
wins
426.
Button
427.
428.
429.
430.
changes.
431.
cancel.
432.
433.
434.
435.
gameplay.
436.
437.
438.
439.
440.
441.
442.
443.
444.
445. */
446.
447.
448. /*

-Add AI
Changes:
2.0- changes below: bug fixes [Stable]
1.95- fixed bug: TryAgain Button takes over Status
1.9- added Label that shows Player 1 and Player 2
1.8- removed Try Again pop-up. Added Try Again
1.7- removed Back Button. Added Continue Button
1.6- fixed bugs below...
fixed bug: Same name for both players.
fixed bug: Names updated in game if user
fixed bug: Names are null if user presses
1.5- added function to set Player Names.
1.4- program more efficient/faster.
1.35- fixed bugs, added turn status to status bar.
1.3- added Status bar with quit button during
1.2- changed theme.
1.15- fixed bug: one win combo not working.
1.1- added play again function.
1.0- changes below: (problems gone!) [Stable]
0.9- added back button, added comments.
0.8- added dynamic win message.
0.7- added game function- game playable.
0.6- changed menu layout.
0.5- basic functions with menu and nice GUI.

LAYOUT OF THE GAME:

449.
450.
451.
452.
453.

THE WINDOW: (pnlMenu/pnlMain)


pnlMenu: (THE MENU)
pnlMain: (pnlTop/pnlBottom)
pnlTop:
(pnlPlayingField/INSTRUCTIONS/ABOUT/NEW GAME)
454.
pnlBottom:(STATUS BAR/BACK BUTTON)
455.
456.
/////////////////////////////////////////////////--------------|
457.
/
pnlMenu
/
|
458.
/
/
|
459.
/////////////////////////////////////////////////-----|
|
460.
/
/
|
|
461.
/
/
|
|
462.
/
/
|
|
463.
/
pnlTop
/
|
|
464.
/
/
|
|- MAIN WINDOW
465.
/
/
||
466.
/
/
|pnlMain |

467.

/
/

|
468.

/
|

469.

/
|

470.

/
|

471.

/
|

472.

/////////////////////////////////////////////////

|
473.

pnlBottom

474.

/
|
|
/////////////////////////////////////////////////-----|--------|

Das könnte Ihnen auch gefallen