Learn Python 015: Tic Tac Toe Game
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Learn Python 015: Tic Tac Toe Game相关的知识,希望对你有一定的参考价值。
board = [‘ ‘ for i in range(9)] def print_board(): row_1 = ‘|{}|{}|{}|‘.format(board[0], board[1], board[2]) row_2 = ‘|{}|{}|{}|‘.format(board[3], board[4], board[5]) row_3 = ‘|{}|{}|{}|‘.format(board[6], board[7], board[8]) print(‘\n‘) print(row_1) print(row_2) print(row_3) print(‘\n‘) def player_move(icon): if icon == ‘ X ‘: number = 1 elif icon == ‘ O ‘: number = 2 print(‘Your turn player {}.‘.format(number)) choice = int(input(‘Enter your move (1-9): ‘).strip()) if board[choice - 1] == ‘ ‘: board[choice - 1] = icon else: print(‘\n‘) print(‘That space is taken!‘) def victory(icon): if (board[0] == icon and board[1] == icon and board[2] == icon) or (board[3] == icon and board[4] == icon and board[5] == icon) or (board[6] == icon and board[7] == icon and board[8] == icon) or (board[0] == icon and board[3] == icon and board[6] == icon) or (board[1] == icon and board[4] == icon and board[7] == icon) or (board[2] == icon and board[5] == icon and board[8] == icon) or (board[0] == icon and board[4] == icon and board[8] == icon) or (board[2] == icon and board[4] == icon and board[6] == icon): return True else: return False def game_is_draw(): if ‘ ‘ not in board: return True else: return False while True: print_board() player_move(‘ X ‘) print_board() if victory(‘ X ‘): print(‘X wins! Nicely done!‘) break elif game_is_draw(): print(‘Its a draw!‘) break player_move(‘ O ‘) if victory(‘ O ‘): print_board() print(‘O wins! Nicely done!‘) break elif game_is_draw(): print(‘Its a draw!‘) break
以上是关于Learn Python 015: Tic Tac Toe Game的主要内容,如果未能解决你的问题,请参考以下文章
Principle of Computing (Python)学习笔记 DFS Search + Tic Tac Toe use MiniMax Stratedy