🎮 Build a Game Bot in Python (Tic-Tac-Toe AI)
Let’s build a simple Tic-Tac-Toe game bot using Python logic. This project introduces basic AI with condition-checking and decision-making—perfect for students learning how AI thinks in games.
🧰 What You Need
- Python 3 installed
- No extra libraries required
- Basic knowledge of loops and conditionals
🧠 Game Logic: How It Works
The bot uses simple rules:
- Play in center if available
- Win if possible
- Block opponent if they can win
- Otherwise, play in a random available spot
📝 Step 1: Basic Setup
import random
board = [' ' for _ in range(9)]
def print_board():
for i in range(3):
print("|".join(board[i*3:(i+1)*3]))
if i < 2:
print("-----")
🎮 Step 2: Player Move
def player_move():
move = int(input("Enter your move (0-8): "))
if board[move] == ' ':
board[move] = 'X'
🤖 Step 3: Bot Move (Basic AI)
def bot_move():
# Try to win
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
if check_win('O'):
return
board[i] = ' '
# Block player
for i in range(9):
if board[i] == ' ':
board[i] = 'X'
if check_win('X'):
board[i] = 'O'
return
board[i] = ' '
# Take center
if board[4] == ' ':
board[4] = 'O'
return
# Random move
empty = [i for i in range(9) if board[i] == ' ']
if empty:
board[random.choice(empty)] = 'O'
🏁 Step 4: Win Check
def check_win(player):
wins = [(0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6)]
return any(board[a]==board[b]==board[c]==player for a,b,c in wins)
🚀 Step 5: Game Loop
def play_game():
print("Welcome to Tic-Tac-Toe!")
print_board()
while ' ' in board:
player_move()
print_board()
if check_win('X'):
print("You win!")
return
bot_move()
print_board()
if check_win('O'):
print("Bot wins!")
return
print("It's a draw!")
play_game()
🔍 Sample Output
Welcome to Tic-Tac-Toe!
| |
-----
| |
-----
| |
Enter your move (0-8):
🎓 Challenges for Students
- Improve the bot to use minimax algorithm
- Turn it into a GUI with Tkinter or Pygame
- Make it two-player mode
- Save game history to a file
Find all tutorials at DarchumsTech Blog.
Comments
Post a Comment