산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python으로 Tic Tac Toe 게임 만들기:단계별 코드 튜토리얼

Python의 Tic Tac Toe Game은 시도해 볼 수 있는 흥미로운 프로젝트입니다. 도전 과제를 해결하는 멋지고 재미있는 프로젝트이며 Python의 기본 개념을 익히는 데 도움이 될 수 있습니다. 재미있는 틱택토 게임을 만들면 기술을 향상하는 데 도움이 됩니다.

Pycharm이나 명령줄 인터페이스와 같은 좋은 Python 편집기를 사용할 수 있습니다.

Tic Toc 게임을 어떻게 플레이하나요?

틱택토(Tic tac toe) 게임은 게임판이 없어도 누구나 즐길 수 있는 간단한 2인용 게임입니다. 두 명의 플레이어가 게임이 끝날 때까지 서로 다른 셀을 표시하여 승리 또는 무승부가 이루어집니다.

틱택토 게임 방법은 다음과 같습니다.

1단계) tic tac toe 게임은 정사각형 격자의 빈 셀로 시작됩니다. 틱택토 보드입니다.

2단계) 두 플레이어 모두 일반적으로 Xs 또는 Os라는 두 가지 기호 중에서 선택합니다. 게임 내에서 다른 고유 기호를 사용할 수 있습니다.

3단계) 현재 플레이어는 플레이어가 승리 조합을 채울 때까지 틱택토 보드의 셀을 차례로 채워 표시합니다. 이는 동일한 부호를 가진 전체 행, 열 또는 대각선입니다.

4단계) 모든 셀이 꽉 차서 확실한 승자가 없을 경우 무승부도 가능합니다

요구사항

tic tac toe Python 프로젝트를 구축하려면 Python 프로그래밍 언어에 대한 초급 수준의 이해가 필요합니다. 여기에는 "for" 루프와 반복에 대한 이해와 Python에서 if 문이 사용되는 내용이 포함됩니다.

또한 tic-tac-toe Python 프로젝트를 완료하려면 Python과 Python 텍스트 편집기가 컴퓨터에 설치되어 있어야 합니다. 이 게임은 Python을 사용한 초보자 수준의 틱택토 게임이므로 Python 라이브러리가 필요하지 않습니다.

코드의 버그에 대한 해결책을 찾으려면 디버깅 기술이 필요할 수 있으며 게임 구성 요소에 대한 적절한 이해도 있어야 합니다.

Tic Tac Toe Python 알고리즘

Python 프로그래밍 언어로 tic tac toe 게임을 만들려면 다음 단계를 따르세요.

1단계) 틱택토 게임을 시작하려면 보드를 만드세요.

2단계) 사용자에게 게임 보드 크기를 결정하도록 요청하세요.

3단계) 첫 번째 플레이어를 무작위로 선택합니다.

4단계) 틱택토 게임이 시작됩니다.

5단계) 플레이어는 보드의 빈 자리를 선택하여 플레이합니다.

6단계) 선택한 빈 자리를 플레이어의 사인으로 채웁니다.

7단계) 게임 로직을 사용하여 플레이어가 게임에서 승리할지 아니면 무승부를 얻을지 결정합니다.

8단계) 어떤 플레이어도 이기거나 두 번째 플레이어와 동점을 얻지 못한 경우 매 플레이 후에 게임 보드를 표시합니다.

9단계) 각각 무승부 또는 승리 메시지를 표시합니다.

10단계) 새 게임을 시작할 수 있는 옵션으로 틱택토 게임을 종료하세요.

tic tac toe용 전체 Python 코드

# Guru99
# Code developed by Guru99.com
# Guru99 tic-tac-toe game
#Get input
def getInput(prompt, cast=None, condition=None, errorMessage=None):
 while True:
 try:
 val = cast(input(prompt))
 assert condition is None or condition(val)
 return val
 except:
 print(errorMessage or "Invalid input.")
# Print the game board
def printBoard(board):
 print()
 for row in board:
 print(*row)
 print()
# Check if player won using the winning combinations
def checkWin(board):
 # Check rows
 for row in range(len(board)):
 for col in range(len(board)-1):
 if board[row][col] == "_" or board[row][col+1] == "_" or board[row][col] != board[row][col+1]:
 break
 else:
 return True
 # Check column numbers
 for col in range(len(board)):
 for row in range(len(board)-1):
 if board[row][col] == "_" or board[row+1][col] == "_" or board[row][col] != board[row+1][col]:
 break
 else:
 return True
 # Check left diagonal
 for cell in range(len(board)-1):
 if board[cell][cell] == "_" or board[cell+1][cell+1] == "_" or board[cell][cell] != board[cell+1][cell+1]:
 break
 else:
 return True
 # Check right diagonal
 for cell in range(len(board)-1):
 emptyCell = board[cell][len(board)-cell-1] == "_" or board[cell+1][len(board)-cell-2] == "_"
 different = board[cell][len(board)-cell-1] != board[cell+1][len(board)-cell-2]
 if emptyCell or different:
 break
 else:
 return True
 # No win
 return False
# Play tic tac toe game
def play():
 # Introduction
 print("------------\nN-DIMENSIONAL TIC TAC TOE game by guru 99.com \n------------")
 # Set up variables
 N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ",
 cast=int,
 condition=lambda x: x >= 3,
 errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com")
 board = [['_'] * N for _ in range(N)]
 used = 0
 turn = 0
 # Play guru99 tic tac toe game in Python using while infinite loop
 while True:
 # Print guru99 tic tac toe game board
 printBoard(board)
 # Get user pick
 pick = getInput(prompt=f"Player {turn+1} - Pick location (row, col): ",
 cast=lambda line: tuple(map(int, line.split(" "))),
 condition=lambda pair: min(pair) >= 0 and max(pair) < N and board[pair[0]][pair[1]] == "_",
 errorMessage="Invalid input. Please enter a valid, unoccupied location as an integer pair.")
 # Populate location
 board[pick[0]][pick[1]] = "X" if turn == 0 else "O"
 used += 1
 # Check for win
 #Guru99 tutorial
 if checkWin(board):
 printBoard(board)
 print(f"Game over, Player {turn+1} wins.")
 break
 # Check for tie
 elif used == N*N:
 printBoard(board)
 print("Game over. Players have tied the match.")
 print("Guru99.com tic tac toe game ")
 break
 # If no win yet, update next user
 turn = (turn+1)%2
 # Check for rematch
 playAgain = getInput(prompt="Play Guru99 tic tac toe_Game again? (y/n): ",
 cast=str,
 condition=lambda ans: ans.strip("\n").lower() in {"y", "n"},
 errorMessage="Invalid input. Please enter 'y' or 'n'.")
 if playAgain == 'n':
 # End the game
 print("\nGuru99 TicTacToe game ended.")
 return
 else:
 # Rematch
 play()
# Main
if __name__ == '__main__':
 play()

위의 소스 코드를 실행하면 다음은 3 X 3 tic tac toe 보드의 예상 출력입니다.

------------
N-DIMENSIONAL TIC TAC TOE game by guru 99.com
------------
Guru99 says>>> Enter N, the dimensions of the board: 3
_ _ _
_ _ _
_ _ _
Player 1 - Pick location (row, col): 1 1
_ _ _
_ X _
_ _ _
Player 2 - Pick location (row, col): 0 1
_ O _
_ X _
_ _ _
Player 1 - Pick location (row, col): 1 2
_ O _
_ X X
_ _ _
Player 2 - Pick location (row, col): 0 2
_ O O
_ X X
_ _ _
Player 1 - Pick location (row, col): 1 0
_ O O
X X X
_ _ _
Game over, Player 1 wins.
Play Guru99 tic tac toe_Game again? (y/n):

전체 코드 분석

만드는 중 Python의 tic tac toe는 간단합니다. 각 줄에서 무슨 일이 일어나는지 이해하기 위해 다양한 기능을 조금씩 분석해 보겠습니다.

보드 인쇄

Tic tac toe 보드는 주요 게임 디스플레이입니다. 에서는 Python 디스플레이 창을 사용하여 게임 보드를 표시합니다.

Python에서 tic tac toe용 보드를 만드는 데 도움이 되는 단계는 다음과 같습니다.

Tic Tac Toe용 Python 코드

def getInput(prompt, cast=None, condition=None, errorMessage=None):
 while True:
 try:
 val = cast(input(prompt))
 assert condition is None or condition(val)
 return val
 except:
 print(errorMessage or "Invalid input.")
# Print the board
def printBoard(board):
 print()
 for row in board:
 print(*row)
 print()
N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ",
 cast=int,
 condition=lambda x: x >= 3,
 errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com")
board = [['_'] * N for _ in range(N)]
used = 0
turn = 0
printBoard(board)

코드 출력:

------------
N-DIMENSIONAL TIC TAC TOE game by guru 99.com
------------
Guru99 says>>> Enter N, the dimensions of the board: 3
_ _ _
_ _ _
_ _ _

Tic Tac Toe 게임 – 승리 배열

어떤 플레이어가 승리했는지 확인하려면 행, 열, 대각선에서 승리 조합을 확인해야 합니다. 승리자가 있다면 승리 메시지를 보여줘야 합니다.

열의 경우 행과 동일한 기능을 반복합니다. 각 플레이어가 자신의 자리를 선택한 후 플레이어가 승리했는지 확인합니다.

대각선 승리

왼쪽 대각선의 경우 작업이 더 간단해집니다. 우리는 항상 대각선의 셀을 비교할 것입니다. 단, 승자가 없는 경우에는 다음 지시로 진행할 수 있습니다.

게임 로직 플레이

이것이 게임의 주요 기능입니다. 이를 위해 정보를 저장하는 변수를 사용할 수 있습니다.

결론


python

  1. 파이썬 반복자
  2. 파이썬 모듈
  3. Linux, macOS, Windows에서 Python 버전 확인:빠른 가이드
  4. Python 속성:고급 데이터 클래스, 예제 코드 포함
  5. Python 연산자:산술, 논리, 비교, 할당, 비트 및 우선 순위
  6. Python 목록 이해, 추가, 정렬, 길이 [예]
  7. Zen of Python(PEP-20 부활절 달걀)
  8. Python For &While 루프:열거, 중단, 계속 문
  9. Python에서 예외를 처리하지 않는 방법
  10. Python RegEx:re.match(), re.search(), re.findall() 예제 포함