لعبة إكس أو (Tic Tac Toe) بلغة بايثون
في هذا المثال، سنقوم بإنشاء لعبة إكس أو باستخدام لغة البرمجة بايثون ومكتبة Tkinter.
الكود:
import tkinter as tk
from tkinter import messagebox
import random
Function to check if any player has won
def check_win(board, player):
# يتم كتابة الكود هنا
Function to handle button clicks
def handle_click(row, col):
# يتم كتابة الكود هنا
Function for the computer's move
def computer_move():
# يتم كتابة الكود هنا
Function to reset the game
def reset_game():
# يتم كتابة الكود هنا
Create the main window
window = tk.Tk()
window.title("Tic Tac Toe")
Create the game board buttons
buttons = []
for row in range(3):
button_row = []
for col in range(3):
button = tk.Button(window, text=' ', width=10, height=5, command=lambda r=row, c=col: handle_click(r, c))
button.grid(row=row, column=col, padx=5, pady=5)
button_row.append(button)
buttons.append(button_row)
Initialize the game variables
board = [[' ' for _ in range(3)] for _ in range(3)]
player = 'X'
Start the game
window.mainloop()
شرح الكود:
يتكون الكود من مجموعة من الوظائف والأحداث التي تتحكم في سير اللعبة:
- check_win: وظيفة للتحقق مما إذا كان أحد اللاعبين فاز في اللعبة.
- handle_click: وظيفة للتعامل مع نقرة اللاعب على زر اللعبة.
- computer_move: وظيفة لحركة الكمبيوتر في اللعبة.
- reset_game: وظيفة لإعادة تهيئة اللعبة بعد انتهائها.
تم إنشاء النافذة الرئيسية وزر اللعبة باستخدام Tkinter. تم تهيئة المتغيرات اللازمة للعبة وبدء تشغيلها.