2 minutes to read - Apr 12, 2023

Code simple games

code me a computer game of tic-tac-toe in python

Sure! Here's a simple implementation of tic-tac-toe in Python:

Copy code

`board = [[" " for _ in range(3)] for _ in range(3)] def draw_board(): print(" 0 1 2") for i, row in enumerate(board): print(i, *row) def get_move(player): while True: try: row = int(input(f"{player}, enter row: ")) col = int(input(f"{player}, enter col: ")) if row in [0, 1, 2] and col in [0, 1, 2]: if board[row][col] == " ": board[row][col] = player return else: print("That space is already occupied. Try again.") else: print("Invalid move. Try again.") except ValueError: print("Invalid input. Try again.") def has_won(player): # check rows for row in board: if row == [player, player, player]: return True # check cols for col in range(3): if board[0][col] == player and board[1][col] == player and board[2][col] == player: return True # check diagonals if board[0][0] == player and board[1][1] == player and board[2][2] == player: return True if board[2][0] == player and board[1][1] == player and board[0][2] == player: return True return False def main(): draw_board() while True: get_move("X") draw_board() if has_won("X"): print("X has won!") break get_move("O") draw_board() if has_won("O"): print("O has won!") break main()`

This implementation uses a simple 3x3 grid represented as a list of lists. The `draw_board` function prints the current state of the board to the console, and the `get_move` function prompts the player for a row and column and makes the move on the board if it is a valid move. The `has_won` function checks if the player has won by checking all rows, columns, and diagonals for a win. The `main` function runs the game loop, alternating between players and checking for a win after each move.

loading...