@K1ssuke

Как сократить/оптимизировать код?

import random

mss1 = ["_", "_", "_"]
mss2 = ["_", "_", "_"]
mss3 = ["_", "_", "_"]

def printP():
    print("    1    2    3")
    print("A", mss1)
    print(" ")
    print("B", mss2)
    print(" ")
    print("C", mss3)

def win():
    if mss1[0] == "X" and mss1[1] == "X" and mss1[2] == "X": print("Win User"); return True
    elif mss2[0] == "X" and mss2[1] == "X" and mss2[2] == "X": print("Win User"); return True
    elif mss3[0] == "X" and mss3[1] == "X" and mss3[2] == "X": print("Win User"); return True
    elif mss1[0] == "X" and mss2[0] == "X" and mss3[0] == "X": print("Win User"); return True
    elif mss1[1] == "X" and mss2[1] == "X" and mss3[1] == "X": print("Win User"); return True
    elif mss1[2] == "X" and mss2[2] == "X" and mss3[2] == "X": print("Win User"); return True
    elif mss1[0] == "X" and mss2[1] == "X" and mss3[2] == "X": print("Win User"); return True
    elif mss3[0] == "X" and mss2[1] == "X" and mss1[2] == "X": print("Win User"); return True

    elif mss1[0] == "0" and mss1[1] == "0" and mss1[2] == "0": print("Win Comp"); return True
    elif mss2[0] == "0" and mss2[1] == "0" and mss2[2] == "0": print("Win Comp"); return True
    elif mss3[0] == "0" and mss3[1] == "0" and mss3[2] == "0": print("Win Comp"); return True
    elif mss1[0] == "0" and mss2[0] == "0" and mss3[0] == "0": print("Win Comp"); return True
    elif mss1[1] == "0" and mss2[1] == "0" and mss3[1] == "0": print("Win Comp"); return True
    elif mss1[2] == "0" and mss2[2] == "0" and mss3[2] == "0": print("Win Comp"); return True
    elif mss1[0] == "0" and mss2[1] == "0" and mss3[2] == "0": print("Win Comp"); return True
    elif mss3[0] == "0" and mss2[1] == "0" and mss1[2] == "0": print("Win Comp"); return True

    else:
        print("Ничья")

def Bot():
    r = random.randint(1, 3)
    if r == 1:
        r = random.randint(0, 2)
        if mss1[r] == "_": mss1[r] = "0"
        else: Bot()
    elif r == 2:
        r = random.randint(0, 2)
        if mss2[r] == "_": mss2[r] = "0"
        else: Bot()
    elif r == 3:
        r = random.randint(0, 2)
        if mss3[r] == "_": mss3[r] = "0"
        else: Bot()

while True:
    printP()
    if win(): break
    else:
        user = input("-> ")
        if user == "A1" or user == "a1":
            if mss1[0] == "_": mss1[0] = "X"; Bot()
            else: print("No ")
        elif user == "A2" or user == "a2":
            if mss1[1] == "_": mss1[1] = "X"; Bot()
            else: print("No ")
        elif user == "A3" or user == "a3":
            if mss1[2] == "_": mss1[2] = "X"; Bot()
            else: print("No ")
        elif user == "B1" or user == "b1":
            if mss2[0] == "_": mss2[0] = "X"; Bot()
            else: print("No ")
        elif user == "B2" or user == "b2":
            if mss2[1] == "_": mss2[1] = "X"; Bot()
            else: print("No ")
        elif user == "B3" or user == "b3":
            if mss2[2] == "_": mss2[2] = "X"; Bot()
            else: print("No ")
        elif user == "C1" or user == "c1":
            if mss3[0] == "_": mss3[0] = "X"; Bot()
            else: print("No ")
        elif user == "C2" or user == "c2":
            if mss3[1] == "_": mss3[1] = "X"; Bot()
            else: print("No ")
        elif user == "C3" or user == "c3":
            if mss3[2] == "_": mss3[2] = "X"; Bot()
            else: print("No ")
  • Вопрос задан
  • 93 просмотра
Пригласить эксперта
Ответы на вопрос 1
Vindicar
@Vindicar
RTFM!
1. Вместо mssX сделай список списков.
field = [ ['_'] * 3, ['_'] * 3, ['_'] * 3 ]
2. Для хода бота пройдись по полю, составь список координат, куда можно ходить. Потом выбирай рандомом из этого списка.
3. Проверку победы гораздо проще заменить на цикл. Соберём все элементы вдоль линии (вертикаль, горизонталь, диагональ) и посмотрим сколько разных элементов нашли. Если только 1 элемент, и это НЕ "_", то игрок с этим элементом победил.
for i in len(field):  # перебираем элементы поля
    values = { field[i][c] for c in len(field[i]) }  # собираем символы i-й строки в _множество_
    if len(values) == 1 and '_' not in values:  # есть строка из одинаковых символов, но не из "_"
        return field[i][0]  # возвращаем символ-победитель
    values = { field[r][i] for r in len(field) }  # собираем символы i-го столбца
    if len(values) == 1 and '_' not in values:  # есть столбец из одинаковых символов, но не из "_"
        return field[0][i]  # возвращаем символ-победитель

По аналогии сделаешь диагонали.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы