Kuinka tehdä Tic Tac Toe -peli sisään Python Code esimerkki
⚡ Älykäs yhteenveto
Tic Tac Toe in Python is a beginner-friendly project that recreates the classic two-player grid game. Building it strengthens core skills such as loops, conditionals, lists, functions, and recursion while checking rows, columns, and diagonals for a winner.

Tic Tac Toe peli sisään Python is an interesting project you can try. It is a cool and fun project of solving a challenge and can help you master basic concepts in Python. Creating a fun Tic Tac Toe game helps you grow your skills.
Voit käyttää hyvää Python toimittaja, kuten PyCharm tai komentorivikäyttöliittymässä.
How to Play the Tic Tac Toe Game?
Tic Tac Toe is a simple two-player game that anyone can play without needing a game board. It involves two players marking different cells until the game ends in a win or a tie.
Here is how to play the Tic Tac Toe game.
Vaihe 1) The Tic Tac Toe game begins with empty cells in a square grid. This is the Tic Tac Toe board.
Vaihe 2) Molemmat pelaajat valitsevat kahdesta symbolista, yleensä Xs tai Os. Voit käyttää mitä tahansa muuta ainutlaatuista symbolia pelissä.
Vaihe 3) The current player marks in turns by filling out the cells of the Tic Tac Toe board until a player fills a winning combination. That is an entire row, column, or diagonal with the same sign.
Vaihe 4) A game tie is also possible in case all cells are full with no apparent winner.
vaatimukset
Building the Tic Tac Toe Python project requires a beginner-level understanding of Python programming language. It includes understanding “for” loops and iterations and what an if statement is used for in Python.
Sinulla on myös oltava Python ja Python text editor installed on your computer to complete the Tic Tac Toe Python project. As this is a beginner-level Tic Tac Toe game in Python, you will not need any Python kirjasto.
You may need some debugging skills in order to find solutions to bugs in your code, and you should also have an adequate understanding of the game components.
Tic Tac Toe Python algoritmi
Follow these steps to create a Tic Tac Toe game in Python ohjelmointikieli:
Vaihe 1) Create the board to begin the Tic Tac Toe game.
Vaihe 2) Pyydä käyttäjää päättämään pelilaudan mitat.
Vaihe 3) Valitse satunnaisesti ensimmäinen pelaaja.
Vaihe 4) Tic Tac Toe game starts.
Vaihe 5) Pelaajat pelaavat valitsemalla tyhjän paikan laudalta.
Vaihe 6) Täytä tyhjä valittu kohta pelaajan merkillä.
Vaihe 7) Määritä pelilogiikan avulla, voittaako tai tasapelin pelaaja.
Vaihe 8) Näytä pelilauta jokaisen pelin jälkeen, jos kukaan pelaaja ei voita tai saa tasapeliä toiselle pelaajalle.
Vaihe 9) Näytä tasapeli- tai voittoviesti.
Vaihe 10) End the Tic Tac Toe game with options to start a new game.
Koko Python koodi tic tac toe
# Guru99 # Code developed by Guru99.com # Guru99 tic-tac-toe game #Get input def getInput(prompt, cast=None, condition=None, errorMessage=None): while True: try: val = cast(input(prompt)) assert condition is None or condition(val) return val except: print(errorMessage or "Invalid input.") # Print the game board def printBoard(board): print() for row in board: print(*row) print() # Check if player won using the winning combinations def checkWin(board): # Check rows for row in range(len(board)): for col in range(len(board)-1): if board[row][col] == "_" or board[row][col+1] == "_" or board[row][col] != board[row][col+1]: break else: return True # Check column numbers for col in range(len(board)): for row in range(len(board)-1): if board[row][col] == "_" or board[row+1][col] == "_" or board[row][col] != board[row+1][col]: break else: return True # Check left diagonal for cell in range(len(board)-1): if board[cell][cell] == "_" or board[cell+1][cell+1] == "_" or board[cell][cell] != board[cell+1][cell+1]: break else: return True # Check right diagonal for cell in range(len(board)-1): emptyCell = board[cell][len(board)-cell-1] == "_" or board[cell+1][len(board)-cell-2] == "_" different = board[cell][len(board)-cell-1] != board[cell+1][len(board)-cell-2] if emptyCell or different: break else: return True # No win return False # Play tic tac toe game def play(): # Introduction print("------------\nN-DIMENSIONAL TIC TAC TOE game by guru 99.com \n------------") # Set up variables N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ", cast=int, condition=lambda x: x >= 3, errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com") board = [['_'] * N for _ in range(N)] used = 0 turn = 0 # Play guru99 tic tac toe game in Python using while infinite loop while True: # Print guru99 tic tac toe game board printBoard(board) # Get user pick pick = getInput(prompt=f"Player {turn+1} - Pick location (row, col): ", cast=lambda line: tuple(map(int, line.split(" "))), condition=lambda pair: min(pair) >= 0 and max(pair) < N and board[pair[0]][pair[1]] == "_", errorMessage="Invalid input. Please enter a valid, unoccupied location as an integer pair.") # Populate location board[pick[0]][pick[1]] = "X" if turn == 0 else "O" used += 1 # Check for win #Guru99 tutorial if checkWin(board): printBoard(board) print(f"Game over, Player {turn+1} wins.") break # Check for tie elif used == N*N: printBoard(board) print("Game over. Players have tied the match.") print("Guru99.com tic tac toe game ") break # If no win yet, update next user turn = (turn+1)%2 # Check for rematch playAgain = getInput(prompt="Play Guru99 tic tac toe_Game again? (y/n): ", cast=str, condition=lambda ans: ans.strip("\n").lower() in {"y", "n"}, errorMessage="Invalid input. Please enter 'y' or 'n'.") if playAgain == 'n': # End the game print("\nGuru99 TicTacToe game ended.") return else: # Rematch play() # Main if __name__ == '__main__': play()
Tic Tac Toe Python Code ulostulo
Once you run the source code above, below is the expected output for a 3 X 3 Tic Tac Toe board:
------------ N-DIMENSIONAL TIC TAC TOE game by guru 99.com ------------ Guru99 says>>> Enter N, the dimensions of the board: 3 _ _ _ _ _ _ _ _ _ Player 1 - Pick location (row, col): 1 1 _ _ _ _ X _ _ _ _ Player 2 - Pick location (row, col): 0 1 _ O _ _ X _ _ _ _ Player 1 - Pick location (row, col): 1 2 _ O _ _ X X _ _ _ Player 2 - Pick location (row, col): 0 2 _ O O _ X X _ _ _ Player 1 - Pick location (row, col): 1 0 _ O O X X X _ _ _ Game over, Player 1 wins. Play Guru99 tic tac toe_Game again? (y/n):
Koko Code Erittely
Luominen Tic Tac Toe in Python is simple. Let us dissect the different functions in bits to understand what is going on for each line:
Taulun tulostaminen
The Tic Tac Toe board is the main game display. In Python, a display window is used to show the game board.
Here are the steps that help you to create a board for Tic Tac Toe in Python:
Python koodi Tic Tac Toe
def getInput(prompt, cast=None, condition=None, errorMessage=None): while True: try: val = cast(input(prompt)) assert condition is None or condition(val) return val except: print(errorMessage or "Invalid input.") # Print the board def printBoard(board): print() for row in board: print(*row) print() N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ", cast=int, condition=lambda x: x >= 3, errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com") board = [['_'] * N for _ in range(N)] used = 0 turn = 0 printBoard(board)
Code lähtö:
------------ N-DIMENSIONAL TIC TAC TOE game by guru 99.com ------------ Guru99 says>>> Enter N, the dimensions of the board: 3 _ _ _ _ _ _ _ _ _
Tic Tac Toe Game – voittojärjestely
Tarkistaaksemme, voittiko joku pelaaja, meidän on tarkistettava rivien, sarakkeiden ja diagonaalien voittoyhdistelmät. Jos voittaja löytyy, meidän on näytettävä voittajaviesti.
Rivit
- Rivillä funktio ottaa jokaisen peräkkäisen sarakeparin ja tarkistaa voittavan yhdistelmän.
- Ensimmäinen pelaaja, joka täyttää rivit, voittaa. Toinen pelaaja siis häviää.
- If a pair of consecutive columns are the same, then it is obvious that all elements within that row are the same.
- Jos kaksi niistä ovat erilaisia tai rivillä on tyhjä solu, voittajaa ei silti ole.
- Toteutamme sitten häviämisehdot ja lisäämme tauon. Jos jokin näistä tappioehdoista pitää paikkansa, meillä ei ollut voittajaa valitulla rivillä.
- Muu väite antaa todellisen tuoton osoittaakseen, että voittaja on olemassa.
- Katko katkeaa tästä silmukasta ja jatkaa seuraavalle riville.
Pylväät
Sarakkeille toistamme saman toiminnon kuin riveillä. Tarkistamme, voittiko pelaaja, kun jokainen pelaaja on valinnut paikkansa.
Diagonaalirivi voittaa
For the left diagonal, the task becomes simpler. We are always going to be comparing the cells in the diagonals. However, in case there is no winner, we can proceed to the next instruction.
Pelin logiikka
Tämä on pelin päätoiminto. Tätä varten voimme käyttää muuttujia, jotka tallentavat tietoa.
- Ensimmäinen muuttuja on "N"-kirjaimeen tallennettu levyn koko. Peli saa laudan koon pyydettyään käyttäjää syöttämään numeron.
- Joten kun syötät arvon, se käsitellään.
- Luomme myös virheilmoituksen, joka näyttää pelaajille, kun virheellinen numero kirjoitetaan.
- Voimme sitten luoda kaksi muuttujaa, jotka täyttävät "X" tai "O", kun solu on täytetty.
- Näytä sitten pelaajille pelilauta. Tämän jälkeen hanki soittimen syöte.
- Logiikka merkitsee sitten valitun solun täytetyksi ja tarkistaa voiton tai tasapelin.
- Jos voittajaa ei löydy, peli pyytää seuraavaa pelaajaa pelaamaan. Jos voitto tai tasapeli tulee, peli voi kysyä käyttäjiltä, haluavatko he uuden pelin.
