Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - adding 9 boxes within a main box

Tags:

java

Typical newb here. Trying to construct the all mighty tic-tac-toe grid for my first programming class.

I've been trying everything that makes sense to do this from the api documentation but no luck so far.

I think my biggest problem is not understanding how to use methods and parameters, and being a total rookie, but I'll get there.

This is what I have:

import java.awt.Rectangle;

public class TicTacToe {
    public static void main (String[] args) {
        new Rectangle (0,0,30,30); //create new box
        Rectangle box = new Rectangle (0,0,30,30); // tying the box to a variable

        box.add (Rectangle 0,0,10,10); /* error box can onot be resolved to a variable*/

    }
}

So my question is how do I add 9 boxes of size width 10 height 10 to this larger box? When I add these boxes I have to input new xy dimensions too right?

Thank you for the help!

like image 500
user1676338 Avatar asked Nov 03 '22 16:11

user1676338


1 Answers

I assume your goal here is to write a simple command line program, not one with a user interface. Correct? If so, then you need to think about the problem from a computer standpoint. While a tic tac toe board is a set of 9 squares to a human, to a computer, it is just a set of 9 variables, each of which can have 3 possible states: 1) filled with an X, 2) filled with a O, and 3) open. So your board could be represented as, for example, an an array of 9 integers.

Like this:

int[] board = new int[9];

To keep track of the state of each square, you can declare some constants:

static final int OPEN = 0;
static final int FILLED_WITH_X = 1;
static final int FILLED_WITH_O = 2;

The rest of your program can just manipulate the board array, changing its state (ie the values of its elements) as necessary. You could even output a string representation of this board to the command line.

The only reason you would use the Rectangle class would be if you plan to draw the board on the screen. In that case, I would create one large rectangle with a white background and draw that on the screen. Then I would draw 9 smaller rectangles on top of it, each with a dark background, giving you your game grid. Finally I would draw the x's and o's (circles and crossed line segments) at the appropriate locations based on the state of the board array previously discussed. The important point here is that there is no need to have rectangles objects contained in a parent. In fact, you only need to figure out the set of coordinates (4 decimal numbers) for each that you want to draw and then write a method that draws a rectangle on the screen at the desired location.

like image 120
CBass Avatar answered Nov 15 '22 01:11

CBass