-
Notifications
You must be signed in to change notification settings - Fork 0
Tic Tac Toe 1.0.0 #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lazorikv
wants to merge
7
commits into
master
Choose a base branch
from
tic_tac
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7ddeb51
Tic Tac Toe 1.0.0
lazorikv 7d17447
Merge branch 'master' of https://github.com/lazorikv/python-education…
lazorikv f2245f1
Tic Tac Toe 1.0.1
lazorikv d72dc5e
Merge branch 'master' of https://github.com/lazorikv/python-education…
lazorikv 058ed22
Add minimax, w/out logging and stat
lazorikv c656a0e
Merge branch 'master' of https://github.com/lazorikv/python-education…
lazorikv 81372c0
fixed computer turn
lazorikv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| """Module constants for main part""" | ||
|
|
||
| X = "X" | ||
| O = "O" | ||
| EMPTY = [1, 2, 3, 4, 5, 6, 7, 8, 9] | ||
| TIE = "TIE" | ||
| NUM_SQUARES = 10 | ||
| AI_TURN = True | ||
| USER_TURN = False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| """Module exit from game""" | ||
|
|
||
|
|
||
| def exit_from_game(): | ||
| """Exit from game""" | ||
| raise SystemExit(1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| """Tic - tac - toe game for 2 gamers. Format: enter the number | ||
| in which you want to put your sign - X or O""" | ||
|
|
||
| import logging | ||
|
|
||
| print("$" * 10, " Крестики-нолики для двух игроков ", "$" * 10) | ||
|
|
||
| board = list(range(1, 10)) # list of numbers for cells | ||
|
|
||
| # logging victories into myapp.log | ||
| logging.basicConfig(level=logging.DEBUG, filename='myapp.log', format='%(asctime)s: %(message)s') | ||
|
|
||
| COUNT = 0 # count for replays | ||
|
|
||
|
|
||
| def menu(): | ||
| """Game menu. User enter number into variable - char""" | ||
|
|
||
| print('\nНачать игру - 1\nПосмотреть результаты предыдущих игр - 2\n' | ||
| 'Очистить логи - 3\nВыйти из игры - 4') | ||
| char = input('Введите цифру: ') | ||
| try: | ||
| if char == '1': # start game | ||
| main(board) | ||
| elif char == '2': # open logging file | ||
| with open('myapp.log', 'r') as file: | ||
| line = file.read() | ||
| if len(line) == 0: | ||
| print("Список пуст\n") | ||
| else: | ||
| print(line) | ||
| menu() | ||
| elif char == '3': # clean logging file | ||
| with open('myapp.log', 'w'): | ||
| pass | ||
| print('Список успешно очищен!!!\n') | ||
| menu() | ||
| elif char == '4': # quit | ||
| exit_from_game() | ||
| else: | ||
| print('\nВведите нужную цифру!!!') | ||
| menu() | ||
| except (ValueError, IndexError): | ||
| print('Введите нужную цифру!!!') | ||
| menu() | ||
|
|
||
|
|
||
| def draw_board(d_board): | ||
| """draw board in console""" | ||
| print("-" * 13) | ||
| for i in range(3): | ||
| print("|", d_board[0 + i * 3], "|", d_board[1 + i * 3], "|", d_board[2 + i * 3], "|") | ||
| print("-" * 13) | ||
|
|
||
|
|
||
| def take_input(player_token, sub_board): | ||
| """the player's turn. replacing a digit in a shape with a sign""" | ||
| valid = False | ||
| while not valid: | ||
| player_answer = input("Куда поставим " + player_token + "? ") | ||
| try: | ||
| player_answer = int(player_answer) # Int check | ||
| except Exception: | ||
| print("Некорректный ввод. Вы уверены, что ввели число?") | ||
| continue | ||
| if 1 <= player_answer <= 9: | ||
| if str(sub_board[player_answer - 1]) not in "XO": | ||
| sub_board[player_answer - 1] = player_token | ||
| valid = True | ||
| else: | ||
| print("Эта клетка уже занята!") | ||
| else: | ||
| print("Некорректный ввод. Введите число от 1 до 9.") | ||
|
|
||
|
|
||
| def check_win(c_board): | ||
| """Check game moment for win""" | ||
| win_coord = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), | ||
| (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) # victory options | ||
| for each in win_coord: | ||
| if c_board[each[0]] == c_board[each[1]] == c_board[each[2]]: # check for victory | ||
| return c_board[each[0]] | ||
| return False | ||
|
|
||
|
|
||
| def restart_game(winner): | ||
| """In case of victory, the function implements | ||
| a replay with statistics recording""" | ||
|
|
||
| print('Играть заново - 1\nВыйти - 2') | ||
| char = int(input('Введите число: ')) | ||
| global COUNT | ||
| try: | ||
| if char == 1: | ||
| COUNT += 1 | ||
| stat[sm_dict[str(winner)]] += 1 | ||
| print('Результат:') | ||
| for key, value in stat.items(): | ||
| print(f'{key}: {value}\n') | ||
| main(board) | ||
| elif char == 2: | ||
| exit_from_game() | ||
| else: | ||
| print('Введите нужную цифру!!!') | ||
| restart_game(winner) | ||
| except ValueError: | ||
| print('Введите нужную цифру!!!') | ||
| restart_game(winner) | ||
|
|
||
|
|
||
| def exit_from_game(): | ||
| """Exit from game""" | ||
| raise SystemExit(1) | ||
|
|
||
|
|
||
| def main(s_board): | ||
| """Implements the process of the game. Checks the number of | ||
| moves to determine the state of the game""" | ||
|
|
||
| global board | ||
| counter = 0 # counter for determining the turn of the move | ||
| win = False | ||
| while not win: | ||
| draw_board(s_board) | ||
| if counter % 2 == 0: # if the counter is even, then move X, if odd - О | ||
| take_input("X", board) | ||
| else: | ||
| take_input("O", board) | ||
| counter += 1 | ||
| if counter > 4: # min count of moves for win - 4 | ||
| tmp = check_win(s_board) | ||
| if tmp: | ||
| print(sm_dict[str(tmp)], "выиграл!") | ||
| logging.debug(f'Winner - {sm_dict[str(tmp)]}, who put' | ||
| f' - {tmp}') | ||
| win = True | ||
| board = list(range(1, 10)) | ||
| restart_game(tmp) | ||
| if counter == 9: # if counter = 9 and the game is not over - draw | ||
| print("Ничья!") | ||
| break | ||
|
|
||
|
|
||
| name1 = input('Введите имя игрока1: ') | ||
| name2 = input('Введите имя игрока2: ') | ||
| sm_dict = {'X': name1, 'O': name2} # dict for init players | ||
| stat = {name1: 0, name2: 0} # dict for statistic of the games | ||
| menu() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Большими буквами обычно только константы называют - согласно PEP8.