Notice
Recent Posts
Recent Comments
Today
Total
05-21 05:41
Archives
관리 메뉴

Jeongchul Kim

TicTacToeGame.py 본문

Computer Language

TicTacToeGame.py

김 정출 2015. 1. 12. 16:26
  1. # Tic Tac Toe
  2.  
  3. import random
  4.  
  5. def drawBoard(board):
  6.     # This function prints out the board that it was passed.
  7.  
  8.     # "board" is a list of 10 strings representing the board (ignore index 0)
  9.     print('   |   |')
  10.     print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
  11.     print('   |   |')
  12.     print('-----------')
  13.     print('   |   |')
  14.     print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
  15.     print('   |   |')
  16.     print('-----------')
  17.     print('   |   |')
  18.     print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
  19.     print('   |   |')
  20.  
  21. def inputPlayerLetter():
  22.     # Lets the player type which letter they want to be.
  23.     # Returns a list with the player's letter as the first item, and the computer's letter as the second.
  24.     letter = ''
  25.     while not (letter == 'X' or letter == 'O')# letter가 X 또는 O이 아니라면 계속 반복
  26.         print('Do you want to be X or O?')
  27.         letter = input().upper() # 플레이어의 글자가 된다.
  28.  
  29.     # the first element in the tuple is the player's letter, the second is the computer's letter.
  30.     # 정해진 글자들을 리스트로 반환한다 [플레이어,컴퓨터]
  31.     if letter == 'X':
  32.         return ['X''O']
  33.     else:
  34.         return ['O''X']
  35.  
  36.  
  37. def whoGoesFirst():
  38.     # Randomly choose the player who goes first.
  39.     if random.randint(01) == 0# 랜덤 수를 이용해 누가 먼저할 지를 뽑는다.
  40.         return 'computer'
  41.     else:
  42.         return 'player'
  43.  
  44. def playAgain():
  45.     # This function returns True if the player wants to play again, otherwise it returns False.
  46.     print('Do you want to play again? (yes or no)')
  47.     return input().lower().startswith('y')
  48.     # startswith('@')메소드 : 문자열이 @로 시작하는 검사한다.
  49.  
  50. def makeMove(board, letter, move):
  51.     board[move] = letter
  52.     # 리스트와 딕셔너리의 데이터 타입은 함수 파라미터로 값을 넣어 변경해주어도 값이 없어지지 않는다.
  53.     # 일반 primitve data type가 다르다.
  54.    
  55. # 리스트 레퍼런스(Reference), 딕셔너리 레퍼런스(Dictionary Reference)
  56. # 레퍼런스 는 가르키는 값이다. 그러므로 리스트를 복사시, 리스트 자체가 아닌 레퍼런스를 집어넣기 때문에
  57. # 동일한 리스트를 가르키는 값을 가진다.
  58.  
  59. def isWinner(bo, le):
  60.     # Given a board and a player's letter, this function returns True if that player has won.
  61.     # We use bo instead of board and le instead of letter so we don't have to type as much.
  62.     return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
  63.     (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
  64.     (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
  65.     (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
  66.     (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
  67.     (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
  68.     (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
  69.     (bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
  70.  
  71. def getBoardCopy(board):
  72.     # Make a duplicate of the board list and return it the duplicate.
  73.     dupeBoard = []
  74.  
  75.     for i in board:
  76.         dupeBoard.append(i)
  77.  
  78.     return dupeBoard
  79.  
  80. def isSpaceFree(board, move):
  81.     # Return true if the passed move is free on the passed board.
  82.     return board[move] == ' '
  83.  
  84. def getPlayerMove(board):
  85.     # Let the player type in his move.
  86.     move = ' '
  87.     # 건너뛰기(Short-Circuit) : or 연산자 왼쪽에 있는 조건이 True가 되면 전체 표현식은 True가 되므로, 오른쪽의 값은 호출하지 않고 넘어간다.
  88.     #   - 그러므로 밑의 isSpaceFree함수의 파라미터 int() 형변환에서 에러가 발생하지 않는다.
  89.     #   - 하지만 순서가 조건의 순서가 바뀐다면 문제가 생길 수 있다.
  90.     while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
  91.         print('What is your next move? (1-9)')
  92.         move = input()
  93.     return int(move)
  94.  
  95. def chooseRandomMoveFromList(board, movesList):
  96.     # Returns a valid move from the passed list on the passed board.
  97.     # Returns None if there is no valid move.
  98.     possibleMoves = []
  99.     for i in movesList:
  100.         if isSpaceFree(board, i):
  101.             possibleMoves.append(i) # 움직일 수 있는 위치를 판멸해 리스트에 저장한다.
  102.  
  103.     if len(possibleMoves) != 0# 움직일 수 있는 위치의 리스트의 길이가 0이 아니라면
  104.         return random.choice(possibleMoves) # 랜덤으로 리스트 중 하나를 뽑아낸다.
  105.     else# 길이가 0이라면, 뽑아낼 수 있는 위치가 없다는 뜻이다.
  106.         return None # None 값은 변수에 할당할 수 있는 특수한 값으로 None Value 값이 없다는 뜻이다.
  107.  
  108. def getComputerMove(board, computerLetter)# 컴퓨터의 인공지능 부분
  109.     # Given a board and the computer's letter, determine where to move and return that move.
  110.     if computerLetter == 'X':
  111.         playerLetter = 'O'
  112.     else:
  113.         playerLetter = 'X'
  114.  
  115.     # Here is our algorithm for our Tic Tac Toe AI:
  116.     # First, check if we can win in the next move
  117.     # 다음 수로 컴퓨터가 이기는 지 검사한다.
  118.     for i in range(110):
  119.         copy = getBoardCopy(board)
  120.         if isSpaceFree(copy, i):
  121.             makeMove(copy, computerLetter, i)
  122.             if isWinner(copy, computerLetter):
  123.                 return i
  124.  
  125.     # Check if the player could win on his next move, and block them.
  126.     # 다음 수로 플레이어가 이기는 지 검사한다.
  127.     for i in range(110):
  128.         copy = getBoardCopy(board)
  129.         if isSpaceFree(copy, i):
  130.             makeMove(copy, playerLetter, i)
  131.             if isWinner(copy, playerLetter):
  132.                 return i
  133.  
  134.     # Try to take one of the corners, if they are free.
  135.     move = chooseRandomMoveFromList(board, [1379])
  136.     if move != None:
  137.         return move
  138.  
  139.     # Try to take the center, if it is free.
  140.     if isSpaceFree(board, 5):
  141.         return 5
  142.  
  143.     # Move on one of the sides.
  144.     return chooseRandomMoveFromList(board, [2468])
  145.  
  146. def isBoardFull(board):
  147.     # Return True if every space on the board has been taken. Otherwise return False.
  148.     for i in range(110):
  149.         if isSpaceFree(board, i):
  150.             return False
  151.     return True
  152.  
  153.  
  154. print('Welcome to Tic Tac Toe!')
  155.  
  156. while True:
  157.     # Reset the board
  158.     theBoard = [' '] * 10 # 곱하기(*)연산자로 쉽게 문자열을 만들 수 있다. = ['','','','','','','','','','']
  159.     playerLetter, computerLetter = inputPlayerLetter()
  160.     turn = whoGoesFirst()
  161.     print('The ' + turn + ' will go first.')
  162.     gameIsPlaying = True
  163.  
  164.     while gameIsPlaying:
  165.         if turn == 'player':
  166.             # Player's turn.
  167.             drawBoard(theBoard)
  168.             move = getPlayerMove(theBoard)
  169.             makeMove(theBoard, playerLetter, move)
  170.  
  171.             if isWinner(theBoard, playerLetter):
  172.                 drawBoard(theBoard)
  173.                 print('Hooray! You have won the game!')
  174.                 gameIsPlaying = False
  175.             else:
  176.                 if isBoardFull(theBoard):
  177.                     drawBoard(theBoard)
  178.                     print('The game is a tie!')
  179.                     break
  180.                 else:
  181.                     turn = 'computer'
  182.  
  183.         else:
  184.             # Computer's turn.
  185.             move = getComputerMove(theBoard, computerLetter)
  186.             makeMove(theBoard, computerLetter, move)
  187.  
  188.             if isWinner(theBoard, computerLetter):
  189.                 drawBoard(theBoard)
  190.                 print('The computer has beaten you! You lose.')
  191.                 gameIsPlaying = False
  192.             else:
  193.                 if isBoardFull(theBoard):
  194.                     drawBoard(theBoard)
  195.                     print('The game is a tie!')
  196.                     break
  197.                 else:
  198.                     turn = 'player'
  199.  
  200.     if not playAgain():
  201.         break
  202.  


'Computer Language' 카테고리의 다른 글

BaseBallGame.py  (0) 2015.01.13
BaglesGame.py  (0) 2015.01.13
HangmanGame_edit.py  (0) 2015.01.12
HangmanGame.py  (0) 2015.01.10
bug & debugger  (0) 2015.01.09
Comments