-6

here is the tic tac toe game in java, can somebody complete the program that it will save how many times win X and how many times O into the text file, please :)

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();
  }
}
Derek Wang
  • 10,098
  • 4
  • 18
  • 39

2 Answers2

1

I've created a basic class for you that will save the wins to a text file and retrieve them from a text file.

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();
        }
    }
}

Here's how you'd use an object of the above class from a different location.

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));
    }
}

The console output in the above example would be '5'.

I've done the hard part. Now it's up to you to implement this into your program. To start off, whenever someone wins, I would retrieve the stored number of wins via the getWins method, add one to that value, and then use the saveWins method to store the incremented value. Keep in mind that even once you exit your program, the win values will be saved.

Note: There are much easier ways to do this if all you want to do is keep track of the wins within the lifespan of the program.

Joel Christophel
  • 2,604
  • 4
  • 30
  • 49
  • thanks, but where does the file save? – user2302407 Apr 20 '13 at 16:21
  • The file saves in your computer's default directory. On Windows 7, it would be C:\Users\Your User Name. The program is able to retrieve it despite it's save location. – Joel Christophel Apr 20 '13 at 16:24
  • Why this doesnt save anything? if(win == true){ JOptionPane.showMessageDialog(null, letter + " Won!"); /* start file write */ PrintWriter out; try { out = new PrintWriter("rezultati.txt"); out.println(letter + " Won!"); } catch (FileNotFoundException ex) { Logger.getLogger(XO2.class.getName()).log(Level.SEVERE, null, ex); } System.exit(0); } else if(count == 9 && win == false){ JOptionPane.showMessageDialog(null, "Draw!"); System.exit(0); } – user2302407 Apr 20 '13 at 16:52
  • What are you actually trying to write to a file? The statement "X Won!"? Or are you trying to record the number of times X won, as stated in the original question? And the reason it didn't save anything is because you'd need to pass in the entire path name to the PrintWriter constructor and not just the file name. – Joel Christophel Apr 20 '13 at 17:01
  • something very simple, i just want to save something to text file, even if its just X won, because that seems to complicated for me – user2302407 Apr 20 '13 at 17:25
  • So instead of passing in "rezultati.txt", try passing in "C:\\rezultati.txt". Two back slashes are used because in Java a single back slash is used for special commands within Strings. You can change the path to save it wherever you want, but make sure you're using double back slashes. – Joel Christophel Apr 20 '13 at 17:36
  • I'd appreciate it if you clicked the check mark next to my answer, signifying that you've chosen this as the most helpful answer. – Joel Christophel Apr 20 '13 at 18:19
  • it would be hard to make to play against computer? – user2302407 Apr 21 '13 at 10:18
  • Well, it would depend on whether or not the computer is smart. It wouldn't be too hard to have the computer make random turns, but that wouldn't be too much fun. Personally, I've never created artificial intelligence for a game. – Joel Christophel Apr 21 '13 at 12:35
0

Take a look at the following resources.

Reading and writing a text file.

How to write console output to a txt file.

How do I create and write data into a text file?

Community
  • 1
  • 1
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
  • the problem is that im a complete noob and i dont know how to use it, i looked at similar threads and tried to do something but it doesnt work – user2302407 Apr 20 '13 at 15:43