بتل کد Battle Codeدارد باز می‌شود…

Step 4: Minimax and Three Levels چالش 4 از جلسه‌ی 16، سخت

کامپیوتر شکست‌ناپذیر و سه سطح سختی:
۱. level = 3 را بالای برنامه بگذار.
۲. minimax(turn): مثل جلسه‌ی ۱۵ روی همان board (O برد 1، X برد -1، مساوی 0؛ نوبت O بیشترین، نوبت X کمترین). میان‌بُر برای سرعت: اگر نوبت O است و یک حرکت امتیاز 1 داد، همان‌جا 1 را برگردان؛ اگر نوبت X است و -1 پیدا شد، -1 را.
۳. best_move(): برای هر خانه‌ی خالی O بگذار، minimax("X") را حساب کن، خالی کن و خانه‌ای با بیشترین امتیاز را برگردان.
۴. computer_move(): سطح 1 تصادفی، سطح 3 با best_move()، سطح 2 همان «یک حرکت جلوتر».
۵. on_key_down(key): کلیدهای 1، 2، 3 سطح را عوض کنند، صفحه را خالی کنند و پیام Level 2: your turn (با عدد سطح) بنویسند.

import pgzrun
import random

WIDTH = 300
HEIGHT = 360
TITLE = "Unbeatable"

board = [" "] * 9
message = "Your turn: click a square"

LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8),
         (0, 3, 6), (1, 4, 7), (2, 5, 8),
         (0, 4, 8), (2, 4, 6)]

def winner(board):
    for a, b, c in LINES:
        if board[a] != " " and board[a] == board[b] == board[c]:
            return board[a]
    return None

def draw():
    screen.fill("white")
    for k in range(1, 3):
        screen.draw.line((k * 100, 0), (k * 100, 300), "black")
        screen.draw.line((0, k * 100), (300, k * 100), "black")
    for i in range(9):
        x = (i % 3) * 100 + 50
        y = (i // 3) * 100 + 50
        if board[i] == "X":
            screen.draw.text("X", center=(x, y), fontsize=80, color="blue")
        if board[i] == "O":
            screen.draw.text("O", center=(x, y), fontsize=80, color="red")
    screen.draw.text(message, center=(150, 330), fontsize=24, color="black")

def empty_squares():
    result = []
    for i in range(9):
        if board[i] == " ":
            result.append(i)
    return result

def winning_move(p):
    for i in empty_squares():
        board[i] = p
        w = winner(board)
        board[i] = " "
        if w == p:
            return i
    return None

def computer_move():
    move = winning_move("O")
    if move == None:
        move = winning_move("X")
    if move == None:
        move = random.choice(empty_squares())
    return move

def game_over():
    global message
    w = winner(board)
    if w == "X":
        message = "You win!"
    elif w == "O":
        message = "Computer wins!"
    elif len(empty_squares()) == 0:
        message = "Draw!"
    else:
        return False
    return True

def on_mouse_down(pos):
    col = pos[0] // 100
    row = pos[1] // 100
    if row > 2 or winner(board) != None:
        return
    i = row * 3 + col
    if board[i] == " ":
        board[i] = "X"
        if game_over():
            return
        board[computer_move()] = "O"
        game_over()

pgzrun.go()

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 16: پروژه: دوز شکست‌ناپذیر

بیشتر بخوان: بازی‌سازی با پایتون و Pygame Zero