How to make a TicTacToe game in Java?

My assignment requires me to make a java applet tic tac toe game. I have come as far as creating panels and adding 9 buttons to the center panel. The logic defeats me. I have looked around at the web for source code but everything looks fairly complicated. Here's what I have so far:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Homework5 extends Applet {
Panel northPanel = new Panel();
Panel southPanel = new Panel();
Panel eastPanel = new Panel();
Panel westPanel = new Panel();
Panel mainPanel = new Panel();
Button resetButton = new Button ("Tic Tac Toe");
Button squares[];
public void init() {
setLayout(new BorderLayout());
northPanel.setBackground(Color.orange);
southPanel.setBackground(Color.orange);
eastPanel.setBackground(Color.orange);
westPanel.setBackground(Color.orange);
mainPanel.setBackground(Color.orange);
add("North", northPanel);
add("South", southPanel);
add("East", eastPanel);
add("West", westPanel);
add("Center", mainPanel);
resetButton.setFont(new Font("Arial", Font.PLAIN, 12));
northPanel.add(resetButton);
mainPanel.setLayout(new GridLayout(3,3));
squares = new Button[9];
for ( int i = 0; i < 9; i++ ) {
squares[i] = new Button();
//squares.addActionListener(this);
squares[i].setFont(new Font("Serif", Font.BOLD, 20));
mainPanel.add(squares[i]);
Can someone explain to me where I should go from here?
Thanks.

I figured it out. :-)
I had to use 2 arrays (one to create the button and another to hold the X's and O's in memory). I also had to call on the getSource method for the values in my array. This is where I was getting stuck initially. 3 hours and 2 mountain dews later, I was all warm and fuzzy when it compiled without an error. :-)
You can see it in action here:
http://www.vnoel.com/pcc/cs162/applets/knarayan/homework5.html

Similar Messages

  • How to make a oval shape in java

    how to make an oval shape in java

    here's a simple example:
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Color;
    /* <applet code="OvalTest" width=83 height=43></applet> */
    public class OvalTest extends Applet {
         public void init() {
              setBackground(Color.white);
         public void paint(Graphics g) {
              g.setColor(Color.blue);
              g.fillOval(1,1,80,40);
    }

  • How to make a DVD game for ps3 in flash 3.0?

    so how would I go about making a DVD game like player 1 vs. player 2 or just player 1 solo in action script 3.0? i know 2.0 well enough and i know a little 3.0 but i am not an expert i am not looking for a complicated game just something simplistic with one question after another I just don't know how to make the options like a right answer a wrong answer and how that would effect scores. or how would i go about if player one got the question right it would go to the next question and if they got it wrong replay the question for player 2 and the points would reflect appropriately also how would i make a time limit for each question? I know you probably wont be able to answer all question I just wanted to convey what I am trying to do.

    I am also looking for an answer to this same querry, could you please infrom me when you do get any help.
    I believe you will get an answer because there some really smart and helpful folks on the adobe forum.
    All the best man.

  • How to make a net browser using java

    We want to make an MultiLingual Explorer in JAVA .So please help me in the case thatfirst i want to do the coding of the basic interface as the menu option like open,save,save As etc.So how can i start it in java.Is their any builtin support or what is the best possible ways.I sahll appreciate the cooperation....
    Kindly help me out....
    (As i am a student and new in java so plz guide me thoroughly)
    Thanx

    There have been java browsers that have been developed + this is well-documented (at least in one or two texts i've read, i assume on-line too), but they're quite complex + i doubt if someone new to java would be able to customise it without a brain haemorrhage. Tough call!

  • TicTacToe game in java

    Thanks alot for offering change to ask u people about problem we face it in java .. iam student in java course and i have project which i find difficulty to solve the problem.. this project is need to implement the Java Applet . it is the game of TicTacToe game ..two class need to be created.one of them has n-by -n(4 bye 4). the constructor inlialize the empty table to all zeros . the TicTacToe game require two players. Whereever the first player selcts a cell of the table , assigne 1 as a number to the selected cell. assing 2 wherever the second player selects a cell The value of the cell connot to be changed. it keeps its value after the first assignation . your player are allowed to select the cells they are interseted in.To this end. the enter the number of rwo and number to column that defind the postion of a cell.The program keeps askind the player n-by-n times . Finaly the progam display the state of the table...
    i hope some one answet to me soon .. i will be thanksfull for who could help me ..
    thanks alot .. wating for the answer ..

    heres a 3x3 one :)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Calendar;
    public class TicTacToe extends JPanel
         private JButton b[][];
         private JButton newGame;
         private JPanel innerPanel;
         private JPanel gamePanel;
         private JTextArea statistics;
         private String symbol = "x";
         private int x;
         private int o;
         private boolean myturn;
         private JLabel lab;
         private int day, year, month;
         public TicTacToe()
              super();
              Calendar cal = Calendar.getInstance();
              day = cal.get(Calendar.DATE);
              year = cal.get(Calendar.YEAR);
              month = (cal.get(Calendar.MONTH) + 1);
              lab = new JLabel("" + day + "/" + month + "/" + year );
              innerPanel = new JPanel();
              innerPanel.setLayout(new GridLayout(1,2));
              gamePanel = new JPanel();
              b = new     JButton[3][3];
              x=o=0;
              setLayout(new BorderLayout());
              gamePanel.setLayout(new GridLayout(3,3));
              initialize(true);
              add(lab, BorderLayout.NORTH);
              statistics = new JTextArea();
              statistics.setEnabled(false);
              innerPanel.add(gamePanel);
              innerPanel.add(statistics);
              add(innerPanel,BorderLayout.CENTER);
              printStatistics();
         private ActionListener createActionListener(JButton button)
              final JButton b = button;
              ActionListener a =
                        new ActionListener()
                             public void actionPerformed(ActionEvent ae)
                                  doPlay(b);
              return a;
         private void doPlay(JButton b)
              if (b.getText().equals(""))
                   b.setText(symbol);
                   if (winCondition(symbol))
                        enableGame(false);
                        if (symbol.equals("x"))
                             x++;
                        else
                             o++;
                        printStatistics();
                   if (symbol.equals("x"))
                        symbol = "o";
                   else
                        symbol = "x";
         private boolean winCondition(String s)
              boolean condition = true;
              for (int i=0 ;i<3 ;i++ )
                   condition = true;
                   for (int j=0; j<3 ;j++ )
                        condition = (condition && b[i][j].getText().equals(s));
                   if (condition)
                        return true;
              for (int i=0 ;i<3 ;i++ )
                   condition = true;
                   for (int j=0; j<3 ;j++ )
                        condition = (condition && b[j].getText().equals(s));
                   if (condition)
                        return true;
              condition = true;
              for (int i=0; i<3 ; i++ )
                   condition = (condition && b[i][i].getText().equals(s));
              if (condition)
                   return true;
              condition = true;
              for (int i=0;i<3 ;i++ )
                   condition = (condition && b[i][2-i].getText().equals(s));
              if (condition)
                   return true;
              return false;
         private void enableGame(boolean flag)
              for (int i=0;i<3;i++)
                   for (int j=0;j<3;j++)
                        b[i][j].setEnabled(flag);
         private void printStatistics()
              String print = "Player\tWins" +
                             "\nPlayer X\t" + x +
                             "\nPlayer O\t" +o;
              statistics.setText(print);
         public void initialize(boolean recreate)
              for (int i=0; i<3; i++)
                   for (int j=0; j<3; j++)
                        if (recreate)
                             b[i][j]= new JButton();
                        b[i][j].addActionListener(createActionListener(b[i][j]));
                        if (recreate)
                             gamePanel.add(b[i][j]);
              if (recreate)
                   newGame = new JButton("New Game");
              newGame.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent ae)
                             for (int i=0; i<3; i++)
                                  for (int j=0; j<3; j++)
                                       setButtonCaption("",i,j);
                             enableGame(true);
              if (recreate)
                   add(newGame,BorderLayout.SOUTH);
         public void setButtonCaption(String s,int row, int column)
              b[row][column].setText(s);
         public static void main(String[] args)
              //SplashScreen splash = new SplashScreen(1200, 1200,1);
              //splash.show();
              //dia sp = new dia(12);
              //sp.show();
              JFrame f = new JFrame("TicTacToe");
              Container c = f.getContentPane();
              TicTacToe t = new TicTacToe();
              f.addWindowListener
                   new WindowAdapter()
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              c.add(t,BorderLayout.CENTER);
              f.setSize(300,200);
              f.show();

  • How to make file associations in my java apps

    I am making a Graph maker in Java. Just give x = 1,2,3,4,5 and corresponding y = f(x) and get the discreate graph.
    The graph can then be saved as a file of extention .grf (say) on the hard disk, and can be opened in my graph maker software for editing, viewing e.t.c.
    Now my problem is that I want that when I dubble click on a file xyz.grf my graph maker should open automatically with this file opened in it, like other applications on windows say Notepad - dubble click on xyz.txt it will automatically launch Notepade with this file.
    In other way I want that any .grf file gets associated to my graf maker.
    Please help me and tell me the way, how should I proceed and how can I do this.

    aashishjava wrote:
    Yes Yes Yes It is 99% what I wanted to have. Thanks a lot ....You're welcome.
    But now I want some thing more,(hand to forehead) They always want more. ;)
    (a) There is a splash screen in my app. but JNLP always show its own splash screen, ...Webstart splash screens work differently to those of plain Jar files (which is unfortunate). A webstart splash screen has to be not included in the Jar, but available as a separate resource. The splash is defined in the JNLP launch file. For further details see the [JNLP File Syntax|http://java.sun.com/j2se/1.4.2/docs/guide/jws/developersguide/syntax.html].
    <quote>
    The optional kind="splash" attribute may be used in an icon element to indicate that the image is to be used as a "splash" screen during the launch of an application. If the JNLP file does not contain an icon element with a kind="splash" attribute, but does contain another icon tag, Java Web Start will display a splash screen consisting of the image specified by the icon element on the left and the application's title and vendor on the right.
    The first time an application is launched following the addition or modification of the icon element in the JNLP file, the old splash image will still be displayed. The new splash image will appear on the second and subsequent launches of the application.
    </quote>
    The 'ignored first time' is because the webstart client is more focused on getting the app. downloaded, cached and launched, than showing splashes. Once the app. is on-screen, it will download the splash in the background.
    One other 'gotcha' of splash screens is that the JNLP file must define a href in the JNLP element for the splash to be used. The webstart client assumes that a JNLP with no href is dynamically generated, and will not be the same twice. Because of that it ignores the splash!
    Edit 1:
    Unfortunately, I do not have any direct examples of using splash screens A splash is usually on my 'To Do' list for projects, but it is a very low priority.
    Edited by: AndrewThompson64 on Dec 10, 2009 11:35 AM

  • How to make a horizontal line in java html browser?? without hr

    I use java html browser
    I want to make a black horizontal line
    the <hr> line is not good
    for my customer it seems that there is a double spacing in this case
    I tried to write
    <td style = "BORDER-BOTTOM: 1px solid #000000"> ...
    but it does not work
    I suppose this style is not supported by the default StyleSheet
    I tried to write
    <td bgcolor="black" height=1>
    but the table has all rows with equal sizes
    therefore the real height is too big
    Please help me
    I tried to write
    <table border="1">... </table>
    even in this case I have table without any border

    Hi,
    the best way might be to use a blind table with all cells set to have a border on the bottom. The problem is that the standard Java runtime does not render such setting automatically. There is plenty of work involved to adapt it and still it then would work only in the adapted version and not the standard runtime environment.
    Anyway, you can find a working example of how to accomplish individual borders around table cells in open source application SimplyHTML at http://www.lightdev.com/dev/sh.htm
    Ulrich

  • How To Make A File Splitter In Java

    Hey everyone...is it possible to make a file splitter program in java swing?what API do you think should be used in creating that application and how does it work? Assume that the application will be ran on windows desktop. Thanks to all...

    * FileSplitter.java
    import java.util.*;
    public class FileSplitter {
        ArrayList list = new ArrayList();{
            list.add("test 01");
            list.add("test 02");
            list.add("test 03");
            list.add("test 04");
            list.add("test 05");
            list.add("test 06");
            list.add("test 07");
            list.add("test 08");
            list.add("test 09");
            list.add("test 10");
            list.add("test 11");
            list.add("test 12");
            list.add("test 13");
            list.add("test 14");
            list.add("test 15");
            list.add("test 16");
            list.add("test 17");
            list.add("test 18");
            list.add("test 19");
            list.add("test 20");
            list.add("test 21");
            list.add("test 22");
            list.add("test 23");
            list.add("test 24");
            list.add("test 25");
            list.add("test 26");
            list.add("test 27");
            list.add("test 28");
            list.add("test 29");
            list.add("test 30");
        public FileSplitter() {
            testAlgorithm();
        private void testAlgorithm(){
            final int randNo = list.size()/2;//=number of input records / 2
            Random r = new Random();         //creates a new random number generator
            List newlist = new ArrayList();  //constructs a new empty list
            while(list.size()> randNo) {//returns true if the number of elements in the list is greater than randNo
                //(half of the input records are splitted)
                int index = r.nextInt(list.size());//returns a random between 0 (inclusive)
                //and the number of elements in the list (exclusive)
                newlist.add(list.get(index));//returns the element at the specified position in the list
                //and appends it to the end of newlist
                list.remove(index);//removes the element at the specified position in the list
                //and shifts any subsequent elements to the left
            System.out.println("newlist: "+newlist);//one part of the file
            System.out.println("list: "+list);//the other part of throws file
        public static void main(String[] args) {
            new FileSplitter();
    }

  • How do i play yahoo games without java

    installing java to run games on my galaxy tab

    It is not possible to run Java based browser plugins in Android. Oracle, the people who make Java and Google, the people who make Android are currently in a legal battle. I would not expect Oracle to be releasing a Java plugin for Android due to this legal fight.
    As a workaround I would suggest searching the Android market (Play Store) for the type of game you want to play. There are hundreds of free and paid game apps in the store.

  • Can someone point in the right direction for how to make a multiplayer game over the internet

    Hello,
    I am looking into making a game where two people who can be in different places would log on to the app, log in and can play - i.e. they would be connected over the internet. I'm looking for a hint on what is the direction to take and which technologies.
    For example is there a best practice for example if you make an app with DirectX and C++, and you use some kind of web service or something? or is it easier using C# and XNA? just looking for some pointers in the right direction. I have played around
    with DirectX, far from proficient but have familiarity, I have no experience with XNA but hear it's less hardcore and easier going. I'm particularly interested in what the best way to connect over the internet.
    Thanks

    What you are asking is very complicated and one of the more difficult things you can do in gaming. I'd strongly recommend you start smaller to learn and then move up to multi-player games as your skills grow.
    From the multiplayer client perspective it doesn't really matter which technology you use. You can write a multiplayer game in any engine or technology that can talk to the network. Choose the client technology that you are most adept at and interested in
    and learn it. You can go straight to DX, use a third party library such as Monogame (XNA isn't supported for Windows Store apps), or a complete game engine such as Unity. Once you can write a decent one-player game you'll have the foundation to start on to
    build a two-player game.
    At that point you'll need to define the problem much more specifically. As you state it, it is really wide open. How do you want the users to connect? Directly machine to machine? Matched through a web server but running client side? Connecting to a game
    running on a remote server? Something else?
    The network connection itself is probably fairly straightforward, but where to connect and how to manage that can be difficult. You'll have to decide what properties you want. Is this an action game where responsiveness is important or
    a turn based game where timing is less relevant?
    Are the players connecting locally or completely remotely? If the former then they can probably connect directly over the local network (NFC is great here). If the latter then they probably will need to connect to a matchmaker service to avoid firewalls.
    This can get very complex, but there are existing solutions you can use rather than writing your own.
    --Rob

  • How to make app store   game

    Hi, I wanted to as you how can I make some ames and put it on app store and how much i need to pay. i want to get some money for my school in US. what programmer language you need to know? thanks

    You need a Mac and the latest XCode.
    The "native" language is Objective-C.
    It costs $99 to join the developer program to be able to put Apps in the App store.
    You would need to sell a lot of games to pay for a US University!

  • How to make a Exception class in java ?

    I want to make a class called SomeException. I want to throw this exception from my class Myclass. How to do it ??

    Just let SomeException extend Exception (or RuntimeException) and throw it the same way you'd throw any other exception. There's no magic involved.

  • How to make a modular program in java

    hello friends,
    i want to know that how i can make my program in a modular way.
    Thanks in advance
    Rakesh

    hello sir,
    thanks to notice me.
    modular program means, i have a large program which contains about 1500 lines. now i want to subdivide this program in multiple files and after call all files in a single main file . and want to run overall program from a single main file.
    regards,
    Rakesh

  • How to make a WSDL file generate Java Code

    Hi, I'm quite new in web services. I used the ebay shopping service importing the WSDL file with wsimport, and NetBeans automagically created the Ebay libraries while parsing the WSDL.
    Now I'm trying to implement my own soap WS, i'm quite finished but when I try to use it importing the WSDL in a new project, my classes are not imported.
    So, where's the trick? How can I include code generationi n my WSDL?
    thanks in advance :)

    hi,
    since the wsdl parsing was complet, for sure the classes are copied (.java), to see them check the following path
    YourService\build\generated\wsimport\client\YourService
    and the .class file will be in
    YourService\build\generated\wsimport\binaries\YourService

  • How to make Visibroker's 'vbjc' use Java 1.3 by modifying the properties fi

    Hi,
    I am using Visibroker for java 4.0 to develop an application. The
    java version that I am using is 1.4.1. Now, the naming service does
    not start when I use 1.4.1. And I cannot do away with Java1.4.1
    because I am using certain classes in javax.crypto which does not
    exist at all in Java 1.3. I am left with the option of trying to
    configure the properties file of 'vbjc' in such a way that it uses
    Java 1.3 instead of 1.4. How can i do this? Can someone please help me
    out?
    Thanks in advance,
    Shankar.

    HI!
    you hasn't given more details ;
    can you send me the command, by which you r trying to start the Naming service.
    As well as send me the error that you are getting , when used jdk1.4.1

Maybe you are looking for

  • Simple question on summing a formula field

    I am somewhat new to Crystal and have run across this need for the first time.  I have a simple report that allows for multiple quote numbers to be entered in a parameter, then groups lines by product # and then calculates in that group, the total qu

  • Transfer individual apps from Snow Leopard to clean installed Mountain Lion

    I had a Snow Leopard on Macbook Pro Early 2011. Took a backup (a clone with Carbon Copy Cloner) of the system and erased my volume to install an SSD and HDD combination, then did a fresh install of Mountain Lion from thumb drive , which I had prepare

  • Problem in JDBC receiver Updation

    Hi friends,     I am updating the DB using the JDBC receiver adapter. Tell me for the following case updation can be done or not.   key Field       Field1       Field2       A                  X           Y       B                  X         C       

  • Shortcuts to switch views in Finder don't work

    I am reading that Apple-1, Apple-2, and Apple-3 will switch between the icon, list, and column view in the Finder. Yet when I try this, nothing happens. Does it work on your machine, and if so, any idea why it doesn't work on mine?

  • Adobe photoshop elements will not work?

    Adobe photoshop elements 8 will not work?