0% found this document useful (0 votes)
2 views5 pages

Final Python Code

This document outlines a Python script for a Tic-Tac-Toe game, including functionalities for player vs player (PvP) or player vs computer (PvC) modes. Key components include board initialization, player symbol selection, move validation, and win condition checks. The main game loop orchestrates the gameplay, allowing for resets and replay options while providing colored terminal output for the game board.

Uploaded by

hngd25pvtj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Final Python Code

This document outlines a Python script for a Tic-Tac-Toe game, including functionalities for player vs player (PvP) or player vs computer (PvC) modes. Key components include board initialization, player symbol selection, move validation, and win condition checks. The main game loop orchestrates the gameplay, allowing for resets and replay options while providing colored terminal output for the game board.

Uploaded by

hngd25pvtj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Python code

import random
import time
from typing import List, Union
random — used for random choices (e.g., computer moves or symbol assignment).

time — used to delay computer's move for realism.

List, Union — type hints for clearer code.

2. Color Codes for Output


python code
RED = '\033[91m'
GREEN = '\033[92m'
RESET = '\033[0m'
ANSI escape codes to color 'X' red and 'O' green in terminal output.

3. Global Variables
python code
tablepoints = [i + 1 for i in range(9)]
Initializes board as a list [1,2,...,9].

python code
player1 = player2 = computer = current_player = ""
p1_name = p2_name = mode = ""
Placeholder variables to store player symbols, names, mode (PvP or PvC), and who's playing
now.

python code
winning_options = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
[0, 4, 8], [2, 4, 6] # Diagonals
]
All possible win conditions using board indices.

4. print_board()
python code
def print_board() -> None:
"""Prints the current game board with colors."""
for i in range(3):
row = ""
for j in range(3):
mark = tablepoints[i * 3 + j]
if mark == 'X':
row += RED + 'X' + RESET
elif mark == 'O':
row += GREEN + 'O' + RESET
else:
row += str(mark)
if j < 2:
row += " | "
print(row)
if i < 2:
print("--+---+--")
Displays the board in 3x3 format, coloring X and O appropriately.

5. select_mode()
python code
def select_mode() -> None:
...
Lets user choose between playing against a friend (PvP) or the computer (PvC).

6. choose_symbols()
python code
def choose_symbols() -> None:
...
First player chooses 'X', 'O', or 'R' (random).

Symbols are assigned to both players or player + computer.

Also sets current_player.

7. player_move()
python code
def player_move() -> None:
...
Prompts current player to pick a spot (1–9).

Validates move (e.g., not already taken).

Updates tablepoints.

8. computer_move()
python code
def computer_move() -> None:
...
Simple AI:

Try to win.

Try to block opponent.

Choose randomly.

9. get_available_moves()
python code
def get_available_moves() -> List[int]:
return [i for i in range(9) if tablepoints[i] not in ['X', 'O']]
Returns list of unoccupied cell indices.

10. check_winner(mark)
python code
def check_winner(mark: str) -> bool:
return any(all(tablepoints[i] == mark for i in option) for option in winning_options)
Checks if the given mark ('X' or 'O') forms a winning pattern.

11. switch_player()
python code
def switch_player() -> None:
global current_player
current_player = player2 if current_player == player1 else player1
Switches turn between player1 and player2.

12. get_current_player_name()
python code
def get_current_player_name() -> str:
...
Returns the name of the current player (or "Computer").

13. reset_board()
python code
def reset_board() -> None:
global tablepoints
tablepoints = [i + 1 for i in range(9)]
Resets the board for a new round.

14. play_again()
python code
def play_again() -> bool:
choice = input("Play again? (y/n): ").strip().lower()
return choice == 'y'
Asks if user wants to replay.

15. main_game()
python code
def main_game() -> None:
select_mode()
choose_symbols()

while True:
reset_board()
print_board()

while True:
if mode == "pvc" and current_player == computer:
print("\nComputer is thinking...")
time.sleep(1)
computer_move()
else:
player_move()

print_board()

if check_winner(current_player):
print(f"\n{get_current_player_name()} wins!\n")
break

if not get_available_moves():
print("\nIt's a draw!\n")
break

switch_player()

if not play_again():
print("\nThanks for playing!")
break
Orchestrates the entire game:

Setup

Loop through moves

Check for win/draw


Optionally repeat

16. Script Entry Point


python code
if __name__ == "__main__":
main_game()
Ensures main_game() runs only when script is executed directly.

You might also like