होम › Code Lab (Hindi) › Python में Tic-Tac-Toe गेम
Python में Tic-Tac-Toe — दो खिलाड़ियों का गेम, कोड और लॉजिक
ब्राउज़र में Python का दो-खिलाड़ी Tic-Tac-Toe गेम खेलें, कोड कॉपी या डाउनलोड करें, और जीत की जाँच का लॉजिक समझें। · स्तर: Beginner · Read this in English
Python कोड चलाएँ
आउटपुट
लॉजिक कैसे काम करता है (मुफ़्त)
- board 9 cells की list है। index 0 से 8 खिलाड़ी के type किए गए cells 1 से 9 से match होते हैं।
- show_board() list को तीन-तीन की तीन rows में काटकर separators के साथ print करता है।
- find_winner() 8 संभावित lines (3 rows, 3 columns, 2 diagonals) जाँचता है। अगर किसी line के तीनों cells एक जैसे और खाली न हों, तो वही symbol जीतता है।
- while loop अधिकतम 9 moves चलता है। गलत input (1-9 के बाहर, या भरा हुआ cell) पर message आता है और turn खर्च नहीं होता।
- हर सही move के बाद एक conditional expression से player X और O के बीच बदलता है।
- अगर 9 moves में कोई जीता नहीं, तो program draw का message print करता है।
इसमें आप ये concepts सीखेंगे
- list indexing और slicing
- lines के लिए nested tuples
- functions
- counter वाला while loop
- conditional switching
पूरा कोड (plain text)
board = [" "] * 9
def show_board():
for row in range(3):
cells = board[row * 3:row * 3 + 3]
print(" " + " | ".join(cells))
if row < 2:
print("---+---+---")
def find_winner():
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)]
for a, b, c in lines:
if board[a] != " " and board[a] == board[b] == board[c]:
return board[a]
return None
def play():
player = "X"
moves = 0
show_board()
while moves < 9:
choice = input(f"Player {player}, pick a cell (1-9): ")
if not choice.isdigit() or not 1 <= int(choice) <= 9:
print("Enter a number from 1 to 9.")
continue
index = int(choice) - 1
if board[index] != " ":
print("That cell is already taken.")
continue
board[index] = player
moves += 1
show_board()
winner = find_winner()
if winner:
print(f"Player {winner} wins!")
return
player = "O" if player == "X" else "X"
print("It's a draw!")
play()
PyDebug पर अभ्यास करें
खेलने के बाद इन मुफ़्त exercises से इस idea को debugging की आदत बनाएँ: