Двадцать одно, но не очко
Правила этой простой игры с числами написаны над игровым полем, весь "ИИ" для неё уместился ровно в три строчки кода. Возможно ли этот ИИ обыграть? Подумайте сами :)
Ниже показан скрипт в работе и полный исходник. Можно вставить теги <style>, внешний <div> и <script> + <noscript> в любой документ HTML, как сделано здесь.
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>21 Game</title> <style> .interface21 div { width: 50%; display: inline-flex; justify-content: flex-end; } div.total21 { margin-bottom: 1ch; } .label21 { padding-right: 1ch; } .button21 { margin-left: 1em; margin-bottom: 1ch; width: 8ch; } </style> </head><body> <div class="interface21"> <div class="total21">21 — это игра для двух игроков, в которой нужно выбрать число 1, 2 или 3, добавляемое к сумме. Выигрывает тот, чьё выбранное число даст ровно 21, будучи прибавленным к текущей сумме. Первым ходит случайно выбранный игрок - вы или компьютер. Используйте кнопки, чтобы делать свои ходы. </div> <div class="total21"> <span id="first21"></span> </div> <div class="total21"> <label class="label21" for="human21">Ваш ход:</label> <input type="text" id="human21" readonly> </div> <div class="total21"> <label class="label21" for="AI21">Ход компьютера:</label> <input type="text" id="AI21" readonly> </div> <div class="total21"> <label class="label21" for="sum21">Сумма:</label> <input type="text" id="sum21" readonly> </div> <div class="buttons"> <button class="button21" id="choice21_1">один</button> <button class="button21" id="choice21_2">два</button> <button class="button21" id="choice21_3">три</button> <button class="button21" id="restart21">заново</button> </div> <div class="total21" id="message21"></div> </div> <script> function game21() { let runningTotal = 0; const human = document.getElementById('human21'); const AI = document.getElementById('AI21'); const sum = document.getElementById('sum21'); const first = document.getElementById('first21') const message = document.getElementById('message21'); const choiceButtons = new Array(3); document.getElementById('choice21_1').addEventListener ("click",function() { choice21(1); }); document.getElementById('choice21_2').addEventListener ("click",function() { choice21(2); }); document.getElementById('choice21_3').addEventListener ("click",function() { choice21(3); }); document.getElementById('restart21').addEventListener ("click",function() { restart21(); }); function restart21() { runningTotal = 0; sum.value = runningTotal; human.value = ''; AI.value = ''; for (let i = 1; i <= 3; i++) { let button = document.getElementById('choice21_' + i); button.disabled = false; choiceButtons[i] = button; } message.innerText = ''; if (Math.random() > 0.5) { update21(AI, ai21()); first.innerText = 'Первым ходит компьютер.' } else first.innerText = 'Первым ходите Вы.' } function update21(textBox, n) { textBox.value = n; runningTotal = runningTotal + n; sum.value = runningTotal; for (let i = 1; i <= 3; i++) if (runningTotal + i > 21) choiceButtons[i].disabled = true; } function choice21(n) { update21(human, n); if (runningTotal == 21) message.innerText = 'Вы выиграли!'; else { update21(AI, ai21()); if (runningTotal == 21) message.innerText = 'Победил компьютер.'; } } function ai21() { //ИИ для задачи :) for (let i = 1; i <= 3; i++) if (runningTotal + i == 21) return i; for (let i = 1; i <= 3; i++) if ((runningTotal + i - 1) % 4 == 0) return i; return 1; } restart21(); } window.addEventListener ('load', function (e) { game21(); }, false); </script> <noscript> <p>Включите Javascript в браузере для работы приложения.</p> </noscript> </body> </html>
P.S. Так как получен всего один ответ, и тот неправильный, раскроем тайну двадцати одного некарточного очка.
Стратегия выигрыша в эту игру очень проста. Первый игрок выигрывает, если начинает с единицы, а потом ходит так, чтобы сумма на следующем ходу была равна 5, 9, 13, 17 и затем 21. Второй игрок, если первый соблюдает эту стратегию, выиграть не может.
23.04.2023, 12:48 [395 просмотров]