Python Tic-Tac-Toe 게임 스크립트
Python에서 터미널 Tic-Tac-Toe 게임을 실행합니다. 보드 상태 관리, 턴 전환, 승리 조건 확인에 대해 알아보세요.
개요
Tic-Tac-Toe 게임을 구축하는 것은 매트릭스 보드 상태 표현, 루프 구조 및 조건부 비교 논리를 강화하는 고전적인 연습입니다.
보드는 3x3 매트릭스(또는 9개 요소의 단순 목록)로 표시됩니다. 두 명의 플레이어가 교대로 자신의 기호('X' 또는 'O')를 그리드에 배치합니다. 각 이동 후 스크립트는 플레이어의 행, 열 또는 대각선에 일치하는 기호 3개가 있는지 확인합니다.
이 구현에는 활성 플레이어 상태를 전환하고, 좌표 배치를 수락하고, 승리 또는 무승부 조건이 발생하면 자동으로 중지되는 게임 루프가 포함되어 있습니다.
코드 및 실행 출력
시뮬레이션된 세션을 실행하는 완전한 기능을 갖춘 명령줄 Tic-Tac-Toe 게임 엔진입니다.
tic_tac_toe.py
에디터에서 사용해 보세요def print_board(board):
for i in range(3):
row = " | ".join(board[i*3:(i+1)*3])
print(f" {row} ")
if i < 2:
print("---+---+---")
def check_win(board, player):
win_states = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
[0, 4, 8], [2, 4, 6] # Diagonals
]
return any(all(board[pos] == player for pos in state) for state in win_states)
def play_tic_tac_toe():
board = [str(i+1) for i in range(9)]
# Simulated sequence of moves (X and O alternating)
moves = [4, 0, 8, 2, 7, 6, 3]
print("Welcome to Tic-Tac-Toe!\n")
print_board(board)
print("\nSimulating Gameplay...")
current_player = 'X'
for move in moves:
if board[move] not in ['X', 'O']:
board[move] = current_player
print(f"\nPlayer {current_player} places on {move+1}:")
print_board(board)
if check_win(board, current_player):
print(f"\nPlayer {current_player} wins the game!")
return
current_player = 'O' if current_player == 'X' else 'X'
print("\nGame ends in a draw!")
play_tic_tac_toe()터미널 출력
Welcome to Tic-Tac-Toe!
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Simulating Gameplay...
Player X places on 5:
1 | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
Player O places on 1:
O | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
... (moves continue)
Player X wins the game!단계별 구현
- 대화형 명령줄 인터페이스 루프
- 간단한 인공지능 미니맥스 라우팅 프로토타입
- 2D 목록 배열 좌표 매핑 학습
자주 묻는 질문
컴퓨터와 어떻게 대결할 수 있나요?
AI 상대를 구현하려면 Python의 'random' 모듈을 사용하여 보드에서 여유 슬롯을 선택하거나 Minimax 알고리즘을 사용하여 무적의 상대를 생성할 수 있습니다.
턴 사이에 터미널 화면을 어떻게 지우나요?
`os`를 가져오고 `os.system('cls' if os.name == 'nt' else 'clear')`를 호출하여 표준 터미널 뷰포트를 지울 수 있습니다.