Click here to Skip to main content
15,901,368 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I can't figure out how to code for it.I have tried asking

What I have tried:

I have tried searching it up but none of those worked.
Posted
Updated 16-Mar-22 23:40pm

Given your other recent question[^], you're not ready for this yet. The question also depends on whether the program will play against you, or whether it will simply allow two people to play against each other.
 
Share this answer
 
Comments
Timothy Stone 2021 16-Mar-22 20:45pm    
it would be two people playing against each other but thank you anyway!
Maybe you should start with a simple Java IDE like BlueJ, see: best-java-ides-or-editors[^]

Then try a tutorial like this one with several examples with increasing difficulty:
Tic-tac-toe - Java Game Programming Case Study[^]

Or, if you prefer a video: How to make a simple TIC TAC TOE game in java | BlueJ | Text Based Game | NoobMasterJONA | Java - YouTube[^]
 
Share this answer
 
v2
Here is a Python version, which you could adapt fairly easily:
Python
'''A simple noughts and crosses game

    This is really used as a test of tkinter under Python.
    The actual game and its result are displayed on the screen
    but no scoring is kept.
'''

import tkinter as tk
import tkinter.font as tkfont


# Start by defining some constant values

# The diagram will be sized based on these two constants
BOXSIZE = 60                                 # individual square size
MARGIN = BOXSIZE * 2 / 3                     # origin of the game diagram in the canvas

HEIGHT = WIDTH = BOXSIZE * 3 + MARGIN * 2    # width and height of the drawing surface

FONTSIZE = int(-BOXSIZE * 3 / 4)             # size in pixels NB int() must be used here
LINESIZE = FONTSIZE / -8                     # the width of the line drawn through the winning boxes

BUTTON_LEFT = 1
BUTTON_RIGHT = 3

# matrix to track the filled squares
squares = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
]

# a boolean so we know when time is up
game_over = False

def new_game():
    # Reset the program to start a new game

    canvas.delete('all')
    
    # clear the matrix
    global squares # make sure we use the correct variable
    squares = [[0 for col in squares[0]] for row in squares]
    
    # set the start and end points of the lines and draw the boxes
    xy1 = MARGIN
    xy2 = xy1 + BOXSIZE * 3

    # draw the vertical lines
    for x in range(4):
        row = x * BOXSIZE + MARGIN
        canvas.create_line(row, xy1, row, xy2)
    
    # draw the horizontal lines
    for y in range(4):
        column = y * BOXSIZE + MARGIN
        canvas.create_line(xy1, column, xy2, column)
    canvas.pack()
    global game_over
    game_over = False


def screen_to_square(pos: int) -> int:
    '''Convert the x and y screen coordinates to offsets into the squares matrix
    
    This works for mouse X or Y co-ordinates since the frame is a
    symmetrical 3 x 3 diagram
    '''

    xory = pos - MARGIN # get the X or Y mouse position in the canvas
    xory //= BOXSIZE    # calculate the offset
    if xory < 0 or xory > 2:
        xory = None
    return int(xory) # return the row or column number

def draw_letter(x: int, y: int, XO: str, colour: str) -> None:
    # Draw the X or O on the relevant square"""

    x = MARGIN + x * BOXSIZE + BOXSIZE // 2   # characters are aligned at the centre
    y = MARGIN + y * BOXSIZE + BOXSIZE // 2
    canvas.create_text(x, y, text=XO, font=font, fill=colour)

def draw_line(x1: int, y1: int, x2: int, y2: int, colour: str) -> None:
    # Draw a line across the three completed squares"""

    offset = MARGIN + BOXSIZE // 5   # start point of the line
    # calculate the start and end points of the line
    x1 = x1 * BOXSIZE + offset
    x2 = x2 * BOXSIZE + offset
    y1 = y1 * BOXSIZE + offset
    y2 = y2 * BOXSIZE + offset

    adjustment1 = BOXSIZE // 3      # one third
    adjustment2 = adjustment1 * 2   # two thirds
    if y1 == y2:
        # adjustment for horizontal lines
        x2 += adjustment2
        y1 += adjustment1
        y2 += adjustment1
    elif x1 == x2:
        # adjustment for vertical lines
        y2 += adjustment2
        x1 += adjustment1
        x2 += adjustment1
    elif x1 < x2 and y1 < y2:
        # adjustment for top left to bottom right
        x2 += adjustment2
        y2 += adjustment2
    else:
        # adjustment for top right to bottom left
        y1 += adjustment2
        x2 += adjustment2
    canvas.create_line(x1, y1, x2, y2, width=LINESIZE, fill=colour)
    
    global game_over
    game_over = True

def on_click(event: tk.Event) -> None:
    # Handle the button click event"""
    if game_over:
        return
    # convert mouse position to relative square
    x = screen_to_square(event.x)
    y = screen_to_square(event.y)
    if x == None or y == None or squares[x][y] != 0:
        return # invalid point or the square is already used

    # select the correct character and colour to draw
    XO = 'X' if event.num == BUTTON_LEFT else 'O'
    colour = 'red' if event.num == BUTTON_LEFT else 'blue'
    squares[x][y] = XO # mark this square in use
    draw_letter(x, y, XO, colour)

    # check for a completed line and mark it if so
    for row in range(3):
        # Check for a horizontal set
        if (squares[row][0] != 0
                and squares[row][1] == squares[row][0]
                and squares[row][2] == squares[row][0]):
            draw_line(row, 0, row, 2, colour)
            return

    for col in range(3):
        # Check for a vertical set
        if (squares[0][col] != 0
                and squares[1][col] == squares[0][col]
                and squares[2][col] == squares[0][col]):
            draw_line(0, col, 2, col, colour)
            return

    if (squares[0][0] != 0
            and squares[1][1] == squares[0][0]
            and squares[2][2] == squares[0][0]):
        # Top left to bottom right
        draw_line(0, 0, 2, 2, colour)
    elif (squares[2][0] != 0
            and squares[1][1] == squares[2][0]
            and squares[0][2] == squares[2][0]):
        # Top right to bottom left
        draw_line(0, 2, 2, 0, colour)


# Start of main program"""
root = tk.Tk()
root.title('Noughts and Crosses')

# The font used to draw the noughts and crosses
font = tkfont.Font(root, size=FONTSIZE, weight=tkfont.BOLD)

restart_button = tk.Button(root, text="New Game", command=new_game)
restart_button.pack(side=tk.TOP)

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
new_game()

canvas.bind("<Button-1>", on_click) # left mouse button
canvas.bind("<Button-3>", on_click) # right mouse button

root.mainloop()
 
Share this answer
 
v2
Quote:
I can't figure out how to code for it.I have tried asking

As programmer, your job is not getting a solution all cooked by asking, your job is creating, and you can ask questions to help you figuring out parts of the problem.
Fist step
Collect information about the problem:
- What is the shape of play field, size, how it will translate in program ?
- What are the rules of game ?
- What is a valid move ?
- What is a winner move ?
- Play games to ensure you understand the game and check if your information is correct.
- Write down a scenario of users interaction with the program (See UML graphs).

Note that, as a learner, you get very known problems with a lot of solutions online. Searching/asking for all cooked solutions will defeat the purpose of homework which is practicing the art of creating your own solution.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900