I am very new at programming in Java. Could somebody help me out with programming a Tic Tac Toe game?
I would love to have to have the code for a game that can be played against the CPU.
The assignment is to write the tic tac toe game using arrays.
Thanks in advance.

Recommended Answers

All 26 Replies

If this is your assignment then nobody here will help you cheat by giving you code.
But if you are willing to learn and to make some effort then we will be very happy to help you.
So...
Try to do it yourself. If/when you get stuck come back here, show what you have done so far, explain what’s stopping you, and someone will help.

There is a big difference between

Could somebody help me out with programming a Tic Tac Toe game?

and

I would love to have to have the code

The first is "I'm stuck here" and the second is "I don't want to bother to learn anything. Please do it for me." At least you admit that it is for an assignment.

Sure. There's plenty of examples ready to go.

I'll look at http://rosettacode.org/wiki/Category:Programming_Tasks and find Tic-Tac-Toe is currently up to 49 languges for TTT.

I really want to know if you tried to find this code if that was your intent. With today's search engines and ready for the taking sites like RosettaCode, I am asking "How could you not find this code?"

As to your assignment, maybe you need to go over what your class has covered so far. The assignments build on what you were taught up to this point.

Thanks, rproffitt, but those are all a little too advanced for the class I'm taking. My class hasn't even gotten to stuff on that scale yet.

when you get stuck come back here, show what you have done so far, explain what’s stopping you, and someone will help.

Sure, James. I was able to get this done, but I have no Idea where to start with programming the CPU's turns.

The thing that's stopping me is the fact that I have no idea what I'm doing. I have an F in my computer science class right now, which I partially blame on my teacher's lack of explaination. I'm doing this for a high school computer science course.

import java.util.*;

public class TicTacToe
{

    private String[][] board; 
    static String X = "X";
    static String O = "O";    

    public TicTacToe()
    {

        board = new String[3][3]; 
    }

    public void printBoard()
    {
        System.out.println();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == null) {
                    System.out.print("_");
                } else {
                    System.out.print(board[i][j]);
                }
                if (j < 2) {
                    System.out.print("|");
                } else {
                    System.out.println();
                } 
             }
         }
         System.out.println();
    }

    public Boolean checkWinner(String play) {
        int playInRow = 0;
        int playD1 = 0;
        int playD2 = 0;
        int[] playInColumn = new int[board[0].length];   // assumes square board
        for (int i = 0; i < board.length; i++) {
            playInRow = 0;
            for (int j = 0; j < board[i].length; j++) {
                if (null == board[i][j]) {
                    continue;
                }
                if (board[i][j].equals(play)) {
                    playInRow++;
                    playInColumn[j]++;
                    if (i == j) {
                        playD1++;
                    } else if (2 == i + j) {
                        playD2++;
                    }
                }

            }
            if (playInRow == 3) {
                return true;
            }
        }
        if (3 == playD1 || 3 == playD2) {
            return true;
        }
        for (int i = 0; i < playInColumn.length; i++) {
            if (playInColumn[i] == 3) {
                return true;
            }
        }
        return false;    
    }

    public void makeMove(Scanner stdin, String play) {
        int r;
        int c;
        Boolean goodInput = false;
        while(!goodInput) {
            r = -1;
            c = -1;
            System.out.println ("Enter coordinates to play your " + play);
            if (stdin.hasNextInt()) {  // must be integers
                r = stdin.nextInt();
            }
            if (stdin.hasNextInt()) {
                c = stdin.nextInt();
            }
            else {
                stdin.nextLine();      // consume a line without an integer
                System.out.println("Both inputs must be integers between 0 and 2.");
                continue;
            }
            // must be in the right coordinate range
            if ((r < 0) || (r > 2) || (c < 0) || (c > 2)) {
                System.out.println("Both inputs must be integers between 0 and 2.");
                continue;                
            } 
            // make sure the space is not occupied
            else if (board[r][c] != null ){  
                System.out.println("That location is occupied");
                continue; 
            }
            else {
                board[r][c] = play;
                return;
            }
        }
        return;
    }

    public static void main(String[] args) {

        TicTacToe ttt = new TicTacToe();            
        Scanner stdin = new Scanner(System.in); 

        int moves = 0;
        System.out.println("Let's play TicTacToe -- X goes first");
        ttt.printBoard();
        while (moves < 9) {
            ttt.makeMove(stdin, ttt.X);
            moves++;
            if (moves > 4) {
                if (ttt.checkWinner(X)) {
                   System.out.println(X + " You Win!!!");
                   break;
                }
            }
            ttt.printBoard();
            ttt.makeMove(stdin, ttt.O);
            moves++;
            if (moves > 4) {
                if (ttt.checkWinner(O)) {
                   System.out.println(O + " You Win!!!");
                   break;
                }
            }
            ttt.printBoard();

        }
    }
}

@Z. I can imagine. Even I with decades of programming behind me stand amazed at 49 versions of Tic-Tac-Toe. I stand by my answer and still wonder about how you could not find more today about this common application. (you didn't answer my question.)

So my answer is this. Review your class material to this point along with the class prerequisites and you should be ready to tackle this assignment.

Short of folk writing it for you, this is how programming is taught today. You work your way through the class, building knowledge and skills that are tested with the assignments. Sometimes a student never gets it. They have to tell the teacher they are stuck and hopefully get pointers on where to research and what material to go over again.

rproffitt, the answer to your question is that, since I am in an early high school class, all of the programs I could find online have things my class hasn't even learned yet.

And, yes, I literally have one week left in the class, and I still have just about no idea what I am doing. I'm failing the class, which is actually my only class that I don't have an A or a B in.

@Z. If you think this will be a F, is there an option to take a non-completion rather than affect your average grade?

Programming isn't for everyone or rather, it may take time to take other courses (Math is always good!) to build up your skills to tackle programming.

For example long after I took various programming classes I went back and took some system analysis classes. This was gold to me since it took my rather haphazard approach to solving problems and helped me see the problem at different levels. This is not a skill we are born with. We have to learn, apply, adapt and survive along the way. No one I know started with programming classes alone. They had to develop their math and problem solving skills along the way.

@rproffitt There sadly isn't an option to take a non-completion.
About the math, I took algebra last year. and finished with a B.
I am taking geometry right now and currently have an A+.

I was thinking about dropping out of the computer science class, but my school charges $45 to drop out of a class.

That may be money well spent.

Out of curiosity I have never heard of a high school charging money to drop a class.

Yeah, neither have I.
It's not really dropping the class. Each student is required to take 8 classes at all times, which would require the student to switch to another class.

To me this would be a wise choice since your GPA could have effects on college choices. Switch to a class you can excel at. Programming isn't for everyone. And sometimes you need time for the brain to ponder the concepts.

This is an odd conversation...
We do get people posting here who obviously don’t have what it takes to be a software wiz. But with A’s in math you clearly have the necessary mental equipment, and the code you posted is is high quality stuff which means either (a) you just copied it or (b) you have far more programming ability than you think. If it’s (a) then we’re all wasting our time here. If it’s (b) then you have a confidence problem, not a programming problem.
Let’s assume it’s (b). You are looking at the assignment in a state of funk and blind panic. You don’t know where to start.
So start with stuff you feel comfortable with. Get some paper and pen. Play tic-tac-toe a few games. Start to write down what you are thinking as you chose moves. After a bit you will have written down some rules about how to chose moves. Now go back to your pc and think about how to turn those rules into code. Start some easy cases, eg there is a winning move available... how do you identify that winning move? Get that working. It’s not quick, but then it was never going to be quick.
There’s a common mistake that learners make, which is to try to solve the whole program in one magnificent try. They type in hundreds of lines of hopeful code before even trying to compile it. When it doesn’t work they don’t know where to start fixing it. Experienced coders work in small increments, compiling and testing one small step at a time. Fixing one problem at a time. Maybe later they will find that there direction wasn’t quite right and they have to backtrack and re-work a bit, but that’s ok.
The longest journey starts with...

commented: I worry this isn't the OP's code. I'm reading http://www.cs.utexas.edu/users/mckinley/305j/lectures/BlueJExamples/22-2Darrays/TicTacToe.java +15

It is entirely possible you have a terrible prof. For example, one of my third year classes was in databases (circa 1976). This was in the days before the plethora of DB engines vailable now. Here is an example (odd that I remember it word for word) of one of the lectures:

This is not a description of the structure of an information structure. It is a description of the structure of a description of an information structure.

The entire class was like that. I dropped the course and took it again the next year from a different prof. I got an A. The first prof wanted to impress us. The second one wanted to teach us.

James, one of my friends (who I think is a computer genius) did try to help me with the code. In the end, I think he just ended up giving me the answer without me understanding it.

Jim, I feel like the teacher is great at computers, but he is just terrible at teaching it.

I think he just ended up giving me the answer without me understanding it.

Beginners' programming teaching builds concepts one at a time. Miss one step and the following step won't make sense. Miss a couple of steps and nothing will make sense.
Your choice is brutal - go back and work through the previous step(s), or give up now.

Your choice is brutal - go back and work through the previous step(s), or give up now.

I gave up... at least on this assignment. My grade dropped slightly, but it doesn't worry me too much.

miss one step and the following step won't make sense. Miss a couple of steps and nothing will make sense.
This is the perfect explaination of what I seem to be going through. I missed quite a bit, so I feel like I don't get any of it.

ZheeYT,

Don't let the people who can do nothing but judge and ASSume
get you down.  In my first computer programming class in high school I was able to follow the book enough to copy code samples from the lessons and alter them enough to make them work without really knowing what I was doing.  I had a real hard time getting past not knowing how the computer actually converted the code to functionality.  We only had a classroom, a blackboard with the assignment, and one computer, we didn't even have a dedicated teacher, to get help we had to interrupt his remedial math class to ask questions, I can tell you that didn't make us popular at all.  Anyway, I asked him what to do because I just wasn't getting it! 

Reading your post I got the feeling that you may have a similar case.  I would recommend you find a different site to seek assistance.  If I had people telling me what they are telling you on this site, I may have quit back then too, but I didn't.  I now have sold my software from Australia to Singapore. 
My software is used in some of the largest resorts in the world.  I would like to help you.  Like others here have stated I will not provide you the code you are seeking, but I may be able to provide a point of view you haven't been exposed to that may help you get it!  Ignore the haters, they are going to hate, and I am sure I am going to get some feedback from this, but I don’t think the person who created this site meant for it to be so negative, it is as if some people here take it personally that others are not as anal as they are. 
But anyway my teacher wasn't a computer programmer, just a math teacher who got assigned the job. He gave me the operations manual (680 pages) and said that it might help if I studied it, he had no clue.  I stumbled through the first four chapters and was more lost than before, so I did what I always do with school books, I went to the back two chapters, which usually summarizes the entire book.  I read how the computer converts code to machine language and how each bit is a portion of a byte, and the register transfers the bits litterally one at a time to move data and images and how each command in the computer language we use is in reality millions of individual actions, with variances built in, so that as we built a human sounding language code, the computer removed only the portion of each command that relates to exactly what is happening at the moment. For instance, the Print command can take a lot of different optional parameters which alters drastically what is output depending on what parameters you use and how you format things.  The Print command can handle dozens of different situations, but when it actual compiles, or is interpreted as the case may be, only the relevant portion is converted to the machine code that the computer actually uses at run time.

This is why each command in the language can do so many different things, if you know how to apply it for that purpose.  Even now after programming for forty years I have to refer to the books to know exactly how to implement what I am trying to accomplish.  In your case I think you are getting hung up on the wording of the assignment, getting the CPU to make plays.  All that means is using the computer code to provide the computer options as a player and instead of looking for input from a user, have the code decide where to play.  Your assignment does not seem to want you to create a program that wins, just one that can make a play, look at your assignment that way.  Start by designing
the playing field.  I would simply use the underscore character and the pipe character (|) to build the TTT Grid inside an array and make the array contain the grid and the space character as a placeholder for the Xs and Os.  From there treat it like you are building a two-player game, then when it is player Computer turn, you use random numbers to get the computer to play.  Later you can worry about making it smart, but for now just approach it as a child making random moves. Have the computer make a choice, then make sure there is a space character stored in the array at that location, and change it to the X or O as the case may be, if the position is not a space, have the computer choose another random play until it can play.

Hi KeyWizard.

Don't let the people who can do nothing but judge and ASSume get you down... haters, they are going to hate

I think you may have gotten the wrong idea from the various posts in this thread. The people who posted have about 100 years programming experience between them, and have taught or assisted hundreds of learners. We were not saying that OP should give up. We were saying that he has to do the work, not copy code blindly, and understand each stage, otherwize he may as well give up because that's not going to work.

Your own experience confirms that - you had to spend time and effort at the beginning to understand it from the most basic level upwards. But it paid off and you have enjoyed real success.

Just check out a few other topics here - you will see that DaniWeb is an outstanding support resource for anyone who genuinely wants to learn, and our contributors will go to great lengths to help people who are willing to make the necessary effort.

JC

commented: I bet over 100 years. First computer program for me was 1972. Ouch. +15

rproffitt: ...over 100 years. First computer program for me was 1972

Well. yes way over 100 then. I joined IBM as a trainee programmer in 1969 and I'm pretty sure the Rev is a similar vintage...

commented: Would be interesting to add up active member programming yerars. All active folk have been very nice, even to the new folk. +15

Similar, indeed. I started programming in first year engineering in 1971 then switched to comp sci the next year.

Let me join the club. I started FORTRAN programming in first year chemistry. It was in 1971. Never switched to CS though.

OK. We're old.

Yesterday I was roller skating on the bike/walking path. I wear old-school roller skates (the kind they wear for roller derby), not the in-line roller blades. There is a bit of gravel on the path that occasionally causes me grief and when I came across two young (20-ish) girls/women who were roller blading, I stopped to ask them how roller blades were in gravel. Somewhere during the conversation they commented on my "still" roller skating, then added (in that sweet, condescending tone that I usually only hear spoken to people in nursing homes who just swallowed their pills with no fuss) "good for you" .

Also, somehow I've made the transition from "looking good" to "looking good for my age".

OK. We're old.

No way.

Senior, experienced, world-wize, maybe. Young people trapped in past-their-sell-by bodies, maybe. But old, no. Old is a state of mind.
OK, time for my guitar practice.

Haha, it's beginning to sound like Statler and Waldorf here.
I have an old sick body but my mind is still some 25 years I guess. So that helps.
Tomorrow I'll have my 3 monthly liver check-up. My kidney check is planned for begin July.
No guitar for me no more, due to some light arthritis in two of my fingers. :(

Young people trapped in past-their-sell-by bodies, maybe. But old, no. Old is a state of mind.

I couldn't agree with you more. I've never felt the age I was at the time. I don't even know what age I feel like now (mentally, that is). Of course, knowing that, I still see my father-in-law as an old fart. I always had it in my head that just about everyone (management/mods) on Daniweb was around 40 years younger than me. Except for Ancient Dragon, of course, and Diafol (but only because I've seen a picture of him with his kids and lovely new bride). And ddanbe has even more aches and pains than I do.

It's not the years, it's the mileage.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.