Advertisement
first_periscope

крестики нолики игра

Apr 7th, 2023
1,213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.26 KB | Source Code | 0 0
  1. # Итак, мы имеем:
  2. #
  3. # Игру «Крестики-нолики».
  4. # Консоль, куда будет выводиться ход игры. Тут делать красиво мы умеем с помощью форматированных строк.
  5. # Неутолимое желание написать что-то реальное своими руками.
  6. # Размер поля предполагается равным 3x3.
  7. #
  8. # Пример печати поля в консоль:
  9. #    0 1 2
  10. # 0  X X 0
  11. # 1  0 X 0
  12. # 2  - 0 -
  13. #
  14.  
  15. def print_play_field(field):
  16.     print('   0 1 2')
  17.     for i in range(3):
  18.         print(f'{i} ', *field[i])
  19.  
  20.  
  21. def get_coordinates(field, element_is_cross):
  22.     while True:
  23.         coordinates = input(
  24.             'Введите координаты хода ' + ('крестиком' if element_is_cross else 'ноликом') +
  25.             ' в формате \'X Y\', где X-столбец, а Y-строка (q - выход): ').split()
  26.         if coordinates[0] == 'q':
  27.             exit(0)
  28.         if len(coordinates) != 2:
  29.             print('Формат ввода не соответствует запрашиваемому \'X Y\'!')
  30.         elif not (coordinates[0].isnumeric() and coordinates[1].isnumeric()):
  31.             print('Необходимо вводить только положительные целые числа!')
  32.         elif not (int(coordinates[0]) in range(3) and int(coordinates[1]) in range(3)):
  33.             print('Необходимо вводить числа в диапазоне от 0 до 2!')
  34.         elif field[int(coordinates[1])][int(coordinates[0])] != '-':
  35.             print('Ячейка занята. Выберите другую!')
  36.         else:
  37.             return int(coordinates[1]), int(coordinates[0])
  38.  
  39.  
  40. def win_combination(field):
  41.     # Проверяем по вертикали и горзонтали
  42.     for i in range(3):
  43.         if field[i][i] != '-' and (
  44.                 field[0][i] == field[1][i] == field[2][i] or field[i][0] == field[i][1] == field[i][2]):
  45.             return True
  46.     # Проверяем обе диагонали
  47.     if field[1][1] != '-' and (
  48.             field[0][0] == field[1][1] == field[2][2] or field[0][2] == field[1][1] == field[2][0]):
  49.         return True
  50.     return False
  51.  
  52. def main():
  53.     play_field = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]    # Игровое поле
  54.     current_is_cross = True                                             # Начинаем игру всегда с крестика
  55.     play_count = None                                                   # Счетчик ходов
  56.     for play_count in reversed(range(9)):
  57.         print_play_field(play_field)
  58.         x, y = get_coordinates(play_field, current_is_cross)
  59.         play_field[x][y] = 'X' if current_is_cross else '0'
  60.         if win_combination(play_field):
  61.             break
  62.         current_is_cross = not current_is_cross                         # Меняем текущий тип элемента (крестик или нет)
  63.     print_play_field(play_field)
  64.     if play_count:
  65.         print('Выиграли', 'крестики!' if current_is_cross else 'нолики!')
  66.     else:
  67.         print('Ничья!')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement