Skip to content

Instantly share code, notes, and snippets.

@droganaida
Last active September 20, 2017 18:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save droganaida/e57ff0d3458bdc6d3a29b7514aa640e6 to your computer and use it in GitHub Desktop.
Save droganaida/e57ff0d3458bdc6d3a29b7514aa640e6 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Самая сложная логическая задача</title>
<meta charset="UTF-8">
<style>
body, html {
margin: 0;
padding: 0;
}
body {
background: #efefef; color: #2d2d2d;
font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 16px;
line-height: 1.5;
display: flex;
flex-direction: column;
}
.holder {
display: flex;
flex-direction: column;
max-width: 1200px;
margin: 50px auto;
}
.gods, .buttons {
display: flex;
flex-flow: row wrap;
justify-content: center;
}
.gods .item, .gods .item:after {
background: #666666;
border-radius: 50%;
color: #ffffff;
display: block;
height: 100px;
line-height: 100px;
margin: 0 20px 0 0;
padding: 10px;
position: relative;
text-align: center;
width: 100px;
}
.gods .item:after {
content: "?";
position: absolute;
left: 0;
top: 0;
}
.gods .item.checked:after {
display: none;
}
.gods .item.true {
background: #358039;
}
.gods .item.false {
background: #802725;
}
.gods .item.random {
background: #0d3349;
}
.gods .item.na {
background: #666666;
transition: .2s;
}
.buttons {
margin: 50px 0;
}
.button {
display: block;
background: #666666;
border-radius: 5px;
color: #ffffff;
cursor: pointer;
padding: 12px 16px;
margin: 0 20px 0 0;
transition: .2s;
text-align: center;
}
.button:hover {
background: #999999;
transition: .2s;
}
.button.na {
background: #cccccc;
cursor: default;
}
#init, #play, #answers {
flex-direction: column;
}
#play {
display: none;
}
#godsContainer {
margin: 0 0 10px 0;
}
#vars {
display: flex;
flex-direction: row;
justify-content: space-around;
margin: 0 0 30px 0;
}
#vars input {
flex-basis: calc(50% - 6px);
border-radius: 5px;
padding: 12px 16px;
box-sizing: border-box;
outline: 0;
border: 1px solid #cccccc;
}
</style>
</head>
<body>
<div class="holder">
<div id="init">
<div id="vars">
<input id="yes" placeholder="Кодовое слово для ДА">
<input id="no" placeholder="Кодовое слово для НЕТ">
</div>
<div id="godsContainer" class="gods">
<div class="item" data-attached="none"></div>
<div class="item" data-attached="none"></div>
<div class="item" data-attached="none"></div>
</div>
<div id="godsPosition" class="gods">
<div class="item true na checked" data-god="true">Бог Правды</div>
<div class="item false na checked" data-god="false">Бог Лжи</div>
<div class="item random na checked" data-god="random">Бог Случая</div>
</div>
<div class="buttons">
<div id="initPuzzle" class="button">Начать игру</div>
</div>
</div>
<div id="play">
<div id="gods" class="gods"></div>
<div class="buttons">
<div id="checkGods" class="button">Опросить богов</div>
<div id="replay" class="button na">Сыграть еще раз</div>
</div>
<div id="answers"></div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script>
//--------------------Самая сложная логическая головоломка ------------------//
//------------------------ © автор Джордж Булос 1992 -----------------------//
//------------------------ © Решение BlondieCode 2017 ---------------------//
// Раздаем богам имена
var TRUE = "Бог Правды";
var FALSE = "Бог Лжи";
var RANDOM = "Бог Случая";
// Объявляем да и нет на языке аборигенов
var DA = "da";
var JA = "ja";
// Назначим глобальные переменные, что задал игрок
// в качестве ДА и НЕТ
var userYes;
var userNo;
function initPuzzle(yes, no, truePos, falsePos, randomPos) {
userYes = yes;
userNo = no;
// Переопределяем да и нет на языке аборигенов
// Для чистоты эксперимента кинем монетку
var daStatement = coinDecision(userYes, userNo);
if (daStatement == userYes){
DA = userYes;
JA = userNo;
} else {
DA = userNo;
JA = userYes;
}
// Функция подбрасывания монетки для выбора решения
function coinDecision(avers, revers) {
var random = Math.random();
if (random <= 0.5) {
return avers;
} else {
return revers;
}
}
// Конструктор для прототипа Бога Правды
function GodOfTruth() {
this.name = TRUE;
this.class = "true";
this.talkToMe = function(statement) {
if (statement) {
return yes
} else {
return no;
}
};
}
// Конструктор для прототипа Бога Лжи
function GodOfLie() {
this.name = FALSE;
this.class = "false";
this.talkToMe = function(statement) {
if (statement) {
return no
} else {
return yes;
}
};
}
// Конструктор для прототипа Бога Случая
function GodOfRandom() {
this.name = RANDOM;
this.class = "random";
this.talkToMe = function(statement) {
return coinDecision(yes, no);
};
}
// Создаем объекты для каждого из богов
var trueGod = new GodOfTruth();
var secondGod = new GodOfLie();
var randomGod = new GodOfRandom();
var godsArray = [];
godsArray[truePos] = trueGod;
godsArray[falsePos] = secondGod;
godsArray[randomPos] = randomGod;
console.log("-----------------Сформированный массив: ");
console.log("-----------------1 " + godsArray[0].name);
console.log("-----------------2 " + godsArray[1].name);
console.log("-----------------3 " + godsArray[2].name);
console.log("");
return godsArray;
}
function godsInterview(finalGodsArray) {
// Переменная для html ответа
var htmlString = "";
// Выбираем бога номер 2 для опроса
var godToInterview = finalGodsArray[1];
console.log("-----------------Опрашиваем номер 2: ");
// Первый бог это Бог Случая?
var questionOne = (finalGodsArray[0].name == RANDOM);
console.log("-----------------Первый бог - это " + RANDOM + "? - " + questionOne);
// Если первый бог это Бог Случая, ты ответишь JA?
// Двойное отрицание: НЕ НЕправда = правда
questionOne = (godToInterview.talkToMe(questionOne) == JA);
console.log("-----------------Если первый бог - " + RANDOM + ", ты ответишь " + JA + "? - " + questionOne);
// Переводим ответ на язык богов
questionOne = (godToInterview.talkToMe(questionOne));
console.log("-----------------Ответ на языке аборигенов - " + questionOne);
console.log("");
// Определяем какого бога опросить следующим
var nextPosition = 0;
if (questionOne == JA) {
// Если ответ JA, то бог случая точно не номер 3
// Ставим номер 3 в очередь на опрос
nextPosition = 2;
} else {
// Если ответ DA, то бог случая точно не номер 1
// Ставим номер 1 в очередь на опрос
nextPosition = 0;
}
godToInterview = finalGodsArray[nextPosition];
// Задаём выбранному богу вопрос "Если ты Бог Лжи, ты ответишь JA"?
var questionTwo = (godToInterview.name == FALSE);
questionTwo = (godToInterview.talkToMe(questionTwo) == JA);
questionTwo = godToInterview.talkToMe(questionTwo);
console.log("----------------Бог номер " + parseInt(finalGodsArray.indexOf(godToInterview) + 1) + ":");
htmlString = htmlString + "<p>Бог номер <b>" + parseInt(finalGodsArray.indexOf(godToInterview) + 1) + "</b> ";
if (questionTwo == JA) {
// Если он ответил JA, он Бог Лжи
console.log("----------------Нагло врёт!");
htmlString = htmlString + "нагло <b>врёт</b>!</p>"
} else {
// Если ответ DA - Бог Правды
console.log("----------------Говорит только правду!");
htmlString = htmlString + "говорит только <b>правду</b>!</p>";
}
console.log("");
// Задаем предыдущему богу новый вопрос
// Предыдущий оратор (номер 2) - Бог Случая?
var questionThree = (finalGodsArray[1].name == RANDOM);
questionThree = (godToInterview.talkToMe(questionThree) == JA);
questionThree = godToInterview.talkToMe(questionThree);
if (questionThree == JA) {
// Если ответ JA, то так и есть
console.log("----------------" + RANDOM + " номер 2");
htmlString = htmlString + "<p><b>" + RANDOM + "</b> под номером <b>2</b></p>"
} else {
if (nextPosition == 0) {
// Если ответ DA, то это бог, с которым мы не общались
console.log("----------------" + RANDOM + " номер 3");
htmlString = htmlString + "<p><b>" + RANDOM + "</b> под номером <b>3</b></p>"
} else {
console.log("----------------" + RANDOM + " номер 1");
htmlString = htmlString + "<p><b>" + RANDOM + "</b> под номером <b>1</b></p>"
}
}
htmlString = htmlString + "<p>Последнего вычисляем методом исключения =)</p>"
htmlString = htmlString + "<p>DA на языке богов - " + DA + "</p>"
htmlString = htmlString + "<p>JA на языке богов - " + JA + "</p>"
return htmlString;
}
$( document ).ready(function() {
var finalGodsArray = [];
// Разрешаем таскать элемент #godsPosition .item
$('#godsPosition .item').draggable({
cursor: 'move',
containment: '#init',
// helper: 'clone' - элемент будет копироваться
helper: 'original',
// revert: true - элемент вернется на место после драга
revert: false,
drag: dragGod
});
// Разрешаем бросать в элемент #godsContainer .item
$('#godsContainer .item').droppable({
accept: '#godsPosition .item',
drop: dropGod
});
// Функция по событию drag (как только начали тянуть)
function dragGod () {
$(this).addClass('na');
var myGod = $(this).attr('data-god');
$('*[data-attached="' + myGod + '"]').attr('data-attached', 'none');
}
// Функция по событию drop (отпустили клавишу мыши над элементом)
function dropGod(event, ui) {
if ($(this).attr('data-attached') != 'none') {
var godToKickName = $(this).attr('data-attached');
var godToKick = $('*[data-god="' + godToKickName + '"]');
godToKick.position({ of: $(this), my: 'left top', at: 'left bottom' });
godToKick.addClass('na');
}
$(this).attr('data-attached', ui.draggable.attr('data-god'));
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.removeClass('na');
// Если откомментить эту строчку после дропа
// элемент не будет отъезжать назад
// ui.draggable.draggable( 'option', 'revert', false );
}
// Собираем данные, которые ввёл пользователь
$('#initPuzzle').on('click', function() {
var yes = 'da';
if ($('#yes').val().length > 0){
yes = $('#yes').val();
}
var no = 'ja';
if ($('#no').val().length > 0){
no = $('#no').val();
}
var godsPositions = [0, 1, 2];
// По умолчанию
// 0 - Бог Правды
// 1 - Бог Лжи
// 2 - Бог Случая
if (!$('*[data-attached="none"]').length){
$('#godsContainer .item').each(function(n){
switch ($(this).attr('data-attached')){
case 'true':
godsPositions[0] = n;
break;
case 'false':
godsPositions[1] = n;
break;
case 'random':
godsPositions[2] = n;
break;
}
})
}
// Строим массив богов в диве с id=gods
finalGodsArray = initPuzzle(yes, no, godsPositions[0], godsPositions[1], godsPositions[2]);
$('#gods').children().remove();
for (var i=0; i<finalGodsArray.length; i++){
$('#gods').append('<div class="item ' + finalGodsArray[i].class + '">' + finalGodsArray[i].name + '</div>');
}
$('#init').fadeOut('fast');
$('#play').fadeIn('fast');
});
// Клик по копке "Опросить богов"
$('#checkGods').on('click', function(){
if (!$(this).hasClass('na')){
var htmlString = godsInterview(finalGodsArray);
$('#answers').append(htmlString);
$('#checkGods').addClass('na');
$('#replay').removeClass('na');
$('#gods').children().addClass('checked');
}
});
// Клик по копке "Сыграть еще раз"
$('#replay').on('click', function(){
if (!$(this).hasClass('na')){
location.reload();
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment