package xo2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class XO2 implements ActionListener {
private int[][] winningCombination = new int[][] {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{3, 4, 6}
};
private JFrame window = new JFrame("Tic Tac Toe");
private JButton buttons[] = new JButton[9];
private int count = 0;
private String letter = "";
private boolean win = false;
public XO2(){
window.setSize(300,300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(3,3));
for(int i=0; i<9; i++){
buttons[i] = new JButton();
window.add(buttons[i]);
buttons[i].addActionListener(this);
}
window.setVisible(true);
}
public void actionPerformed(ActionEvent a) {
count++;
if(count % 2 == 0){
letter = "O";
}
else {
letter = "X";
}
JButton pressedButton = (JButton)a.getSource();
pressedButton.setText(letter);
pressedButton.setEnabled(false);
for(int i=0; i<8; i++){
if( buttons[winningCombination[i][0]].getText().equals(buttons[winningCombination[i][1]].getText()) &&
buttons[winningCombination[i][1]].getText().equals(buttons[winningCombination[i][2]].getText()) &&
!buttons[winningCombination[i][0]].getText().equals("")){
win = true;
}
}
if(win == true){
JOptionPane.showMessageDialog(null, letter + " won!");
System.exit(0);
} else if(count == 9 && win == false){
JOptionPane.showMessageDialog(null, "draw!");
System.exit(0);
}
}
public static void main(String[] args){
XO2 starter = new XO2();
}
}
答案 0 :(得分:1)
我为你创建了一个基本类,它将胜利保存到文本文件中并从文本文件中检索它们。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WinsFileManager {
String path = System.getProperty("user.home").replace("\\", "\\\\") + "\\";
public int getWins(String fileName) {
String fullPath = path + fileName;
int wins = 0;
try {
wins = Integer.parseInt(new Scanner(new File(fullPath)).nextLine());
} catch (NumberFormatException e) {}
catch (FileNotFoundException e) {
wins = 0;
}
return wins;
}
public void saveWins(String fileName, int wins) {
PrintWriter out = null;
try {
out = new PrintWriter(path + fileName, "UTF-8");
out.println(wins);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以下是您从不同位置使用上述类的对象的方法。
public class test {
public static void main(String[] args) {
WinsFileManager manager = new WinsFileManager();
String fileName = "O Wins.txt";
manager.saveWins(fileName, 5);
System.out.println(manager.getWins(fileName));
}
}
上例中的控制台输出为'5'。
我做了很多困难。现在由您决定将其实施到您的程序中。首先,每当有人获胜时,我将通过getWins
方法检索存储的获胜次数,向该值添加一个,然后使用saveWins
方法存储递增的值。请记住,即使退出程序,也会保存获胜值。
注意:如果你想要做的就是在程序的生命周期内跟踪胜利,那么有更简单的方法可以做到这一点。
答案 1 :(得分:0)