Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #21 (permalink)  
Старый 18.05.2021, 19:12
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

Сообщение от prototip
при многократном нажатии на кнопку start скорость игры увеличивается с каждым нажатием,
исправлено, строка 100, #18.
Ответить с цитированием
  #22 (permalink)  
Старый 18.05.2021, 19:25
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

Сообщение от prototip
low, medium, hight
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <style type="text/css">
        #canvas {
            width: 300;
            height: 300;
            border: 2px solid black;
            margin: 40px;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="300" height="300"></canvas>

    <label for="height">Высота:</label>
    <input type="text" class="inputText" id="height" value="147" />
    <label for="width">Ширина:</label>
    <input type="text" class="inputText" id="width" value="147" />
    <input type="button" value="Создать поле" class="btn red" id="create" />
    <p>Таймер: <span id="count">0</span></p>
    <button id="start">Start</button>
    <button id="pause">Pause</button>
    <button id="stop">Stop</button>
    <label>Speed:</label>
     <label><input type="radio" name="speed"  value="800"/>low</label>

     <label><input type="radio" name="speed" value="300" checked/>medium</label>

     <label><input type="radio" name="speed"  value="100"/>hight</label>

    <script>
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        let widthInput = document.getElementById("width");
        let heightInput = document.getElementById("height");
        let count = document.getElementById('count');
        let width, height, n, m;

        let xRect = 10;
        let yRect = 10;

        let mas = [];
        let timer;

        let maxWidth = 1000;
        let maxHeight = 1000;


        canvas.onclick = function(event) {
            event.stopPropagation();
            let x = event.offsetX;
            let y = event.offsetY;
            x = Math.floor(x / xRect);
            y = Math.floor(y / yRect);
            mas[y][x] = 1;
            drawField();
        };

        function resizeCanvas() {
            width = Math.min(widthInput.value, maxWidth);
            height = Math.min(heightInput.value, maxHeight);
            let str = "";
            if(width == maxWidth) str += ` Установлена максимальная ширина поля игры ${maxWidth}`
            if(height == maxHeight) str += ` Установлена максимальная высота поля игры ${maxWidth}`
            if(str) alert(str);
            width = Math.trunc(width/xRect) * xRect;
            height = Math.trunc(height/yRect) * yRect;

            canvas.width = widthInput.value = width;
            canvas.height = heightInput.value = height;

            n = width / xRect;
            m = height / yRect;

            goLife();
        }

        function goLife() {
            for (let i = 0; i < m; i++) {
                mas[i] = [];
                for (let j = 0; j < n; j++) {
                    mas[i][j] = 0;
                }
            }
        }
        resizeCanvas();

        function drawField() {

            ctx.clearRect(0, 0, width, height);
            for (let i = 0; i < m; i++) {
                for (let j = 0; j < n; j++) {

                    if (mas[i][j] === 1) {
                        ctx.fillRect(j * xRect, i * yRect, xRect, yRect);
                    }
                }
            }
        }

        function startLife() {
            pauseLife();
            let mas2 = [];
            for (let i = 0; i < m; i++) {
                mas2[i] = [];
                for (let j = 0; j < n; j++) {
                    let neighbors = [-1, 1].reduce((a, b) => {
                        b = mas[i + b];
                        if (b === undefined)
                            return a;
                        let num = b[j];
                        if (b[j + 1] !== undefined) {
                            num += b[j + 1]
                        }
                        if (b[j - 1] !== undefined) {
                            num += b[j - 1]
                        }
                        return a + num;
                    }, 0);
                    neighbors = [-1, 1].reduce((a, b) => a += mas[i][j + b] !== undefined && mas[i][j + b], neighbors);
                    mas2[i][j] = +(neighbors == 3 || (mas[i][j] && neighbors == 2));
                }
            }
            mas = mas2;
            drawField();
            count.innerHTML++;
            const delay = document.querySelector("[name='speed']:checked").value;
            timer = setTimeout(startLife, delay);
        }

        function pauseLife() {
            clearInterval(timer)
        }

        function stopLife() {
            pauseLife();
            goLife();
            drawField();
            count.innerHTML = 0;
        }

        document.getElementById("create").onclick = resizeCanvas;
        document.getElementById("start").onclick = startLife;
        document.getElementById("pause").onclick = pauseLife;
        document.getElementById("stop").onclick = stopLife;
    </script>
</body>

</html>
Ответить с цитированием
  #23 (permalink)  
Старый 18.05.2021, 19:42
Аспирант
Отправить личное сообщение для prototip Посмотреть профиль Найти все сообщения от prototip
 
Регистрация: 15.05.2021
Сообщений: 35

рони,
Интересное решение, не думал что решается так просто, пробовал сделать через условия, но получалось ерунда. Спасибо
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как добавить уникальный идентификатор для нового поля формы? javascript_pupil Общие вопросы Javascript 4 19.12.2020 13:06
Изменение текста при изменении содержимого поля input Win_D Элементы интерфейса 2 14.01.2018 00:45
Изменение поля input через console. Заплачу! Неумелый Работа 0 25.11.2015 16:26
Изменение value поля после событии change saxap jQuery 3 22.02.2013 10:55
Подскажите событие любого изменения поля Rooner jQuery 3 16.10.2012 17:38