My new game, Escape, is still in development. The concept has been decided, the project is being coded, and the model has been built. However, more and more dilemmas and obstacles have appeared and I’m encountering more challenges than I thought would. To continue with my process, I must overcome difficulties related to Java swing and the rendering system. Thus, I’m deciding to do some “exercises” before I start with the actual process.
My first excercise is to make my own Tic Tac Toe game:
Figuring out the dynamics of a game is much more significant than the actual coding: command lists (“cheats”) can be found on the internet, but arranging them in the correct sequence is diffcult. Basically, Tic Tac Toe uses a 3 x 3 square board that contains a total of 9 buttons. When a player clicks on a button, the trigered button will turn into an “X”, and then the computer (your opponent) will generate an “O” on a random location. Whoever gets three “X”s or “O”s wins. If no one wins, and all the boxes are occupied, it will be a draw.
IMPORTS (aka, special Java instructions, for anyone who’s not familiar with the term)
Here are all the imports from Java library (JSE 8.0). I need Jframe to make the game runnable and visible. Jpanel is necessary for simple management on Jbuttons. Actionlistener and actionevent function as a receiver and an executor.
I name these variables very casually since I am the only one that is supposed to know what they mean. However, it is important to memorize each function of each variable because it makes your life much easier when it comes time to debug. One time, by accident, I referred to the wrong variable somewhere in my code, and later on it became a disaster for me when I realized that there was a mistake inside hundreds of lines of codes.
METHOD.CHECK (How the game knows who wins!)
So how does the computer know excatly when the game ends or who wins/loses? A check method is triggered every time the player clicks on a button in the interface shown above. This class called method. check and basically examines if there are 3 sequences in a row. Here is the trick: each time a button turns into an “X”, the value of the corresponding variable will be set to “1”, and if the button turns into an “O”, the corresponding variable will be set to “-1”. If the button is null, the value will be “0” instead. Every time the method.check is triggered, the computer will add up the values of each row, column, and diagonal and seek for the “-3” or “3”, meaning defeat or victory.
GIVE IT A SHOT!
The url is provided below:
Notice: JSE 8.0 is required (provided below)
Words and images by Jiaming Yang