Untitled
unknown
python
a year ago
2.8 kB
11
Indexable
➜ ~ ollama run codegemma
>>> Write tic-tac-toe for linux console. You can use curses
```python
import curses
import time
# Initialize the screen
stdscr = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
# Define the game board
board = [" "] * 9
# Define the player symbols
player1 = "X"
player2 = "O"
# Define the current player
current_player = player1
# Function to draw the game board
def draw_board():
stdscr.clear()
stdscr.addstr(0, 0, "Tic-Tac-Toe")
stdscr.addstr(2, 0, f"Player 1 ({player1}): ")
stdscr.addstr(3, 0, f"Player 2 ({player2}): ")
stdscr.addstr(5, 0, " | | ")
stdscr.addstr(6, 0, " | | ")
stdscr.addstr(7, 0, " | | ")
for i, square in enumerate(board):
if square == player1:
stdscr.addstr(i // 3 + 5, (i % 3) * 4, player1, curses.color_pair(1))
elif square == player2:
stdscr.addstr(i // 3 + 5, (i % 3) * 4, player2, curses.color_pair(2))
# Function to get the player's move
def get_move():
while True:
stdscr.addstr(10, 0, "Enter a number between 1 and 9:")
stdscr.refresh()
move = stdscr.getch()
try:
move = int(move)
if move >= 1 and move <= 9 and board[move - 1] == " ":
return move - 1
else:
stdscr.addstr(12, 0, "Invalid move. Try again.")
except ValueError:
stdscr.addstr(12, 0, "Invalid input. Try again.")
# Function to check if there is a winner
def check_winner():
for i in range(0, 9, 3):
if board[i] == board[i + 1] == board[i + 2] != " ":
return board[i]
for i in range(3):
if board[i] == board[i + 3] == board[i + 6] != " ":
return board[i]
if board[0] == board[4] == board[8] != " ":
return board[0]
if board[2] == board[4] == board[6] != " ":
return board[2]
return None
# Game loop
while True:
draw_board()
stdscr.refresh()
# Get the player's move
move = get_move()
# Update the game board
board[move] = current_player
# Check for a winner
winner = check_winner()
if winner:
stdscr.clear()
stdscr.addstr(0, 0, f"Player {winner} wins!")
stdscr.refresh()
time.sleep(3)
break
# Switch the current player
current_player = player2 if current_player == player1 else player1
# End the game
curses.endwin()
```
**Instructions:**
* Run the script in a Linux terminal.
* Use the arrow keys to navigate the game board.
* Enter a number between 1 and 9 to make your move.
* The game ends when there is a winner or all squares are filled.
>>>
Use Ctrl + d or /bye to exit.
>>> Send a message (/? for help)
Editor is loading...
Leave a Comment