Amazing-Python-Scripts
116 строк · 3.4 Кб
1import random2
3
4def display_board(board):5print('-------------')6print('| ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + ' |')7print('-------------')8print('| ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + ' |')9print('-------------')10print('| ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + ' |')11print('-------------')12
13
14def player_input():15marker = ''16while marker != 'X' and marker != 'O':17marker = input('Player 1, choose X or O: ').upper()18player1 = marker19player2 = 'O' if player1 == 'X' else 'X'20return player1, player221
22
23def place_marker(board, marker, position):24board[position] = marker25
26
27def win_check(board, mark):28winning_combinations = [29[1, 2, 3], [4, 5, 6], [7, 8, 9], # rows30[1, 4, 7], [2, 5, 8], [3, 6, 9], # columns31[1, 5, 9], [3, 5, 7] # diagonals32]33return any(all(board[i] == mark for i in combination) for combination in winning_combinations)34
35
36def choose_first():37return random.choice(['Player 1', 'Player 2'])38
39
40def space_check(board, position):41return board[position] == ' '42
43
44def full_board_check(board):45return all(board[i] != ' ' for i in range(1, 10))46
47
48def player_choice(board):49position = 050while position not in range(1, 10) or not space_check(board, position):51position = int(input('Choose a position (1-9): '))52return position53
54
55def replay():56choice = input('Do you want to play again? Enter Yes or No: ')57return choice.lower() == 'yes'58
59
60def play_tic_tac_toe():61print('Welcome to Tic Tac Toe!')62while True:63the_board = [' '] * 1064player1_marker, player2_marker = player_input()65turn = choose_first()66print(turn + ' will go first.')67play_game = input('Are you ready to play? Enter y or n: ')68if play_game.lower() == 'y':69game_on = True70else:71game_on = False72
73while game_on:74if turn == 'Player 1':75display_board(the_board)76position = player_choice(the_board)77place_marker(the_board, player1_marker, position)78
79if win_check(the_board, player1_marker):80display_board(the_board)81print('Player 1 has won!')82game_on = False83else:84if full_board_check(the_board):85display_board(the_board)86print('TIE GAME!')87game_on = False88else:89turn = 'Player 2'90else:91display_board(the_board)92position = player_choice(the_board)93place_marker(the_board, player2_marker, position)94
95if win_check(the_board, player2_marker):96display_board(the_board)97print('Player 2 has won!')98game_on = False99else:100if full_board_check(the_board):101display_board(the_board)102print('TIE GAME!')103game_on = False104else:105turn = 'Player 1'106
107if not replay():108if play_game.lower() == 'n':109print('BYE! Have a good day.')110else:111print('Thank you for playing.')112break113
114
115# Start the game
116play_tic_tac_toe()117