Форум программистов, компьютерный форум, киберфорум
Python: Решение задач
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.75/4: Рейтинг темы: голосов - 4, средняя оценка - 4.75
0 / 0 / 0
Регистрация: 20.12.2020
Сообщений: 233

Три в ряд

02.04.2022, 21:35. Показов 968. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Вам предстоит написать простую игру с компьютером, модификацию всем известной "Три в ряд".
Условия простые.
Пользователь вводит число – сколько мест в линии, первый ход делает компьютер, вводит строку: место и цвет (’R’, ’G’ или ’B’) через пробел, нумерация с 0.
Выводится сообщение, кто сделал и какой ход:
AI step <шаг>
или
Your step <шаг>

Выводится строка с размещенной буквой.
Затем ходит пользователь, вводит в одной строке место и цвет (’R’, ’G’ или ’B’) через пробел. Если три буквы одного цвета рядом, они пропадают, тому, кто поставил последнюю, начисляется очко и линия выводится ещё раз, уже без одинаковых букв, стоящих рядом.
Игра продолжается, пока есть места.
Если пользователь хочет походить на занятое место, выводится сообщение:
This place is taken.

По окончании выводятся сообщения, кто выиграл и счёт.
Если выиграл компьютер, вывести:
AI win! <счёт> : <счёт>

Если выиграл пользователь, выводим:
You win! <счёт> : <счёт>

Если ничья:
We have a tie.

Пример работы программы:

5
AI step 2 R
_ _ R _ _
Your step 1 B
_ B R _ _
AI step 0 B
B B R _ _
Your step 3 R
B B R R _
AI step 4 R
B B R R R
B B _ _ _
Your step 3 G
B B _ G _
AI step 2 G
B B G G _
Your step 4 R
B B G G R
AI win! 1 : 0

Моё решение
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
game_field = ['_' for i in range(int(input()))]
 
computer_count = 0
user_count = 0
 
IsUserStep = False
IsStop = False
 
while 1:
    count_busy_field = 0
    for i in game_field:
        if i != '_':
            count_busy_field += 1
    if count_busy_field == len(game_field):
        if computer_count > user_count:
            print(f"AI win! {computer_count} : {user_count}")
            break
        elif computer_count < user_count:
            print(f"You win! {computer_count} : {user_count}")
            break
        else:
            print("We have a tie.")
            break
    if IsUserStep is False:
        for i in range(len(game_field) - 2):
            if game_field[i] == 'R' and game_field[i + 1] == 'R' and game_field[i + 2] == '_':
                game_field[i + 2] = 'R'
                print(f"AI step {i + 2} R")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            elif game_field[i] == 'R' and game_field[i + 1] == '_' and game_field[i + 2] == 'R':
                game_field[i + 1] = 'R'
                print(f"AI step {i + 1} R")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            elif game_field[i] == '_' and game_field[i + 1] == 'R' and game_field[i + 2] == 'R':
                game_field[i] = 'R'
                print(f"AI step {i} R")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            if game_field[i] == 'G' and game_field[i + 1] == 'G' and game_field[i + 2] == '_':
                game_field[i + 2] = 'G'
                print(f"AI step {i + 2} G")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            elif game_field[i] == 'G' and game_field[i + 1] == '_' and game_field[i + 2] == 'G':
                game_field[i + 1] = 'G'
                print(f"AI step {i + 1} G")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            elif game_field[i] == '_' and game_field[i + 1] == 'G' and game_field[i + 2] == 'G':
                game_field[i] = 'G'
                print(f"AI step {i} G")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            if game_field[i] == 'B' and game_field[i + 1] == 'B' and game_field[i + 2] == '_':
                game_field[i + 2] = 'B'
                print(f"AI step {i + 2} B")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            elif game_field[i] == 'B' and game_field[i + 1] == '_' and game_field[i + 2] == 'B':
                game_field[i + 1] = 'B'
                print(f"AI step {i + 1} B")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
            elif game_field[i] == '_' and game_field[i + 1] == 'B' and game_field[i + 2] == 'B':
                game_field[i] = 'B'
                print(f"AI step {i} B")
                print(*game_field, sep=' ')
                game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                IsStop = True
                break
        if IsStop is True:
            print(*game_field, sep=' ')
            computer_count += 1
            IsUserStep = True
            IsStop = False
            continue
        if game_field[0] == '_' and game_field[1] == '_' and game_field[2] == '_' and \
                game_field[3] == '_' and game_field[0] == '_':
            game_field[2] = 'R'
            print("AI step 2 R")
            print(*game_field, sep=' ')
            IsUserStep = True
            continue
        for i in range(len(game_field) - 2):
            if (game_field[i] == 'R' and game_field[i + 1] == '_' and game_field[i + 2] == '_') or \
                    (game_field[i] == '_' and game_field[i + 1] == '_' and game_field[i + 2] == 'R'):
                game_field[i + 1] = 'R'
                print(f"AI step {i + 1} R")
                IsStop = True
                break
            elif (game_field[i] == 'G' and game_field[i + 1] == '_' and game_field[i + 2] == '_') or \
                    (game_field[i] == '_' and game_field[i + 1] == '_' and game_field[i + 2] == 'G'):
                game_field[i + 1] = 'G'
                print(f"AI step {i + 1} G")
                IsStop = True
                break
            elif (game_field[i] == 'B' and game_field[i + 1] == '_' and game_field[i + 2] == '_') or \
                    (game_field[i] == '_' and game_field[i + 1] == '_' and game_field[i + 2] == 'B'):
                game_field[i + 1] = 'B'
                print(f"AI step {i + 1} B")
                IsStop = True
                break
        if IsStop is True:
            print(*game_field, sep=' ')
            IsUserStep = True
            IsStop = False
            continue
        for i in range(len(game_field)):
            if game_field[i] == '_':
                if i > 0:
                    game_field[i] = game_field[i - 1]
                    print(f"AI step {i} {game_field[i - 1]}")
                    IsStop = True
                    break
                else:
                    game_field[i] = 'R'
                    print(f"AI step {i} R")
                    IsStop = True
                    break
        if IsStop is True:
            print(*game_field, sep=' ')
            IsUserStep = True
            IsStop = False
            continue
    else:
        while 1:
            buffer = str(input()).split()
            if game_field[int(buffer[0])] != '_':
                print("Your step ", end='')
                print(*buffer, sep=' ')
                print('This place is taken.')
                continue
            print("Your step ", end='')
            print(*buffer, sep=' ')
            game_field[int(buffer[0])] = buffer[1]
            print(*game_field, sep=' ')
            IsUserStep = False
            count_r = 0
            count_g = 0
            count_b = 0
            for i in range(len(game_field) - 2):
                if game_field[i] == 'R' and game_field[i + 1] == 'R' and game_field[i + 2] == 'R':
                    user_count += 1
                    game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                    print(*game_field, sep=' ')
                elif game_field[i] == 'G' and game_field[i + 1] == 'G' and game_field[i + 2] == 'G':
                    user_count += 1
                    game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                    print(*game_field, sep=' ')
                elif game_field[i] == 'B' and game_field[i + 1] == 'B' and game_field[i + 2] == 'B':
                    user_count += 1
                    game_field[i], game_field[i + 1], game_field[i + 2] = '_', '_', '_'
                    print(*game_field, sep=' ')
            break
Ошибка
Code
1
2
3
4
5
Traceback (most recent call last):
  File "/temp/executing/solution.py", line 145, in <module>
    buffer = str(input()).split()
EOFError: EOF when reading a line
make: *** [run] Error 1
Вывод
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
AI step 2 R
_ _ R _ _
Your step 0 B
B _ R _ _
AI step 3 R
B _ R R _
Your step 3 G
This place is taken.
Your step 4 B
B _ R R B
AI step 1 R
B R R R B
B _ _ _ B
Your step 1 R
B R _ _ B
AI step 2 R
B R R _ B
Your step 1 R
This place is taken.
Your step 3 R
B R R R B
B _ _ _ B
AI step 1 B
B B _ _ B
Your step 3 B
B B _ B B
AI step 2 B
B B B B B
_ _ _ B B
Your step 3 G
This place is taken.
Your step 3 B
This place is taken.
Your step 2 R
_ _ R B B
AI step 1 R
_ R R B B
Makefile:5: recipe for target 'run' failed
Сообщение
Code
1
2
3
4
Неверная замена трёх в ряд.
Completion status: ABNORMAL_EXIT
Term sig: null
Error code: 2
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
02.04.2022, 21:35
Ответы с готовыми решениями:

Три в ряд
Здравствуйте, программа проходит все мои тесты, но яндекс почему-то выдаёт ошибку. Задача: Вам предстоит написать простую игру с...

Три в ряд
Вам предстоит написать простую игру с компьютером, модификацию всем известной &quot;Три в ряд&quot;. Условия простые. Пользователь...

Три функции print() в ряд?
Нужно создать программу которая будет выводить три любых сообщений (трижды вызвать функцию print()), но все сообщения выведуться в одну...

1
3750 / 1944 / 612
Регистрация: 21.11.2021
Сообщений: 3,706
03.04.2022, 13:55
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from random import randint
# ==============================================================================
FIELD_SYMB = '_'
COLORS     = 'RGB'
WIN_COUNT  = 3
# ==============================================================================
def print_game_field( game_field ):
    print( ' '.join( game_field ) )
# ==============================================================================
def set_move_in_game_field( game_field, move ):
    ind, symb = move
    return game_field[:ind] + symb + game_field[ind + 1:]
# ==============================================================================
def AI_makes_move( moves, game_field ):
    for m in moves:
        if move_is_good(m, game_field):
            return m
    return moves[ randint( 0, len(moves) - 1 ) ]
# ==============================================================================
def user_makes_move(moves, game_field):
    while True:
        move_str = input('Ваш ход: ')
        for m in moves:
            ind, symb = m
            if str(ind) + ' ' + symb == move_str:
                return m
        print('Ввод некорректный.')
# ==============================================================================
def get_moves(game_field):
    res = []
    for i in range( len(game_field) ):
        if game_field[i] == FIELD_SYMB:
            for symb in COLORS:
                res.append([i, symb])
    return res
# ==============================================================================
def move_is_good(move, game_field):
    ind, symb = move
    new_game_field = set_move_in_game_field(game_field, move)
    return symb * WIN_COUNT in new_game_field
# ==============================================================================
def remove_good_move(game_field):
    for symb in COLORS:
        ind = game_field.find( symb * WIN_COUNT )
        if ind != -1:
            return game_field[:ind] + FIELD_SYMB * WIN_COUNT + game_field[ind + WIN_COUNT:]
# ==============================================================================
def play(game_field):
    AI_counter   = 0
    user_counter = 0
    AI_move      = 1
    while True:
        moves = get_moves(game_field)
        if not moves:
            break
        print()
        move = [user_makes_move, AI_makes_move][AI_move](moves, game_field)
        ind, symb = move
        print(f'{["user step", "AI step"][AI_move]} {ind} {symb}')
        game_field = set_move_in_game_field(game_field, move)
        print_game_field(game_field)
        if move_is_good(move, game_field):
            if AI_move:
                AI_counter += 1
            else:
                user_counter += 1
            game_field = remove_good_move(game_field)
            print_game_field(game_field)
        AI_move = not AI_move
 
    if AI_counter > user_counter:
        print(f'AI win! {AI_counter} : {user_counter}')
    elif user_counter > AI_counter:
        print(f'You win! {user_counter} : {AI_counter}')
    else:
        print(f'We have a tie.')
# ==============================================================================
n = int(input('Введите ширину поля: '))
game_field = FIELD_SYMB * n
play(game_field)
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
03.04.2022, 13:55
Помогаю со студенческими работами здесь

Три в ряд на JS
Привет всем. Нашел в интернете простенький скрипт популярной игры из категории 3 в ряд (ссылка). Там реализованы базовые...

Три в ряд
Вам предстоит написать простую игру с компьютером, модификацию всем известной &quot;Три в ряд&quot;. Условия простые. Пользователь...

Три в ряд
Три в ряд Ограничение времени 1 секунда Ограничение памяти 64Mb Ввод стандартный ввод или input.txt Вывод стандартный вывод или...

Три сполера в ряд
вспомнил о закинутом футбольном сайте, сейчас на всех аналогичных сайтах прямые трансляции с источником видео скрыты, или в спойлерах или...

Три div в ряд
три div cделать в ряд внутри div - прям верный css нужен


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Доступность команды формы по условию
Maks 07.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: сделать доступной кнопку (команда формы "ЗавершитьСписание") при. . .
Уведомление о неверно выбранном значении справочника
Maks 06.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "НарядПутевка", разработанного в конфигурации КА2. Задача: уведомлять пользователя, если в документе выбран неверный склад. . .
Установка Qt Creator для C и C++: ставим среду, CMake и MinGW без фреймворка Qt
8Observer8 05.04.2026
Среду разработки Qt Creator можно установить без фреймворка Qt. Есть отдельный репозиторий для этой среды: https:/ / github. com/ qt-creator/ qt-creator, где можно скачать установщик, на вкладке Releases:. . .
AkelPad-скрипты, структуры, и немного лирики..
testuser2 05.04.2026
Такая программа, как AkelPad существует уже давно, и также давно существуют скрипты под нее. Тем не менее, прога живет, периодически что-то не спеша дополняется, улучшается. Что меня в первую очередь. . .
Отображение реквизитов в документе по условию и контроль их заполнения
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеСпецтехники", разработанного в конфигурации КА2. Данный документ берёт данные из другого нетипового документа. . .
Фото всей Земли с борта корабля Orion миссии Artemis II
kumehtar 04.04.2026
Это первое подобное фото сделанное человеком за 50 лет. Снимок называют новым вариантом легендарной фотографии «The Blue Marble» 1972 года, сделанной с борта корабля «Аполлон-17». Новое фото. . .
Вывод диалогового окна перед закрытием, если документ не проведён
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: реализовать программный контроль на предмет проведения документа. . .
Программный контроль заполнения реквизитов табличной части документа
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: 1. Реализовать контроль заполнения реквизита. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru