I am trying to make a very simple Tic Tac Toe game in Java. However, I cannot figure out how to draw something after I've drawn the board. Here's my structure of my game.
public class ThreeInARowMain extends JPanel {
public static final int WIDTH = 600, HEIGHT = 640;
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.black);
g.drawString("1.", 0,20);
g.drawString("2.", 210,20);
g.drawString("3.", 410,20);
g.drawString("4.", 0,220);
g.drawString("5.", 210,220);
g.drawString("6.", 410,220);
g.drawString("7.", 0,420);
g.drawString("8.", 210,420);
g.drawString("9.", 410,420);
//Horizontal Lines
g.drawLine(0, 200, WIDTH, 200);
g.drawLine(0, 400, WIDTH, 400);
//Vertical Lines
g.drawLine(200, 0, 200, HEIGHT);
g.drawLine(400, 0, 400, HEIGHT);
}
public static void main (String [] args) {
boolean firstorsecond = true;
JFrame frame = new JFrame("Tic Tac Toe");
frame.setSize(WIDTH, HEIGHT);
frame.getContentPane().add(new ThreeInARowMain());
frame.setLocationRelativeTo(null);
frame.setBackground(Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
boolean someonewins = false;
int firstplayerpos, secondplayerpos;
int [] [] board = new int [3] [3];
Scanner in = new Scanner(System.in);
while (!someonewins){
System.out.println("P1, enter the number of the square you'd like to mark.");
firstplayerpos = in.nextInt();
DrawXorO(firstplayerpos,firstorsecond);
System.out.println("P2, enter the number of the square you'd like to mark.");
secondplayerpos = in.nextInt();
DrawXorO(secondplayerpos,!firstorsecond);
}
}
public static void DrawXorO (int position, boolean firstorsecond) {
}
}
I know this is a badly designed game at the moment; I will correct that later. However, what I want with DrawXorO is to draw an X or and O in the position that the player has typed in. How do I add graphics after using the method paint? Thanks!
Do you mean something like this?
Here's one way to draw the tic tac toe diagram on the left of the GUI. I have a model class that keeps the board position in a 2 dimensional int array, and a mouse controller class that let's me know where the person clicked on the tic tac toe diagram.
And here's the mouse controller code.