実際に動くコードでタイピング練習をしたいなと思い、

AI対戦マルバツゲームのコードをAIに作ってもらいました。

タイピングはこちらから。慣れていれば5分くらいで打ち込めると思います。

リストはこちら。

import sys, random
def p(b):
  for i in (0,3,6):
    r=[b[i+j] if b[i+j]!=" " \
      else "." for j in (0,1,2)]
    print(" | ".join(r))
    if i<6: print("-" * 9)
def main():
  b=[" "]*9
  t="O"
  w=[(0,1,2),(3,4,5),(6,7,8),
     (0,3,6),(1,4,7),(2,5,8),
     (0,4,8),(2,4,6)]
  for i in range(9):
    p(b)
    try:
      if t=="X":
        v=None
        for k in ("X","O"):
          for a,c,d in w:
            L=[b[a],b[c],b[d]]
            if L.count(k)==2 \
               and " " in L:
              ix=L.index(" ")
              v=[a,c,d][ix]
              break
          if v!=None:break
        if v==None:
          e=[j for j in \
            range(9) if \
            b[j]==" "]
          v=random.choice(e)
        print(f"CPU(X): {v+1}")
      else:
        print("123/456/789(q:Quit)")
        u=input(f"{t}:")
        if u=="q":return
        v=int(u)-1
      if b[v]!=" ":continue
    except:continue
    b[v]=t
    if any(b[a]==b[c]==b[d]==t \
      for a,c,d in w):
      p(b);print(f"Win:{t}!");return
    t="X" if t=="O" else "O"
  p(b);print("Draw!")
if __name__ == "__main__":
  main()
Code language: Python (python)

実際に動かすと、下のように3×3のマスが表示されるで、Oを置きたい箇所の数値(1~9)を入力します。

. | . | .
---------
. | . | .
---------
. | . | .
123/456/789(q:Quit)
O:Code language: Python (python)

1を入れるとCPUが5にXを置きました。こんな感じで続けていきます。

CPU(X): 5
O | . | .
---------
. | X | .
---------
. | . | .
123/456/789(q:Quit)
O:Code language: Python (python)

おっと油断していたら負けました(笑)。

CPU(X): 3
O | O | X
---------
O | X | .
---------
X | . | .
Win:X!Code language: Python (python)

変数名を分かりやすくして日本語のコメントを入れて可読性を良くしたコードも記載します。

import sys
import random

def print_board(board):
    """盤面をコンソールに表示する"""
    for i in range(0, 9, 3):
        # 空いているマスはドット(.)を表示する
        row = [board[i+j] if board[i+j] != " " else "." for j in range(3)]
        print(f" {row[0]} | {row[1]} | {row[2]} ")
        if i < 6:
            print("--- + --- + ---")

def get_cpu_move(board, cpu_symbol, player_symbol):
    """CPUの次の一手を決定する(賢いロジック)"""
    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)]
    
    # 1. 自分が勝てる手があるか確認
    for a, b, c in wins:
        line = [board[a], board[b], board[c]]
        if line.count(cpu_symbol) == 2 and line.count(" ") == 1:
            return [a, b, c][line.index(" ")]
            
    # 2. 相手が勝ちそうなら阻止する
    for a, b, c in wins:
        line = [board[a], board[b], board[c]]
        if line.count(player_symbol) == 2 and line.count(" ") == 1:
            return [a, b, c][line.index(" ")]
            
    # 3. それ以外はランダムに選択
    empty_indices = [i for i, val in enumerate(board) if val == " "]
    return random.choice(empty_indices)

def main():
    board = [" "] * 9      # 3x3の盤面(空白で初期化)
    player_symbol = "O"    # プレイヤーは先手「O」
    cpu_symbol = "X"       # CPUは後手「X」
    turn = player_symbol
    
    # 勝利条件のパターン
    win_patterns = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8), # 横
        (0, 3, 6), (1, 4, 7), (2, 5, 8), # 縦
        (0, 4, 8), (2, 4, 6)             # 斜め
    ]
    
    print("--- マルバツゲーム (CPU対戦版) ---")
    
    for i in range(9):
        print_board(board)
        
        if turn == cpu_symbol:
            # CPUの番
            move_index = get_cpu_move(board, cpu_symbol, player_symbol)
            print(f"CPUの番です。 {move_index + 1} に置きました。")
        else:
            # プレイヤーの番
            print("\n入力ガイド: 1 2 3 / 4 5 6 / 7 8 9 (qで終了)")
            user_input = input(f"あなたの番 ({player_symbol}) [1-9]: ").lower()
            
            if user_input == 'q':
                print("ゲームを終了します。")
                return
            
            try:
                # ユーザー入力をインデックス(0-8)に変換
                move_index = int(user_input) - 1
                if not (0 <= move_index <= 8) or board[move_index] != " ":
                    print("そこには置けません。もう一度入力してください。")
                    continue
            except ValueError:
                print("1から9の数字、または q を入力してください。")
                continue
        
        # 盤面に記号を配置
        board[move_index] = turn
        
        # 勝利判定
        if any(board[a] == board[b] == board[c] == turn for a, b, c in win_patterns):
            print_board(board)
            if turn == player_symbol:
                print("おめでとうございます!あなたの勝ちです!")
            else:
                print("CPUの勝ちです。次は頑張りましょう!")
            return
            
        # ターン交代
        turn = cpu_symbol if turn == player_symbol else player_symbol
        
    print_board(board)
    print("引き分けです!")

if __name__ == "__main__":
    main()
Code language: Python (python)