Jump to content

Photo

Wrote this Code instead of studying let me know what you think I want to be a better programmer.

* * * * * 1 votes

  • Please log in to reply
2 replies to this topic

#1
maxaustein

maxaustein
  • Members
  • 2 posts
  • Joined: 20-October 10

My school's annual finals testing was happening this week. So, I spent my Sunday prepping with some buddies for our exams, I knew my Computer Science exam (the course is taught in Java) exam was going to fall on a hard day so instead of studying I just wrote this program.

 

 I'm not sure how to program in a Cat's Game and the CPU vs CPU function is a bit unpredictable.

 

I just learned to code recently but this really wasn't as hard as you'd think. It was a good project to start building my skills and I was wondering if anyone has some suggestions on what to do next!

 

 

 
/**
 * This class simulates a Tic Tac Toe Game.
 * 
 * @author Max Goldstein 
 * @version 1.25
 */
import java.io.PrintStream;
import java.util.Scanner;
 
public class TicTacToe
{
    PrintStream O = new PrintStream(System.out);
    Scanner I = new Scanner(System.in);
    
    private char[] board = new char[15];
    private char choice;
    private int numOfPlayers;
    private int errorCode;
    
    /*
     * This is the default constructor for the TicTacToe class.
     * Sets all squares to default values.
     */
    public TicTacToe()
    {
    this.board[0] = '0';
    this.board[1] = '1';
    this.board[2] = '2';
    this.board[3] = '3';
    this.board[4] = '4';
    this.board[5] = '5';
    this.board[6] = '6';
    this.board[7] = '7';
    this.board[8] = '8';
    this.errorCode = 0;
    }
        
    /*
     * Resets the game conditions to default values.
     */
    public void resetBoard()
    {
    this.board[0] = '0';
    this.board[1] = '1';
    this.board[2] = '2';
    this.board[3] = '3';
    this.board[4] = '4';
    this.board[5] = '5';
    this.board[6] = '6';
    this.board[7] = '7';
    this.board[8] = '8';
    this.errorCode = 0;
    }
    
    /*
     * This method checks if a win has been achieved.
     * @return Whether or not 3 in a row has been achieved.
     */
    public boolean isWon()
    {
        if ((this.board[0] == this.board[1]) && (this.board[1] == this.board[2])) 
        {
            System.out.println(""+this.board[0]+" Wins!");
            return true;
        }
        
        if ((this.board[3] == this.board[4]) && (this.board[4] == this.board[5])) 
        {
            System.out.println(""+this.board[4]+" Wins!");
            return true;
        }
        
        if ((this.board[6] == this.board[7]) && (this.board[7] == this.board[8])) 
        {
            System.out.println(""+this.board[7]+" Wins!");
            return true;
        }
        
        if ((this.board[0] == this.board[3]) && (this.board[3] == this.board[6])) 
        {
            System.out.println(""+this.board[3]+" Wins!");
            return true;
        }
        
        if ((this.board[1] == this.board[4]) && (this.board[4] == this.board[7])) 
        {
            System.out.println(""+this.board[4]+" Wins!");
            return true;
        }
        
        if ((this.board[2] == this.board[5]) && (this.board[5] == this.board[8])) 
        {
            System.out.println(""+this.board[5]+" Wins!");
            return true;
        }
        
        if ((this.board[6] == this.board[4]) && (this.board[4] == this.board[2])) 
        {
            System.out.println(""+this.board[4]+" Wins!");
            return true;
        }
        
        if ((this.board[0] == this.board[4]) && (this.board[4] == this.board[8])) 
        {
            System.out.println(""+this.board[4]+" Wins!");
            return true;
        }
        
        return false; 
    }
    
    /*
     * This method prints the gameboard in its current form.
     */
     public void getBoard()
    {
        String board = "   |   |   \n"
           +" "+this.board[0]+" | "+this.board[1]+" | "+this.board[2]+" \n"
           +"   |   |   \n"+"-----------\n"+"   |   |   \n"+" "+this.board[3]+" | "+this.board[4]+" | "+this.board[5]+" \n"
           +"   |   |   \n"+"-----------\n"+"   |   |   \n"+this.board[6]+"  | "+this.board[7]+" | "+this.board[8]+" \n"
           +"   |   |   \n";
        System.out.println(board);
    }
    
    /*
     * This method modifies the game board.
     * @param choice Is an 'X' or 'O' being placed?
     * @param pos The position on the board where the item is being placed.
     */
    public void setBoard (char choice, int pos) 
    {
        boolean done = false;
        while (done != true)
        {
        this.isLegal(choice, pos);
        if (this.isLegal(choice, pos) != false) 
        {
            this.board[pos] = choice;
            done = true;
            this.errorCode = 0;
        }
        else
        {
            O.println("Illegal move. Try again\n");
            this.errorCode = 1;
            done = true;
        }
        }
    }
    
    /*
     * This method checks to see if the position is filled.
     * @return Whether or not the proposed move is legal.
     */
    public boolean isLegal(char choice, int pos)
    {
       if (this.board[pos] == 'X' || this.board[pos] == 'O') return false;
       else return true;
    }
    
    /**
     * This method creates a 1 player game.
     */
    public void oneVsCPU()
    {
        this.getBoard();
        this.playX();
        System.out.println("Computer thinking...");
        this.playCPU('O');
    }
    
    /**
     * This method creates a two player game.
     */
    public void oneVsOne()
    {
        this.getBoard();
        this.playX();
        this.playO();
    }
    
    /**
     * This method creates a zero player game.
     */
    public void CPUVsCPU()
    {
        this.getBoard();
        this.playCPU('X');
        this.playCPU('O');
    }
    
    /*
     * Prompts player 1 for their move.
     * Player 1 is conventionally 'X'.
     */
    public void playX()
    {
    O.println("[1] Choose Position: ");
    int pos = I.nextInt();
    this.setBoard( 'X', pos);
    if (this.errorCode == 1)
    {
    O.println("[1] Choose Position: ");
    pos = I.nextInt();
    this.setBoard( 'X', pos);
    this.isWon();
    }
    this.getBoard();
    }
    
    /*
     * Prompts player 2 for their move.
     * Player 2 is conventionally 'O'.
     */
    public void playO()
    {
    O.println("[2] Choose Position: ");
    int pos = I.nextInt();
    this.setBoard( 'O', pos);
    if (this.errorCode == 1)
    {
    O.println("[2] Choose Position: ");
    pos = I.nextInt();
    this.setBoard( 'O', pos);
    this.isWon();
    }
    this.getBoard();
    }
    
    /*
     * Creates and acts as a CPU player.
     * @param choice Is an 'X' or 'O' being placed on the board?
     */
    public void playCPU(char choice)
    {
        boolean isLegal = false;
        while (isLegal != true)
        {
        int move = (int)(Math.random() * 10 - 1);
        this.isLegal(choice, move);
        if (this.isLegal(choice, move) == true)
        {
        this.setBoard(choice, move);
        this.isWon();
        this.getBoard();
        isLegal = true;
        }
        else 
        {
            move = (int)(Math.random() * 10 - 1);
        }
    }
 
    }
    
    public static void main(String[] args)
    {
        TicTacToe game = new TicTacToe();
        PrintStream O = new PrintStream(System.out);
        Scanner I = new Scanner(System.in);
        O.print ("Welcome to Tic-Tac-Toe!\n");
        game.getBoard();
        
        while (true)
        {
        game.resetBoard();
        game.numOfPlayers = -3;
        game.errorCode = 0;
        O.println("1 or 2 Players? :");
        game.numOfPlayers = I.nextInt();
       
        while (game.numOfPlayers == 1 && game.isWon() == false) 
        {
            game.oneVsCPU();
        }
        
        while (game.numOfPlayers == 2 && game.isWon() == false) 
        {
            game.oneVsOne();
        }
        
        while (game.numOfPlayers == 0 && game.isWon() == false) 
        {
            game.CPUVsCPU();
        }
        
        }
        }
        
    }
 

 


1-year programmer, Java, C.

 

Have a Sh*t day!


#2
Sephern

Sephern
  • Moderators
  • 1,143 posts
  • Joined: 04-June 10
  • LocationLondon, UK
  • Expertise:HTML, CSS, PHP, Javascript, Python

Looks like you've made a pretty good start! Here are some comments in no particular order

 

  1. All of your code right now is in one class. Think about what different classes you might be able to split out - I think the board is a pretty good place to start. If you're struggling with this, try to think about what changes you might want to make to your tic-tac-toe game, and which parts of it would stay the same if you make that change. For example, if you wanted to make a GUI instead of a console app, the 'Board' probably wouldn't change (but your rendering logic would). This means they're good candidates to be decoupled. If you're already quite comfortable with this, and would like some more advanced reading, this is a good place to start, and should help you think about how to break your application down into classes & objects.
  2. Look at places where some of your code is duplicated. For example, the "playX" and "playO" methods look very similar. Could you extract some of this code out into a smaller, reusable private method? This means that if you find a bug in part of your code, or want to extend it to have more functionality, you only have to do it in one place rather than copying and pasting it everywhere.
  3. The 'isWon' method looks quite long, and you're manually checking a bunch of cases. Would it be possible to write it in a more concise way? Possibly using modulo? Likewise with your constructor and resetBoard methods - could you use a loop?
  4. What sort of tests would you write to verify that your code is working as expected? How do you think they might change as you break up your application into smaller classes (see point 1). You could have a go at writing them with JUnit or another Java unit testing framework.

 

Hope this helps, and best of luck with your finals!



#3
TheEmpty

TheEmpty

    Less annoying than LinkedIn's Emails

  • Members
  • 5,433 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, Node.js, SQL, MongoDB

 

The 'isWon' method looks quite long, and you're manually checking a bunch of cases. Would it be possible to write it in a more concise way? Possibly using modulo? Likewise with your constructor and resetBoard methods - could you use a loop?

I so want to link my modulo solution, ugghhh. I love modulo! 

 

This looks like a 101 level course? With that in mind, I wouldn't care about 4 yet, you'll get there, but I wouldn't overload yourself now. I think in order of importance 2,1,3. But yeah all of Sephren's advice is good and I'm sure there are a lot of us here that are happy to help out a bit if you get stuck.


all-thin-banner.jpg




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users