Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 07.06.2020, 12:40
Интересующийся
Отправить личное сообщение для s4meone Посмотреть профиль Найти все сообщения от s4meone
 
Регистрация: 07.06.2020
Сообщений: 15

Почему не исчезает последняя цифра?
Приветсвую, есть следующий код:
var mili = 0.0;
var time = document.getElementById("time");
function plusMil() {
  mili += 0.01;
  time.innerHTML = Math.floor(mili * 100) / 100;
}
let interval;
const cells = Array.from(document.querySelectorAll("td"));
let nums = Array.from(Array(50).keys()).map((el) => el + 1);
let f = 0;
cells.forEach((cell) => {
  const i = Math.floor(Math.random() * (25 - f));
  cell.textContent = nums[i];
  nums.splice(i, 1);
  f++;
});
let current = 1;
document.querySelector("table").addEventListener("click", function (event) {
  const td = event.target.closest("td");
  if (+td.textContent !== current) {
    return;
  } else {
    const i = nums.indexOf(+td.textContent);
    if (i !== -1) {
      nums.splice(0, 1);
    }
    if (+td.textContent == 1) {
      interval = setInterval(plusMil, 10);
    }
    if (+td.textContent == 50) {
      clearInterval(interval);
      return;
    }
    const m = Math.floor(Math.random() * nums.length);
    td.textContent = nums[m];
    nums.splice(m, 1);
    current++;
  }
});

Код:
<!DOCTYPE html>
<html lang="en">
<head>
	<link href="css/style.css" rel="stylesheet">
	<meta charset="UTF-8">
	<title>test</title>
</head>
<body>
    <div class="zone">
          <div id="time">0.000</div>
          <a href="index.html">restart</a>
    </div>
    <table>
          <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
      </tr>
      <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
      </tr>
      <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
      </tr>
      <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
      </tr>
      <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
      </tr>
</table>
</div>
</body>
</html>

<script src="js/script.js"></script>
Проблема в том, что последняя цифра (т.е 50) не исчезает при нажатии на неё, и я никак не могу понять в чем проблема. Может быть вы поможете мне решить данную задачку?
Ответить с цитированием
  #2 (permalink)  
Старый 07.06.2020, 12:44
Интересующийся
Отправить личное сообщение для s4meone Посмотреть профиль Найти все сообщения от s4meone
 
Регистрация: 07.06.2020
Сообщений: 15

Просто убрал return, извиняюсь за беспокойство C:
Ответить с цитированием
  #3 (permalink)  
Старый 07.06.2020, 12:53
Интересующийся
Отправить личное сообщение для s4meone Посмотреть профиль Найти все сообщения от s4meone
 
Регистрация: 07.06.2020
Сообщений: 15

хм, а не подскажете, как сделать так, чтобы вместо цифр появлялись буквы (От А до Я) по тому же принципу. Например поле будет 16 на 16 (просто везде по одному <td> вырезать). И также первые 16 букв (кроме ё) появляются в разброс. Просто не приходит ничего в голову, как напихать кучу if-ов, типа если 1, то а, если 2, то б.
Ответить с цитированием
  #4 (permalink)  
Старый 07.06.2020, 19:11
Профессор
Отправить личное сообщение для laimas Посмотреть профиль Найти все сообщения от laimas
 
Регистрация: 14.01.2015
Сообщений: 12,990

Можно взять массив 'А' ... 'Я', получать случайный его индекс, по которому извлекать из массива символ и удаляя его из массива.
Ответить с цитированием
  #5 (permalink)  
Старый 07.06.2020, 19:32
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

gameTable алфавит
Сообщение от s4meone
чтобы вместо цифр появлялись буквы
любой массив данных, любой размер таблицы.
<!doctype html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
 td{
     border: 1px solid hsla(240, 100%, 40%, 1);
     height: 45px;
     width: 45px;
     text-align: center;
     font-size: 28px;
     transition: 1s;
 }
 td.collapsing{
     transform: scale(0);
 }

 </style>
</head>
<body>
<script>
class gameTable {
    constructor(arr, colls, rows) {
        this.colls = colls;
        this.rows = rows;
        this.length = this.colls * this.rows;
        this.index = 0;
        this.array = arr;
        this.contentTd = this.createContent(this.array, this.length);
        this.table = document.createElement('table');
        this.createTableHtml();
        this.table.addEventListener("click", this.clickHandler.bind(this));
    }
    shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            let j = Math.trunc(Math.random() * i);
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }
    createContent(array, length) {
        let content = [];
        for (let i = 0; i < array.length;) {
            let temp = array.slice(i, i += length);
            temp = this.shuffleArray(temp);
            content = content.concat(temp);
        }
        return content
    }
    createTableHtml() {
        this.index = 0;
        for (var i = 0; i < this.rows; i++) {
            let row = this.table.insertRow();
            for (var k = 0; k < this.colls; k++) {
                let cell = row.insertCell();
                cell.textContent = this.contentTd[this.index++] || '';
            }
        }
        this.index = 0;
    }
    clickHandler({target}) {
        target = target.closest('td');
        if (!target) return;
        let txt = target.textContent;
        if (txt == this.array[this.index]) {
            txt = this.contentTd[this.index + this.length] || '';
            target.textContent = txt;
            target.classList.toggle('collapsing', !txt);
            this.index++;
        }
        if (this.index == this.array.length) alert('End');
    }
}
let game = new gameTable('АБВГДЕЁЖЗИЙКЛМНОП'.split(''), 3, 4);
document.body.appendChild(game.table);
</script>
</body>
</html>

Последний раз редактировалось рони, 07.06.2020 в 23:08.
Ответить с цитированием
  #6 (permalink)  
Старый 08.06.2020, 06:27
Интересующийся
Отправить личное сообщение для s4meone Посмотреть профиль Найти все сообщения от s4meone
 
Регистрация: 07.06.2020
Сообщений: 15

Спасибо, не могли бы помочь теерь с таймером?
Чего-то не работает он
<!doctype html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <link href="css/style.css" rel="stylesheet">
    <title>Document</title>
</head>
<body>
  <div id="time">0.000</div>
<script>
var mili = 0.0;
var time = document.getElementById("time");
function plusMil() {
  mili += 0.01;
  time.innerHTML = Math.floor(mili * 100) / 100;
}
let interval
class gameTable {
    constructor(arr, colls, rows) {
        this.colls = colls;
        this.rows = rows;
        this.length = this.colls * this.rows;
        this.index = 0;
        this.array = arr;
        this.contentTd = this.createContent(this.array, this.length);
        this.table = document.createElement('table');
        this.createTableHtml();
        this.table.addEventListener("click", this.clickHandler.bind(this));
    }
    shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            let j = Math.trunc(Math.random() * i);
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }
    createContent(array, length) {
        let content = [];
        for (let i = 0; i < array.length;) {
            let temp = array.slice(i, i += length);
            temp = this.shuffleArray(temp);
            content = content.concat(temp);
        }
        return content
    }
    createTableHtml() {
        this.index = 0;
        for (var i = 0; i < this.rows; i++) {
            let row = this.table.insertRow();
            for (var k = 0; k < this.colls; k++) {
                let cell = row.insertCell();
                cell.textContent = this.contentTd[this.index++] || '';
            }
        }
        this.index = 0;
    }
    clickHandler({target}) {
        target = target.closest('td');
        if (!target) return;
        let txt = target.textContent;
        if (txt == this.array[this.index]) {
            txt = this.contentTd[this.index + this.length] || '';
            target.textContent = txt;
            target.classList.toggle('collapsing', !txt);
            this.index++;
        if (+td.textContent == 'А'){
          interval=setInterval(plusMil, 10);
        }
        if (+td.textContent == 'Я'){
          clearInterval(interval)
        }
        }
    }
}

let game = new gameTable('АБВГДЕЁЖЗИЙКЛМНОП'.split(''), 3, 4);
document.body.appendChild(game.table);
</script>
</body>
</html>
Ответить с цитированием
  #7 (permalink)  
Старый 08.06.2020, 09:00
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

Сообщение от s4meone
== 'Я'
нет такой буквы!!!
Ответить с цитированием
  #8 (permalink)  
Старый 08.06.2020, 09:03
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

игра алфавит
s4meone,
<!doctype html>
<html lang="ru">
<head>
        <meta charset="UTF-8">
        <title>Document</title>
  <style type="text/css">
 td{
     border: 1px solid hsla(240, 100%, 40%, 1);
     height: 45px;
     width: 45px;
     text-align: center;
     font-size: 28px;
     transition: 1s;
 }
 td.collapsing{
     transform: scale(0);
 }
 </style>
</head>
<body>
<script>
class gameTable {
    constructor(arr, colls, rows) {
        this.colls = colls;
        this.rows = rows;
        this.length = this.colls * this.rows;
        this.index = 0;
        this.array = arr;
        this.contentTd = this.createContent(this.array, this.length);
        this.table = document.createElement('table');
        this.createTableHtml();
        this.table.addEventListener("click", this.clickHandler.bind(this));
        this.time = 0;
    }
    shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            let j = Math.trunc(Math.random() * i);
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }
    createContent(array, length) {
        let content = [];
        for (let i = 0; i < array.length;) {
            let temp = array.slice(i, i += length);
            temp = this.shuffleArray(temp);
            content = content.concat(temp);
        }
        return content
    }
    createTableHtml() {
        const tHead = this.table.createTHead();
        let row = tHead.insertRow();
        let cell = row.insertCell();
        cell.colSpan = this.colls
        cell.textContent = '0.0';
        this.timeTd = cell;
        this.index = 0;
        const tBody = this.table.createTBody();
        for (var i = 0; i < this.rows; i++) {
            row = tBody.insertRow();
            for (var k = 0; k < this.colls; k++) {
                cell = row.insertCell();
                cell.textContent = this.contentTd[this.index++] || '';
            }
        }
        this.index = 0;
    }
    clickHandler({target}) {
        target = target.closest('td');
        if (!target) return;
        let txt = target.textContent;
        if (txt == this.array[this.index]) {
            if (txt == this.array[0]) {
                this.interval = setInterval(() => {
                    this.time += 0.01;
                    this.timeTd.textContent = (Math.floor(this.time * 100) / 100).toFixed(1);
                }, 10);
            }
            if (txt == this.array[this.array.length - 1]) {
                clearInterval(this.interval)

            }
            txt = this.contentTd[this.index + this.length] || '';
            target.textContent = txt;
            target.classList.toggle('collapsing', !txt);
            this.index++;
        }
    }
}
let game = new gameTable('АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'.split(''), 3, 4);
document.body.appendChild(game.table);
</script>
</body>
</html>

Последний раз редактировалось рони, 08.06.2020 в 09:56.
Ответить с цитированием
Ответ



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

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


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Свойства объекта, методы и this. Почему свойство вызывается с () ? jsuse Общие вопросы Javascript 2 04.11.2011 20:39
Prototype. Одноблочное определение псевдокласса. Литеральная форма не робит. Почему? GuardCat Общие вопросы Javascript 6 03.10.2011 13:46
Почему не определяется втарая переменная? Арман Общие вопросы Javascript 3 09.04.2011 11:14
Почему в Opera исчезает курсор при нажатии клавиши Esc ? Маэстро Opera, Safari и др. 3 23.11.2010 16:31
Почему это работает? (инклуд JS в JS) Василий Б. Общие вопросы Javascript 4 11.06.2010 12:41