Tic Tac Toe (new draft)

I have implemented suggestion and created new draft of the Tic Tac Toe program. Please review and let me know where I can improve.

import random

def update_board():
    """Play game"""
    board = ((3 * row + col for col in range(1, 4)) for row in range(3))

    total_count = 0
    UserTurn = False

    while total_count < 9:
        available_number = remaining_num(board)
        message = ''
        if total_count == 0 :
            board(1)(1) = 'X'
            UserTurn = True
        elif UserTurn == False :
            #Computer's Turn
            num = random.choice(available_number)
            num_indx = find_index(num, board)
            board(num_indx(0)(0))(num_indx(0)(1)) = 'X'
            UserTurn = True
        elif UserTurn == True :
            #User's Turn
            UserTurn = False
            num = int(input(f'select number {available_number}: '))
            num_indx = find_index(num, board)
            if num_indx:
                board(num_indx(0)(0))(num_indx(0)(1)) = 'O'
            else :
                print('Selected number is invalid!')
        total_count += 1
        message = check(board, message)
        if message:
            draw_board(board)
            print(message)
            break
        elif message == '' and len(available_number) <= 1:
            draw_board(board)
            print('Tie !!')
            break
        draw_board(board)


def find_index(num,board):
    """Find index of the number"""
    num_indx = ((indx1, indx2) for indx1, val1 in enumerate(board)
                for indx2, val2 in enumerate(val1)
                if val2 == num)
    return num_indx

def remaining_num (board):
   """Available number list."""
   avail_num = (board(i)(j) 
                for i in range(len(board)) 
                for j in range(len(board)) 
                if board(i)(j) not in ('X', 'O'))
   return avail_num



def check(board,message):
    """Ckeck for win."""
    if board(0)(0) == board(0)(1) == board(0)(2) == 'X' or 
       board(1)(0) == board(1)(1) == board(1)(2) == 'X' or 
       board(2)(0) == board(2)(1) == board(2)(2) == 'X' or 
       board(0)(0) == board(1)(0) == board(2)(0) == 'X' or 
       board(0)(1) == board(1)(1) == board(2)(1) == 'X' or 
       board(0)(2) == board(1)(2) == board(2)(2) == 'X' or 
       board(0)(0) == board(1)(1) == board(2)(2) == 'X' or 
       board(0)(2) == board(1)(1) == board(2)(0) == 'X' :
                message = 'Computer win !!'
    elif board(0)(0) == board(0)(1) == board(0)(2) == 'O' or 
         board(1)(0) == board(1)(1) == board(1)(2) == 'O' or 
         board(2)(0) == board(2)(1) == board(2)(2) == 'O' or 
         board(0)(0) == board(1)(0) == board(2)(0) == 'O' or 
         board(0)(1) == board(1)(1) == board(2)(1) == 'O' or 
         board(0)(2) == board(1)(2) == board(2)(2) == 'O' or 
         board(0)(0) == board(1)(1) == board(2)(2) == 'O' or 
         board(0)(2) == board(1)(1) == board(2)(0) == 'O' :
                message = 'User win !!'
    return message

def draw_board(board):
    """Draw board"""
    for i in range(3):
        print('+' + '-' * 5 + '+' + '-' * 5 + '+' + '-' * 5 + '+', )
        print('|' + ' ' * 5 + '|' + ' ' * 5 + '|' + ' ' * 5 + '|')
        for j in range(3):
            print('| ' + str(board(i)(j))+ ' ' * 3, end='')
        print('|')
        print('|' + ' ' * 5 + '|' + ' ' * 5 + '|' + ' ' * 5 + '|')
    print('+' + '-' * 5 + '+' + '-' * 5 + '+' + '-' * 5 + '+')



if __name__ == "__main__":
    update_board()

python – Tic Tac Toe program

I have created a simple Tic-Tac-Toe program. Can someone please review it and let me know where I can improve.

Here we can play against computer. Program start by putting ‘X’ at the center that is at the position 5. Then ask user to enter number from available position and then assign ‘O’ on selected position. There are four possible verdicts: the game should continue, or the game ends with a tie, your win, or the computer’s win;

import random

def board():
    "Creating Board dictionary"
    dic_board = {}
    v = 1
    for i in range(3):
        for j in range(3):
            k = str(i) + str(j)
            dic_board(k) = v
            v += 1
    update_board(dic_board)

def draw_board(board):
    """Draw board"""
    for i in range(3):
        print('+' + '-' * 5 + '+' + '-' * 5 + '+' + '-' * 5 + '+', end='')
        print()
        print('|' + ' ' * 5 + '|' + ' ' * 5 + '|' + ' ' * 5 + '|')
        for j in range(3):
            k = str(i) + str(j)
            print('| ' + str(board(k)) + ' ' * 3, end='')
        print('|')
        print('|' + ' ' * 5 + '|' + ' ' * 5 + '|' + ' ' * 5 + '|')
    print('+' + '-' * 5 + '+' + '-' * 5 + '+' + '-' * 5 + '+', end='')
    print()

def update_board(board):
    """the first move belongs to the computer -
    it always puts its first 'X' in the middle of the board that is at 5;"""
    total_moves = 0
    flag = True  #Flag = True for computer's move and False for user's move
    while total_moves < 9 :
        available_num = (v for k, v in board.items() if v not in ('X','O'))
        if flag :
            if total_moves == 0:
                update_moves(board, 'Comp', 5)
                flag = False
                sign = 'X'
                draw_board(board)
            else:
                num = random.choice(available_num)
                update_moves(board, 'Comp', num)
                flag = False
                sign = 'X'
                draw_board(board)
        else:
            try:
                s = str(available_num)
                val = int(input('Select Number '+ s + ': '))
                update_moves(board, 'User', val)
                flag = True
                sign = 'O'
            except:
                print('Invalid Input!!')
                continue
        total_moves += 1

        v = victory(board,sign)

        if v:
            print(v)
            if sign == 'O' :
                draw_board(board)
            break
    else :
        print('Tie !!')
        print('Game Over!!')




def update_moves(board, moves,val):
    "Updating borad as per input"
    key_to_update = (k for k, v in board.items() if v == val)
    if moves == 'Comp':
        board(key_to_update(0)) = 'X'
    elif moves == 'User':
        board(key_to_update(0)) = 'O'
    return board

def victory(board,sign):
    message = ''
    message = row_status(board,sign,message)
    message = column_status(board,sign,message)
    message = digonals_status(board,sign,message)
    return message



def row_status(board,sign,message):
    """checking for Horizontal row"""
    if board('00') == board('01') == board('02') == sign or 
            board('10') == board('11') == board('12') == sign or 
            board('20') == board('21') == board('22') == sign:
        if sign == 'X':
            message = 'computer win !!'
        elif sign == 'O':
            message = 'Your win !!'
    return message

def column_status(board,sign,message):
    """checking for verticle column """
    if board('00') == board('10') == board('20') == sign or 
            board('01') == board('11') == board('21') == sign or 
            board('02') == board('12') == board('22') == sign:
        if sign == 'X':
                message = 'computer win !!'
            elif sign == 'O':
                message = 'Your win !!'
        return message
    
    def digonals_status(board,sign,message):
        """checking for digonals """
        if board('00') == board('11') == board('22') == sign or 
           board('02') == board('11') == board('20') == sign :
            if sign == 'X':
                message = 'computer win !!'
            elif sign == 'O':
                message = 'Your win !!'
        return message

print(board())

tic tac toe – Python: Tic Tac Toe Game

I am here to ask for some more experienced programmers to critique my first project. I wanted to see where I lack and what I can improve on. Thank you for taking time out of your day to help me better my skills as a programmer! I hope I did a good job for being a beginner but I know there is much more to learn!

game_board = ('1','2','3','4','5','6','7','8','9')
original_board = ('1','2','3','4','5','6','7','8','9')

player1 = ''
player2 = ''

isFull = False
game_on = True
winner = False

def display_board(board):
    print(board(0)+'|'+board(1)+'|'+board(2))
    print(board(3)+'|'+board(4)+'|'+board(5))
    print(board(6)+'|'+board(7)+'|'+board(8))

def player_input():
    global player1
    global player2
    while player1 != 'X' or player1 != 'O':
        player1 = input("Which do you want to be? (X or O): ")
        player1 = player1.upper()
        if player1 == 'X':
            print("Player 1 has chosen X.")
            player1 = 'X'
            player2 = 'O'
            break
        elif player1 == 'O':
            print("Player 1 has chosen O.")
            player1 = 'O'
            player2 = 'X'
            break
    return player1


def place_marker(board, player, position):

    board(position-1) = player
    
    return board(position-1)

def win_check(board):
    global player1
    global player2
    global game_on
    global winner

    if board(0) == 'O' and board(1) == 'O' and board(2) == 'O':
        
        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True

    elif board(0) == 'O' and board(4) == 'O' and board(8) == 'O':
        
        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True

    elif board(2) == 'O' and board(4) == 'O' and board(6) == 'O':

        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True

    elif board(0) == 'O' and board(3) == 'O' and board(6) == 'O':

        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True

    elif board(1) == 'O' and board(4) == 'O' and board(7) == 'O':

        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True

    elif board(2) == 'O' and board(5) == 'O' and board(8) == 'O':

        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True

    elif board(3) == 'O' and board(4) == 'O' and board(5) == 'O':

        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True

    elif board(6) == 'O' and board(7) == 'O' and board(8) == 'O':

        if player1 == 'O':
            print("Player 1 (O) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (O) has won!")
            game_on = False
            winner = True
    
    if board(0) == 'X' and board(1) == 'X' and board(2) == 'X':
        
        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

    elif board(0) == 'X' and board(4) == 'X' and board(8) == 'X':
        
        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

    elif board(2) == 'X' and board(4) == 'X' and board(6) == 'X':

        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

    elif board(0) == 'X' and board(3) == 'X' and board(6) == 'X':

        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

    elif board(1) == 'X' and board(4) == 'X' and board(7) == 'X':

        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

    elif board(2) == 'X' and board(5) == 'X' and board(8) == 'X':

        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

    elif board(3) == 'X' and board(4) == 'X' and board(5) == 'X':

        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

    elif board(6) == 'X' and board(7) == 'X' and board(8) == 'X':

        if player1 == 'X':
            print("Player 1 (X) has won!")
            game_on = False
            winner = True
        else:
            print("Player 2 (X) has won!")
            game_on = False
            winner = True

def space_check(board, position):
    isTaken = False
    if board(position - 1) == 'X' or board(position - 1) == 'O':
        print("That position is already taken choose again.")
        isTaken = True
    else:
        pass
    return isTaken
        
def full_board_check(board):
    global isFull
    global original_board

    for num in range(9):
        if board(num) == original_board(num):
            return isFull
    else:
        isFull = True
    return isFull

def player_choice(board):
    good = False
    while good == False:
        choice = int(input("Choose a spot: "))
        space_check(board, choice)
        if space_check(board, choice) == False:
            good = True
            return choice
    return choice

def replay():
    global game_board
    global player1
    global player2
    global isFull
    global game_on
    
    keep_playing = True

    while keep_playing == True:
        replay = input("Do you want to replay? (Y or N): ")
        replay = replay.upper()
        if replay == 'Y':
            game_board = ('1','2','3','4','5','6','7','8','9')
            player1 = ''
            player2 = ''
            game_on = True
            isFull = False
        elif replay == 'N':
            keep_playing = False
            print("Thanks for playing!")

print("Welcome to Tic Tac Toe!")
while isFull == False:
    display_board(game_board)
    player_input()
    while game_on:
        
        full_board_check(game_board)
        if isFull == True and winner == False:
            print("The game is a tie!")
            game_on = False
            break
        if game_on:
            print("Player 1's turn.")
            place_marker(game_board, player1, player_choice(game_board))
            display_board(game_board)
            win_check(game_board)

        full_board_check(game_board)
        if isFull == True and winner == False:
            print("The game is a tie!")
            game_on = False
            break
        if game_on:
            print("Player 2's turn.")
            place_marker(game_board, player2, player_choice(game_board))
            display_board(game_board)
            win_check(game_board)
            
    break

python – A beginner’s first tic tac toe implementation

I’ve been teaching myself python and decided to make a Tic Tac Toe game for a bit of practice. Any criticisms or pointers are welcome! Thanks.

class TicTacToe:
  """A class for playing tic tac toe"""

  def __init__(self):
    self.values = ("-", "-", "-", 
                  "-", "-", "-", 
                  "-", "-", "-")
    self.player = "x"


  def show_board(self):
    print(f"{self.values(0)} | {self.values(1)} | {self.values(2)}")
    print(f"{self.values(3)} | {self.values(4)} | {self.values(5)}")
    print(f"{self.values(6)} | {self.values(7)} | {self.values(8)}")


  def play_game(self):
    # display initial board
    self.show_board()
    # play for 9 turns max
    for i in range(9):
      self.handle_turn(self.values)
      if self.check_tie() or self.winner():
        break


  def handle_turn(self, values):
    # get next move from a player
    try:
      turn = int(input(f"Player {self.player} pick a square (1-9) from left to right: "))
    except ValueError:
      self.handle_turn(self.values)
      return
    
    # change values to show the move made (check square empty)
    if self.values(turn-1) == "x" or self.values(turn-1) == "o":
      print("That square has been played already!")
      self.handle_turn(self.values)
    else:
      self.values(turn-1) = self.player
      self.show_board()
    # switch turns
    self.flip_player()


  def winner(self):
    # check all possible win methods
    self.row_winner = self.check_rows()
    self.column_winner = self.check_columns()
    self.diagonal_winner = self.check_diagonals()
    #declare a winner
    if self.row_winner:
      winner = self.check_rows()
      print(f"{winner} has won the game!")
      return True
    elif self.column_winner:
      winner = self.check_columns()
      print(f"{winner} has won the game!")
      return True
    elif self.diagonal_winner:
      winner = self.check_diagonals()
      print(f"{winner} has won the game!")
      return True


  def check_rows(self):
    # Check for a win in the rows
    row1 = self.values(0) == self.values(1) == self.values(2) != "-"
    row2 = self.values(3) == self.values(4) == self.values(5) != "-"
    row3 = self.values(6) == self.values(7) == self.values(8) != "-"
    # Return the player that has won
    if row1:
      return self.values(0)
    elif row2:
      return self.values(3)
    elif row3:
      return self.values(6)  
  

  def check_columns(self):
    # Check for a win in the columns
    col1 = self.values(0) == self.values(3) == self.values(6) != "-"
    col2 = self.values(1) == self.values(4) == self.values(7) != "-"
    col3 = self.values(2) == self.values(5) == self.values(8) != "-"
    # Return the winning player
    if col1:
      return self.values(0)
    elif col2:
      return self.values(1)
    elif col3:
      return self.values(2)


  def check_diagonals(self):
    # Check for win in the diagonals
    dia1 = self.values(0) == self.values(4) == self.values(8) != "-"
    dia2 = self.values(2) == self.values(4) == self.values(6) != "-"
    # Return the player that has won
    if dia1:
      return self.values(0)
    elif dia2:
      return self.values(2)


  def check_tie(self):
    if "-" not in self.values:
      print("Game is a tie!")
      return True
    else:
      return False


  def flip_player(self):
    if self.player == "x":
      self.player = "o"
    else:
      self.player = "x"

if __name__ == "__main__":
  new_board = TicTacToe()
  new_board.play_game()
```

beginner – Tic Tac Toe in Python 3.x

beginner – Tic Tac Toe in Python 3.x – Code Review Stack Exchange

Tic Tac Toe (Haskell)

I implemented tic-tac-toe in Haskell. I’m trying to incorporate suggestions from my last question (which mostly revolved around algorithmic logic) while trying something new – IO logic.

What kind of improvements could I make to this program? Am I being too tricky anywhere? Are there some built-in library functions that I could use to simplify the logic?

Model.hs

module Model (doTurn, getWinner, initialState, isVacant, State(..), Board, Player(..), Winner(..)) where
import Data.List (transpose)
import Safe (atMay)
import Data.Maybe (isJust, isNothing, catMaybes)
import Control.Monad (join)

data Player = X | O deriving (Eq)

data Winner = XWins | OWins | CatScratch

type Board = ((Maybe Player))

data State = State
  {
    boardState :: Board,
    turnState :: Player
  }

opponentOf :: Player -> Player
opponentOf X = O
opponentOf O = X

diagonal :: ((a)) -> (a)
diagonal board =
  catMaybes $ zipWith atMay board (0..)

replaceAt :: (a -> a) -> Int -> (a) -> (a)
replaceAt updateFn index array =
  case splitAt index array of
    (left, val:right) -> left ++ (updateFn val) ++ right
    _ -> array

isVacant :: (Int, Int) -> Board -> Bool
isVacant (x, y) board =
  isNothing $ join $ (`atMay` x) =<< (`atMay` y) board

placeInBoard :: (Int, Int) -> Maybe Player -> Board -> Board
placeInBoard (x, y) =
  (`replaceAt` y) . (`replaceAt` x) . const

isPlayerWinner :: Player -> Board -> Bool
isPlayerWinner player board =
  (any . all) (Just player ==) $
    board ++
    transpose board ++
    map diagonal (board, transpose board)

isCatScratch :: Board -> Bool
isCatScratch =
  (all . all) isJust

getWinner :: Board -> Maybe Winner
getWinner board
  | isPlayerWinner X board = Just XWins
  | isPlayerWinner O board = Just OWins
  | isCatScratch board = Just CatScratch
  | otherwise = Nothing

doTurn :: State -> (Int, Int) -> State
doTurn state coord =
  State {
    boardState = placeInBoard coord (Just $ turnState state) (boardState state),
    turnState = opponentOf (turnState state)
  }

initialState :: Player -> State
initialState firstPlayer =
  State {
    boardState = replicate 3 (replicate 3 Nothing),
    turnState = firstPlayer
  }

View.hs

module View (renderBoard, currentPlayerText, parseAsCoord, winnerText) where
import Data.List (intercalate, intersperse)
import Data.Char (toUpper)
import Model (Board, Player(X, O), Winner(XWins, OWins, CatScratch))

surround :: a -> (a) -> (a)
surround value array = (value) ++ intersperse value array ++ (value)

renderCell :: Maybe Player -> String
renderCell (Just X) = "X"
renderCell (Just O) = "O"
renderCell Nothing = " "

renderBoard :: Board -> String
renderBoard =
  let
    header  = "   A     B     C  "
    divider = " -----+-----+-----"
    padding = "      |     |     "
    renderRow :: Int -> (Maybe Player) -> String
    renderRow n = intercalate "" . (++) (show n) . surround "  " . intersperse "|" . map renderCell
  in
    unlines . (++) (header) . surround padding . intersperse divider . zipWith renderRow (1..)

parseAsCoord :: String -> Maybe (Int, Int)
parseAsCoord (number, letter) =
  let
    maybeX = case toUpper letter of { 'A' -> Just 0; 'B' -> Just 1; 'C' -> Just 2; _ -> Nothing }
    maybeY = case number of { '1' -> Just 0; '2' -> Just 1; '3' -> Just 2; _ -> Nothing }
  in case (maybeX, maybeY) of
    (Just x, Just y) -> Just (x, y)
    _ -> Nothing
parseAsCoord _ = Nothing

currentPlayerText :: Player -> String
currentPlayerText X = "It's X's turn"
currentPlayerText O = "It's O's turn"

winnerText :: Winner -> String
winnerText XWins = "X Wins!"
winnerText OWins = "O Wins!"
winnerText CatScratch = "Cat Scratch!"

Main.hs

import System.IO (hFlush, stdout)
import System.Random (randomIO)
import Model (initialState, doTurn, getWinner, isVacant, Player(X, O), State(boardState, turnState))
import View (renderBoard, currentPlayerText, parseAsCoord, winnerText)

prompt :: String -> IO String
prompt msg = do
  putStr msg >> hFlush stdout
  getLine

promptForVacantCoord :: State -> IO (Int, Int)
promptForVacantCoord state = do
  userInput <- prompt "Pick a spot (e.g. 2B): "
  case parseAsCoord userInput of
    Just coord | isVacant coord (boardState state) -> return coord
    _ -> putStrLn "Invalid input" >> promptForVacantCoord state

step :: State -> IO ()
step state = do
  putStrLn ""
  putStrLn $ renderBoard $ boardState state
  case getWinner (boardState state) of
    Just winner -> putStrLn (winnerText winner)
    Nothing -> do
      putStrLn $ currentPlayerText (turnState state)
      coord <- promptForVacantCoord state
      step $ doTurn state coord

main :: IO ()
main =
  let
    playerFromBool True = X
    playerFromBool False = O
  in
    step . initialState . playerFromBool =<< randomIO

beginner – Text-based Tic Tac Toe in Python (First Project)

I’ve recently started learning Python again after a long time away from it and doing MATLAB at university. Today, I spent some time working on a first little project of mine. Right now it works as it should minus ending the game when all the fields are full. I would love to get advice on how I could improve the code and would like to fix any bad habits early on in learning.

    mapA = ((" ", "|", " ", "|", " "),
            (" ", "|", " ", "|", " "),
            (" ", "|", " ", "|", " "))

    def printMap():
        # prints out the map
        map = ("".join(mapA(0)),
               "".join(mapA(1)),
               "".join(mapA(2)))
        print(map(0))
        print(map(1))
        print(map(2))

        # makes a list of just the fields with x and o
        mapB = (map(0).split("|"),
                map(1).split("|"),
                map(2).split("|"))

        for x in range(3): # converts the board to numbers
            for y in range(3):
                if mapB(x)(y) == "X":
                    mapB(x)(y) = 1
                elif mapB(x)(y) == "O":
                    mapB(x)(y) = -1
                elif mapB(x)(y) == " ":
                    mapB(x)(y) = 0

        for x in range(3):
            if abs(sum(mapB(x))) == 3: # checks for full rows
                return "END"
            elif abs(int(mapB(0)(x)) + int(mapB(1)(x)) + int(mapB(2)(x))) == 3: # checks for full columns
                return "END"
        if abs(int(mapB(0)(0)) + int(mapB(1)(1)) + int(mapB(2)(2))) == 3: # checks for full right diagonal
            return "END"
        elif abs(int(mapB(0)(2)) + int(mapB(1)(1)) + int(mapB(2)(0))) == 3: # checks for full left diagonal
            return "END"
        counter = 0


    def choice(): # allows the user to choose O or X
        print("O or X?")
        symbol = input().lower() # case insensitive
        if symbol == "o":
            return ("O", "X")
        elif symbol == "x":
            return ("X", "O")
        else:
            print("Invalid symbol")
            return choice() # restarts the function if the user input neither O nor X

    def placement(symbol):
        print("Place " + symbol + " in form: rowNumber columnNumber")
        x = input()
        coordinates = x.split(" ")
        while len(coordinates) != 2 or coordinates(0).isnumeric() != True or coordinates(1).isnumeric() != True:
            print("Invalid input.")
            print("Place " + symbol + " in form: rowNumber columnNumber")
            x = input()
            coordinates = x.split(" ")
        while mapA(int(coordinates(0)) - 1)(int(coordinates(1)) * 2 - 2) != " ":
            if mapA(int(coordinates(0)) - 1)(int(coordinates(1)) * 2 - 2) != " ":
                print("That space is taken.")
            else:
                print("Invalid input.")

            print("Place " + symbol + " in form: rowNumber columnNumber")
            x = input()
            coordinates = x.split(" ")

        if coordinates(0) == "1" and coordinates(1) == "1":
            mapA(0)(0) = symbol
        elif coordinates(0) == "1" and coordinates(1) == "2":
            mapA(0)(2) = symbol
        elif coordinates(0) == "1" and coordinates(1) == "3":
            mapA(0)(4) = symbol
        elif coordinates(0) == "2" and coordinates(1) == "1":
            mapA(1)(0) = symbol
        elif coordinates(0) == "2" and coordinates(1) == "2":
            mapA(1)(2) = symbol
        elif coordinates(0) == "2" and coordinates(1) == "3":
            mapA(1)(4) = symbol
        elif coordinates(0) == "3" and coordinates(1) == "1":
            mapA(2)(0) = symbol
        elif coordinates(0) == "3" and coordinates(1) == "2":
            mapA(2)(2) = symbol
        elif coordinates(0) == "3" and coordinates(1) == "3":
            mapA(2)(4) = symbol
        return printMap()

    symbol = choice()
    printMap()
    end = ""

    while end != "END":

        end = placement(symbol(0))

        if end == "END":
            print("Game Finished")
            break
        end = placement(symbol(1))
        if end == "END":
            print("Game Finished")
            break


tictac()

My First Tic Tac Toe

I made this game and it seems to works except the part that checks if all cells are filled. I just don’t know how to write it. Also I know that this game can be written much better but due to lack of experience I don’t know any better way to code this game

def start_game(table, i):
    cor = int(input('Type coordinates'))
    insert(cor, table, i)
    i += 1
    if not is_game_finished(table):
    start_game(table, i)
    else:
        draw_table(table)
        print('Game Over!')


def x_or_o(i):
    if i % 2 == 0:
        print('Player Х')
        return 'X'
    else:
        print('Player О')
        return 'O'


def is_game_finished(tb):
    # Checks rows
    for row in tb:
        if len(set(row)) == 1:
            print('Check Row')
            return True

# Checks cols
for i in range(3):
    col = ()
    for j in range(3):
        col.append(tb(j)(i))
    if col.count('X') == 3 or col.count('O') == 3:
        return True

# Check diagonals
main_diag = {row(i) for i, row in enumerate(tb)}  # row(i) moves right with each iteration
anti_diag = {row(-i) for i, row in enumerate(tb, start=1)}
if len(main_diag) == 1 or len(anti_diag) == 1:
    return True

# Checks if all cells are filled


def draw_table(tb):
    print ('     '+str(1)+' '+str(2) + ' ' + str(3))
    for i in range(len(tb)):
        for j in range(len(tb(0))):
            if j % 3 == 0:
                print('    -------')
                print(str(i+1)+'    ', end='')
            if (j + 1) % 3 == 0:
                print(tb(i)(j))
            else:
                print(tb(i)(j) + '|', end='')


def insert(cor, tb, i):
    if 0 <= cor % 10 - 1 < 3 and 0 <= cor // 10 - 1 < 3:
        item = x_or_o(i)
        tb(int(cor//10)-1)(int(cor % 10)-1) = item
        draw_table(tb)


print("Х begins")
table = ((' ', ' ', '  '),
         (' ', ' ', '  '),
         (' ', ' ', '  '))
i = 0
values = ()
draw_table(table)
start_game(table, i)

tic tac toe – Tic-Tac-Toe game in Java

I had to write a TicTacToe game as an assignment for class & the last program I wrote used a few continues here and there. When I asked for a peer code-review I was informed that I should use additional variables rather than continue and break for my use-case. Did I make the same mistake in this code?

import java.util.HashMap;
import java.util.Scanner;

public class TicTacToe {

    public enum Box { 

        BAD_PLACEMENT(-2),
        X(-1), 
        EMPTY(0), 
        O(1),
        SOLVED(2),
        RESET_GAME(3);
        
        public int value;
        
        @Override
        public String toString() {
            return Integer.toString(value);
        }
        
        public String asString() {
            String rtn;
            switch(value) {
            case -1:
                rtn = "X";
                break;
            case 0:
                rtn = "-";
                break;
            case 1:
                rtn = "O";
                break;
            default:
                rtn = "Something has gone terribly wrong";
            }
            return rtn;
        }
        
        Box(int boxType){
            this.value = boxType;
        }
    }
    
    public static boolean isInteger(String s) {
        try { 
            Integer.parseInt(s); 
        } catch(NumberFormatException e) { 
            return false; 
        } catch(NullPointerException e) {
            return false;
        }
        // only got here if we didn't return false
        return true;
    }
    
    public static class Board {
        
        // The referee will handle computing tictactoe solves
        public class Referee {
            
            Board currentBoard;
            
            public Referee(Board b) {
                this.currentBoard = b;
            }
            
            public Board getBoard() {
                return this.currentBoard;
            }
            
            public Box checkSolveColumns() {
                for (int x=0; x <= 2; x++) {
                    
                    int currentSum = 0;
                    
                    for(int y=0; y <= 2; y++)
                        currentSum+=getBoard().getBox(x, y).value;
                        
                    if(currentSum == 3)
                        return Box.X;
                    if(currentSum == -3)
                        return Box.O;
                }
                return Box.EMPTY;
            }
            
            public Box checkSolveRows() {
                for (int y=0; y <= 2; y++) {
                    
                    int currentSum = 0;
                    
                    for(int x=0; x <= 2; x++)
                        currentSum+=getBoard().getBox(x, y).value;
                    if(currentSum == 3)
                        return Box.X;
                    if(currentSum == -3)
                        return Box.O;
                }
                return Box.EMPTY;
            }
            
            public Box checkSolveDiagonals() {
                
                int topLeftToBottomRightSum = 0;
                int topRightToBottomLeftSum = 0;
                                                                         //  0  1  2 
                topLeftToBottomRightSum+=getBoard().getBox(0, 0).value;// 0 (X)( )( )
                topLeftToBottomRightSum+=getBoard().getBox(1, 1).value;// 1 ( )(X)( )
                topLeftToBottomRightSum+=getBoard().getBox(2, 2).value;// 2 ( )( )(X)
                                                                         //  0  1  2 
                topRightToBottomLeftSum+=getBoard().getBox(2, 0).value;// 0 ( )( )(X)
                topRightToBottomLeftSum+=getBoard().getBox(1, 1).value;// 1 ( )(X)( )
                topRightToBottomLeftSum+=getBoard().getBox(0, 2).value;// 2 (X)( )( )

                if(topLeftToBottomRightSum == 3 || topRightToBottomLeftSum == 3)
                    return Box.X;
                if(topLeftToBottomRightSum == -3 || topRightToBottomLeftSum == -3)
                    return Box.O;
                
                return Box.EMPTY;
            }
            
            public Box checkSolve() {
                
                if(isFull())
                    return Box.SOLVED;
                
                // Observe this is "checked" not "check" > NAMING CONVENTIONS ROCK!!!
                Box checkedSolveRows = checkSolveRows();
                Box checkedSolveColumns = checkSolveColumns();
                Box checkedSolveDiagonals = checkSolveDiagonals();
                
                // return whatever guy won
                if(checkedSolveRows != Box.EMPTY) {
                    return checkedSolveRows;}
                if(checkedSolveColumns != Box.EMPTY) {
                    return checkedSolveColumns;}
                if(checkedSolveDiagonals != Box.EMPTY) {
                    return checkedSolveDiagonals;}
                
                // fall back to an empty return
            return Box.EMPTY;
            }
            
        }
        
        Referee referee;
        
        public Box boardInternal()();
        
        public Board() {
            this.referee = new Referee(this);
            this.boardInternal = new Box(3)(3);
            for(int x=0; x<=2; x++) {
                for(int y=0; y<=2; y++) {
                    this.boardInternal(x)(y) = Box.EMPTY; // initialize every slot with an empty box
                }
            }
            /* Ideally, this is our data structure for the boxes
             * 
             * (EMPTY)(EMPTY)(EMTPY)
             * (EMPTY)(EMPTY)(EMTPY)
             * (EMPTY)(EMPTY)(EMTPY)
             */
        }
        
        public Box getBox(int x, int y) {
            if(x > 2 || y > 2 || x < 0 || y < 0)
                return Box.BAD_PLACEMENT;
            
            return this.boardInternal(x)(y);
        }
        
        public boolean isFull() {
            // neat trick i picked up from lua to check a boolean in a return method
            for(int x=0; x<=2; x++) {
                for(int y=0; y<=2; y++) {
                    if(getBox(x, y)==Box.EMPTY)
                        return false;
                }
            }
            return true;
        }
        
        public void resetGame() {
            // Reset the board c:
            this.referee = new Referee(this);
            this.boardInternal = new Box(3)(3);
            for(int x=0; x<=2; x++) {
                for(int y=0; y<=2; y++) {
                    this.boardInternal(x)(y) = Box.EMPTY; // initialize every slot with an empty box
                }
            }
            System.out.println("*** Game reset ***");
            System.out.println("*** Welcome to TicTacToe! ***");
            System.out.println("*** Type RESET to restart! ***");
            System.out.println("*** Type QUIT to exit! ***");
        }
        
        public Box setBox(int x, int y, Box player) {
            
            if(this.referee.checkSolve() == Box.SOLVED || player==Box.RESET_GAME) { resetGame(); return Box.RESET_GAME;} // board is already solved
            
            Box currentBox = getBox(x, y); // get the current value of the box
            
            Box rtn = null;
            
            switch(currentBox) {
                case EMPTY: // if the box is empty, we fill it with the player requesting the area
                    this.boardInternal(x)(y) = player; // set the field
                    rtn = this.referee.checkSolve();
                    break; // break out of our switch
                case BAD_PLACEMENT:
                    System.out.println("That is a invalid placement option!");
                    rtn = Box.BAD_PLACEMENT;
                    break;
                default: // if the box is not EMPTY, we need to throw a invalid placement exception to notify the caller
                    System.out.println("That box is filled option!");
                    rtn = Box.BAD_PLACEMENT;
            }
        System.out.println(this.toString());
        return rtn;
        }
        
        public String toString() {
            StringBuilder boxResult = new StringBuilder(); // save the memories! (bad save the trees pun)
            
            boxResult.append(String.format("n   1  2  3nA (%s)(%s)(%s)nB (%s)(%s)(%s)nC (%s)(%s)(%s)n",
                    this.boardInternal(0)(0).asString(),
                    this.boardInternal(0)(1).asString(),
                    this.boardInternal(0)(2).asString(),
                    this.boardInternal(1)(0).asString(),
                    this.boardInternal(1)(1).asString(),
                    this.boardInternal(1)(2).asString(),
                    this.boardInternal(2)(0).asString(),
                    this.boardInternal(2)(1).asString(),
                    this.boardInternal(2)(2).asString()
                    ));
            
            return boxResult.toString();
        }
    }
    
    public static void main(String() args) {
        Scanner keyboard = new Scanner(System.in);
        Board ourBoard = new Board();
        
        HashMap<String, Box> Players = new HashMap<String, Box>();
        Players.put("Player1", Box.X);
        Players.put("Player2", Box.O);
        
        String currentPlayer = "Player1";
        
        System.out.println("*** Welcome to TicTacToe! ***");
        System.out.println("*** Type RESET to restart! ***");
        System.out.println("*** Type QUIT to exit! ***");
        System.out.println(ourBoard.toString());
        do {
            System.out.printf("Your move, %s: ",currentPlayer);
            String desiredInput = keyboard.next();
            
            Box inputResult = null;
            
            if(desiredInput.toLowerCase().equals("quit")) // quit the program immediately
                break;
            if(desiredInput.toLowerCase().equals("reset")) // reset the game
                inputResult = ourBoard.setBox(0, 0, Box.RESET_GAME);
            else if(desiredInput != null) {
                // we got an input let's see where we're going with this
                if(desiredInput.length() != 2) {
                    // wrong answer buddy
                    System.out.printf("Hey, %s! Please enter your format in the format of "LetterNumber". ex. A2%n%s is in the wrong format!%n",
                            currentPlayer,
                            desiredInput);
                    continue;
                } else {
                    // this is probably the correct format... let's check
                    char columnPicked = desiredInput.toLowerCase().charAt(0);
                    String rowPicked = desiredInput.split("")(1); // get the 2 characters input
                    
                    if(isInteger(rowPicked)) {
                        int decidedRow = Integer.parseInt(rowPicked);
                        decidedRow--;
                        switch(columnPicked) {
                        case 'a':
                            inputResult = ourBoard.setBox(0, decidedRow, Players.get(currentPlayer));
                            break;
                        case 'b':
                            inputResult = ourBoard.setBox(1, decidedRow, Players.get(currentPlayer));
                            break;
                        case 'c':
                            inputResult = ourBoard.setBox(2, decidedRow, Players.get(currentPlayer));
                            break;
                        default:
                            System.out.println("Could not decipher your column (A,B,C allowed.)");
                            continue;
                        }
                    } else {
                        System.out.println("Could not decipher your row (Only numbers allowed)");
                        continue;
                    }
                    
                }
            }
                
            // do a reset check here
            switch(inputResult) {
                case X:
                    System.out.println("Player 2 wins!"); // player2 win
                    currentPlayer = "Player1";
                    ourBoard.resetGame();
                    break;
                case O:
                    System.out.println("Player 1 wins!"); // player1 win
                    currentPlayer = "Player1";
                    ourBoard.resetGame();
                    break;
                case RESET_GAME:
                    System.out.printf("%n%s requested a reset for the previous game. Bad sport!%n", currentPlayer);
                    currentPlayer = "Player1";
                    break;
                case BAD_PLACEMENT:
                    // nothing to really handle here but we should catch every possible outcome
                    break;
                case SOLVED: // this doesn't mean solved, it's a draw
                    System.out.println("Draw game! Better luck next time!");
                    currentPlayer = "Player1";
                    ourBoard.resetGame();
                    break;
                case EMPTY:
                    // give each player a turn
                    if(currentPlayer.equals("Player1"))
                        currentPlayer = "Player2";
                    else
                        currentPlayer = "Player1";
                    break;
                default:
                    System.out.println("Something went wrong!");
                    System.out.println("RESULT: "+inputResult);
            }
            
        } while(true);
        
        keyboard.close();
    }

}
```

Tic Tac Toe Combinations

I am creating a Tic-Tac-Toe game and was wondering how many combinations there are. I am an amateur coder and was going to code all the combinations by hand. Also if I do not do then what am I supposed to do? code in c# (using console)

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive Proxies-free.com New Proxy Lists Every Day Proxies123