Модераторы: Sardar, Aliance
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Игра "Пятнашки", Игра "Пятнашки" или "Такен" 
:(
    Опции темы
PsiMagistr
Дата 29.1.2018, 12:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 479
Регистрация: 31.12.2009

Репутация: нет
Всего: 1



Ребята, готовый, свеженаписанный скрипт игры 15. 

Использован Canvas.  (HTML 5) С эффектом анимации движения.

Код наверное не самый лучший, но работоспособный.


Код

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/style.css">
    <title>Title</title>
    <script src="script/lib.js"></script>
</head>
<body>
<h3>Пятнашки</h3>
<div id="contaner">
    <div id="message"></div>
    <canvas width="240" height="240" id="canvas"></canvas>
    <button id="button">Смешать</button>
</div>
</body>
</html>



Код

#contaner{
   width:240px;
   height:240px;
   margin: 0 auto;

}

h3{
    text-align: center;
}



#canvas{
   // border: 2px solid;
    cursor:pointer;
}
button{
   width:100px;
   margin: 0 auto;
}

#message{
    width:220px;
    height:100px;
    padding:10px;
    border:1px solid black;
    margin-bottom: 10px;

}




Код

// объект игры

function Game(canvasSelector, buttonSelector, messageSelector, borderDiceColor, diceColor, diceWidth, fontString, borderZeroColor, zeroDiceColor, textColor,  zeroText) {
    var dices = []; // Массив координат
    var zero;
    var canvas = document.querySelector(canvasSelector); // Канвас
    var context = canvas.getContext('2d'); // Контекст
    var button = document.querySelector(buttonSelector); // Кнопка смешивания
    var msg = document.querySelector(messageSelector);
    var canvasWidth = canvas.getAttribute('width');
    var diceRow = canvasWidth / diceWidth;
    var dicesCount = diceRow * diceRow;
    var lastValue;
    var start = false;
  //  var n = {name:'Вася'};
    context.font = fontString; //Шрифт
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    function drawDice(x, y, txtValue , borderDiceColor, diceColor) { //Построение плашки
        var textX;
        var textY;
        context.strokeStyle = borderDiceColor;
        context.strokeRect(x, y, diceWidth, diceWidth);
        context.fillStyle = diceColor;
        context.fillRect(x + 1, y + 1, diceWidth - 2, diceWidth - 2);
        context.fillStyle =  textColor;

        if (x == 0) {
            textX = (1 + diceWidth - diceWidth / 2);
        }
        else {
            textX = (x + diceWidth - diceWidth / 2);
        }

        if (y == 0) {
            textY = (1 + diceWidth - diceWidth / 2);
        }
        else {
            textY = (y + diceWidth - diceWidth / 2);
        }
        if(txtValue) {
            context.fillText(txtValue, textX, textY);

        }
       // dices[count] =  {x:x, y: y, value: txtValue};

    }

    function drawGame() {
        var x = -diceWidth;
        var y = 0;
        for (var i = 1; i < dicesCount + 1; i++) {
            x += diceWidth;
            if (x > (diceRow - 1) * diceWidth) {
                x = 0;
                y += diceWidth;
            }
         if(i < dicesCount) {
             drawDice(x, y, i, borderDiceColor, diceColor);
             dices[i] = {x:x, y: y, value:i};

         }
         else{
             drawDice(x, y, zeroText, borderZeroColor, zeroDiceColor) ;
             zero = i;
             dices[i] = {x:x, y: y, value:zeroText};
         }



        }

        //button.onclick;
        randomazeDices();

    }

    function moveAnimationDice(dice){
       var direction;
       var timer;
       var clicedX = dices[dice].x;
       var clicedY = dices[dice].y;
        if(dices[dice].y == dices[zero].y && dices[dice].x == dices[zero].x - diceWidth ||
            dices[dice].x == dices[zero].x && dices[dice].y == dices[zero].y - diceWidth ||
            dices[dice].y == dices[zero].y &&  dices[dice].x == dices[zero].x + diceWidth ||
            dices[dice].x == dices[zero].x &&  dices[dice].y == dices[zero].y + diceWidth
        ) {
            if (!timer) {
                if (dices[dice].y == dices[zero].y && dices[dice].x == dices[zero].x - diceWidth) {
                    direction = 'right';
                }
                if (dices[dice].y == dices[zero].y && dices[dice].x == dices[zero].x + diceWidth) {
                    direction = 'left';
                }
                if (dices[dice].x == dices[zero].x && dices[dice].y == dices[zero].y + diceWidth) {
                    direction = 'up';
                }
                if (dices[dice].x == dices[zero].x && dices[dice].y == dices[zero].y - diceWidth) {
                    direction = 'down';
                }
                //  alert(direction);
                timer = setInterval(function () {
                    switch (direction) {
                        case 'right':
                            dices[dice].x += 2;
                            break;
                        case 'left':
                            dices[dice].x -= 2;
                            break;
                        case 'up':
                            dices[dice].y -= 2;
                            break;
                        case 'down':
                            dices[dice].y += 2;
                            break;
                    }
                    drawDice(clicedX, clicedY, zeroText, borderZeroColor, zeroDiceColor);
                    drawDice(dices[dice].x, dices[dice].y, dices[dice].value, borderDiceColor, diceColor);
                    if (dices[zero].x == dices[dice].x && dices[zero].y == dices[dice].y) {
                        clearInterval(timer);
                        dices[zero].value = dices[dice].value;
                        dices[dice].value = zeroText;
                        zero = dice;
                        dices[zero].x = clicedX;
                        dices[zero].y = clicedY;

                        function message(msgText) {
                            return function () {
                               // var msg = document.querySelector('#message');
                                lastValue = '';
                                // alert();
                                start = false;
                                msg.style.color = 'blue';
                                //  message.style.borderColor = 'black';
                                msg.innerHTML = msgText;
                            }
                        }



                        victory(message('Поздравляем, Вы достигли цели! Если хотите начать новую игру нажмите кнопочку "Смешать".'));
                    }

                }, 5);
            }
        }

    }

    function moveDice(dice){
        if(dices[dice].y == dices[zero].y && dices[dice].x == dices[zero].x - diceWidth ||
            dices[dice].x == dices[zero].x && dices[dice].y == dices[zero].y - diceWidth ||
            dices[dice].y == dices[zero].y &&  dices[dice].x == dices[zero].x + diceWidth ||
            dices[dice].x == dices[zero].x &&  dices[dice].y == dices[zero].y + diceWidth
        ){
            dices[zero].value = dices[dice].value;
            drawDice(dices[zero].x, dices[zero].y, dices[zero].value, borderDiceColor, diceColor);
            dices[dice].value = zeroText;
            drawDice(dices[dice].x, dices[dice].y, dices[dice].value, borderZeroColor, zeroDiceColor);
            zero = dice;
        }

    }

    function randomazeDices(){
        msg.style.color = 'black';
        var candidates = [];
        function randomInteger(min, max) {
            var rand = min + Math.random() * (max + 1 - min);
            rand = Math.floor(rand);
            return rand;
        }

        for(var j = 1; j < 3000; j++) {
            for (var i = 1; i < dicesCount + 1; i++) {
                if (dices[i].y == dices[zero].y && dices[i].x == dices[zero].x - diceWidth ||
                    dices[i].x == dices[zero].x && dices[i].y == dices[zero].y - diceWidth ||
                    dices[i].y == dices[zero].y && dices[i].x == dices[zero].x + diceWidth ||
                    dices[i].x == dices[zero].x && dices[i].y == dices[zero].y + diceWidth
                ) {
                    if(lastValue) {
                        //   alert('r');
                        if(dices[i].value != lastValue) {
                            candidates[candidates.length] = i;

                        }
                    }
                    else{
                        candidates[candidates.length] = i;
                    }
                }
            }



            var rand = randomInteger(0, candidates.length - 1);
            var t = candidates[rand];
            // alert(t);
            lastValue = dices[t].value;
            moveDice(candidates[rand]);
            //alert(lastValue);
        }
        start = true;
        var message = document.querySelector('#message');
        message.innerHTML = 'Кликом мыши на смежную с пустым местом фишку, переместите ее. <br> Необходимо упорядочить все фишки.';


    }

    drawGame();
 //   drawDice(dices[1].x, dices[1].y, zeroText, borderZeroColor, zeroDiceColor, zeroTextColor, 1);
   // alert(dices[16].value);

    function victory(func){
        var count = 0;
        var f = func || function(){};
        for(var i = 1; i < dicesCount; i++){
            if(dices[i].value == i){
                count++;
            }
            else{
                break;
            }
        }
        if(count == dicesCount-1){
           f();
        }
    }


    canvas.onclick = function(event){
        if(start) {
                 var index = Math.floor(event.offsetX / diceWidth) + Math.floor(event.offsetY / diceWidth) * diceRow + 1;
                 moveAnimationDice(index);



           // victory(message('Поздравляем, Вы достигли цели! Если хотите начать новую игру нажмите кнопочку "Смешать".'));
        }

    }

    button.onclick = randomazeDices;
}


window.onload = function () {
    var game = new Game('#canvas', '#button', '#message', 'white', '#708090', 60, 'bold 20px TimesNewRoman', 'white', '#FFB6C1', 'white', ''); //Канвас, кнопка, див сообщений, сторона квадрата, зеро-значение.


}



Не забудьте распределить файлы по нужным папкам:




Это сообщение отредактировал(а) PsiMagistr - 29.1.2018, 12:34

Присоединённый файл ( Кол-во скачиваний: 9 )
Присоединённый файл  animation.zip 8,18 Kb


--------------------
"Арфы нет? Возьмите бубен!

Ребята, будем жить!"

 (с) "В бой идут одни старики"

---

"ИЕ" - один из самых сумасшедших браузеров в нашей галактике.
PM MAIL   Вверх
zarubski
Дата 14.1.2019, 14:36 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 14.1.2019

Репутация: нет
Всего: нет



 smile  smile  smile 
PM MAIL   Вверх
ksnk
Дата 5.6.2019, 01:16 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


прохожий
****


Профиль
Группа: Комодератор
Сообщений: 6855
Регистрация: 13.4.2007
Где: СПб

Репутация: 2
Всего: 386



https://jsfiddle.net/noqty43m/
Зачем куда-то копировать , если есть фидл ? Скрипт слегка модифицирован, чтобы под фидлом запускался (отрезан window.onload и оформление html вне снаружи body)


--------------------
Человеку свойственно ошибаться, программисту свойственно ошибаться профессионально ! user posted image
PM MAIL WWW Skype   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Здесь публикуют скрипты, которые уже проверены в обсуждениях других тем (при этом полезно поставить ссылки на все смежные обсуждения) или переносятся кем-либо из модераторов по просьбе участников, если видно, что в результате обсуждения темы был написан полезный или интересный скрипт. Третий возможный вариант - участник форума публикует скрипт, заведомо известный как полезный и эффективный, для, возможно, небольшой доработки и обсуждения.
 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | JavaScript: Наши скрипты | Следующая тема »


 




[ Время генерации скрипта: 0.1165 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.