Match-match game
Типичные ошибки
Что не так?
function setTimer() {
timerConainer = document.getElementsByClassName("timer")[0];
timerConainer.style.visibility = 'visible';
timer = setInterval(() => {
let timeArr = timerConainer.innerHTML.split(":"),
h = timeArr[0],
m = timeArr[1],
s = timeArr[2];
if (s == 59) {
if (m == 59) {
if (h == 24) {
h = 0;
}
h++;
m = -1;
if (h < 10) h = "0" + h;
}
m++;
if (m < 10) m = "0" + m;
s = 0;
}
else s++;
if (s < 10) s = "0" + s;
timerConainer.innerHTML = h+":"+m+":"+s;
}, 1000);
}Game.prototype.showMessage = function showMessage (message) {
var _this = this;
var messageTextElement = document.createElement('p');
messageTextElement.innerText = message;
var messageTextWrapperElement = document.createElement('div');
messageTextWrapperElement.classList.add('game-message__text');
messageTextWrapperElement.appendChild(messageTextElement);
var messageMenuButtonElement = document.createElement('a');
messageMenuButtonElement.classList.add('game-message__button');
messageMenuButtonElement.innerText = 'Main menu';
messageMenuButtonElement.href = '#main-menu';
var messageAgainButtonElement = messageMenuButtonElement.cloneNode(true);
messageAgainButtonElement.innerText = 'Play again';
messageAgainButtonElement.href = '#game';
messageAgainButtonElement.addEventListener('click', function () {
_this.removeMessage();
_this.restart();
})
var messageButtonWrapperElement = document.createElement('div');
messageButtonWrapperElement.classList.add('game-message__button-wrapper');
messageButtonWrapperElement.appendChild(messageMenuButtonElement);
messageButtonWrapperElement.appendChild(messageAgainButtonElement);
var messageElement = document.createElement('div');
messageElement.classList.add('game-message');
messageElement.appendChild(messageTextWrapperElement);
messageElement.appendChild(messageButtonWrapperElement);
document.body.appendChild(messageElement);
this.messageElement = messageElement;
}let settings = document.getElementById('memory--settings-icon');
let modal = document.getElementById('memory--settings-modal');
var handleOpenSettings = function (event) {
event.preventDefault();
modal.classList.toggle('show');
if (stopwatch) {
stopwatch.pause();
}
};
settings.addEventListener('click', handleOpenSettings);
let reset = document.getElementById('memory--settings-reset');
var handleSettingsSubmission = function (event) {
event.preventDefault();
let cover = document.querySelector('input[type="radio"][name="select-cover"]:checked').value;
let grid = document.querySelector('input[type="radio"][name="select-label"]:checked').value;
let gridValues = grid.split('x');
let cards = $.initialize(Number(gridValues[0]), Number(gridValues[1]));
if (cards) {
document.getElementById('memory--settings-modal').classList.remove('show');
document.getElementById('memory--end-game-modal').classList.remove('show');
document.getElementById('memory--end-game-message').innerText = "";
document.getElementById('memory--end-game-score').innerText = "";
buildLayout($.cards, $.settings.rows, $.settings.columns, cover);
}
stopwatch.restart();
};
reset.addEventListener('click', handleSettingsSubmission);
let timeId = setInterval(function () {
if (cardWidth < 200) {
node.setAttribute('width', cardWidth + 'px');
cardWidth = cardWidth+4;
} else {
clearInterval(timeId);
store.faceTimer = undefined;
if (!!store._prevSelectedCard) {
if (store._prevSelectedCard[2] === cardState['faceId'] && !cardState['isOpen']) {
let prevNode = document.getElementById(store._prevSelectedCard[1]);
let cardStatePrev = store._matrix[store._prevSelectedCard[1]];
cardStatePrev['hasPair'] = true;
cardState['hasPair'] = true;
store._prevSelectedCard = null;
let timerId = setInterval(function () {
if (cardWidth > 0 || cardWidth === 0) {
node.setAttribute('width', cardWidth + 'px');
prevNode.setAttribute('width', cardWidth + 'px');
cardWidth = cardWidth-4;
} else {
node.setAttribute("style", 'visibility:hidden');
prevNode.setAttribute("style", 'visibility:hidden');
clearInterval(timerId);
function isTrue(item) {
return item.hasPair == true;
}
if (store._matrix.every(isTrue)) {
stopTimer("winner");
alert('YOU WINNER');
}
}
}, 5);
} else { /* перемешать массив */
function shuffle(arr) {
let r_i; // случайный индекс
let v; // временная переменная
for (let i = 0; i < arr.length-1; i++) {
/* получаем случайный индекс (кроме последнего) */
r_i = random(0, arr.length-1);
/* меняем местами случайный элемент массива с последним */
v = arr[r_i];
arr[r_i] = arr[arr.length-1];
arr[arr.length-1] = v;
}
return arr;/* Я посвящаю весь свой код, всю работу своей жене Дарлин, которой придётся содержать self, наших childs(3) & @, когда это пойдет в паблик. */
// variable i with value 5
// If you want you can change the value
// Be brave
// TODO: Change to const in production
// Do not change the value, other numbers won't compile
var i = 5;function startGame() {
document.getElementById('description').style.display = 'none';
document.getElementById('congrats').style.display= 'none';
document.getElementById('game').style.display = 'block';
document.getElementById('game-field').style.display= 'block';
timer.classList.remove('finished');
timerMinutes.innerHTML = '00';
timerSeconds.innerHTML = '00';
timerHours.innerHTML = '00';
gameInstance = new PonyMatchGame(selectedDifficulty, selectedShirt);
gameInstance.start(time => {
let hours = Math.floor(time / 3600);
let minutes = Math.floor(time / 60);
let seconds = time - minutes * 60;
timerHours.innerHTML = hours < 10 ? '0' + hours : hours;
timerMinutes.innerHTML = minutes < 10 ? '0' + minutes : minutes;
timerSeconds.innerHTML = seconds < 10 ? '0' + seconds : seconds;
});
field.innerHTML = '';
for (let i = 0; i < gameInstance.difficulty.height; i++) {
let row = document.createElement('div');
row.classList.add('game-row');
for (let j = 0; j < gameInstance.difficulty.width; j++) {
let card = document.createElement('div');
card.classList.add('card');
card.id = 'card-' + i + '-' + j;
card.addEventListener('click', () => {
let id = card.id.split('-');
card.classList.add('opened');
let result = gameInstance.openCard(id[1], id[2]);
setTimeout(() => {
if (result) {
if (result.close) {
for (let closed of result.close) {
document.getElementById('card-' + closed.row + '-' + closed.column).classList.remove('opened')
}
}
if (result.match) {
for (let matched of result.match) {
document.getElementById('card-' + matched.row + '-' + matched.column).classList.add('matched')
}
}
if (result.isFinished) {
setTimeout(() => {
timer.classList.add('finished');
document.getElementById('game-field').style.display= 'none';
document.getElementById('congrats').style.display= 'block';
}, 600)
}
}
}, 600)
});
let shirt = document.createElement('div');
shirt.classList.add('card-image', 'card-shirt');
shirt.style.backgroundImage = 'url(' + gameInstance.shirt + ')';
card.appendChild(shirt);
let pattern = document.createElement('div');
pattern.classList.add('card-image', 'card-pattern');
pattern.style.backgroundImage = 'url(' + gameInstance.field[i][j].pattern + ')';
card.appendChild(pattern);
row.appendChild(card);
}
field.appendChild(row);
}
}function startGame() {
document.getElementById('description').style.display = 'none';
document.getElementById('congrats').style.display= 'none';
document.getElementById('game').style.display = 'block';
document.getElementById('game-field').style.display= 'block';
timer.classList.remove('finished');
timerMinutes.innerHTML = '00';
timerSeconds.innerHTML = '00';
timerHours.innerHTML = '00'; constructor(difficulty, shirt) {
this.difficulty = config.difficulies[difficulty];
this.shirt = config.shirts[shirt];
this.field = [];
for (let i = 0; i < this.difficulty.height; i++) {
this.field[i] = [];
for (let j = 0; j < this.difficulty.width; j++) {
this.field[i][j] = null;
}
}let clearSelected = function (list) {
for (let i = 0; i < list.length; i++) {
if (list[i].style.backgroundColor === ("red")) {
list[i].style.backgroundColor = "#96d1f8";
}
}
};if (isContainOpenCards(cardsPlaces)) {
this._border.place.style.display = "block";
this._border.place.style.fontSize = " 5em";
this._border.place.style.padding = "20px";
this._border.place.textContent = "YOU ARE WINNER!!!";
clearInterval(interval);
} setCards(cardView) {
let countCards = this._border.cells;
let i = 0;
this.cardDeck = new CollectionCard(cardView).getCardsDeck(countCards);
}constructor(backView) {
this.backView = backView;
const defaultImagePath = "./images/cars/";
const firstImagePath = "./images/emoji/";
const secondImagePath = "./images/minions/";
this._collection = (backView === DEFAULT_CARD) ?
[defaultImagePath + "2.png", defaultImagePath + "2-1.png", defaultImagePath + "2-2.png"
, defaultImagePath + "2-3.png", defaultImagePath + "2-4.png", defaultImagePath + "2-5.png"
, defaultImagePath + "2-6.png", defaultImagePath + "2-7.png", defaultImagePath + "2-8.png"
, defaultImagePath + "2-1.png", defaultImagePath + "2-2.png", defaultImagePath + "2-3.png"]
: (backView === FIRST_CARD) ?
[firstImagePath + "1-1.png", firstImagePath + "1-2.png", firstImagePath + "1-3.png", firstImagePath + "1-4.png"
, firstImagePath + "1-5.png", firstImagePath + "1-6.png", firstImagePath + "1-7.png"
, firstImagePath + "1-8.png", firstImagePath + "1-1.png"
, firstImagePath + "1-2.png", firstImagePath + "1-3.png", firstImagePath + "1-4.png"]
:
[secondImagePath + "3-1.png", secondImagePath + "3-2.png", secondImagePath + "3-3.png", secondImagePath + "3-4.png"
, secondImagePath + "3-5.png", secondImagePath + "3-6.png", secondImagePath + "3-7.png"
, secondImagePath + "3-8.png", secondImagePath + "3-9.png",
secondImagePath + "3-10.png", secondImagePath + "3-11.png", secondImagePath + "3-12.png"]
}createGame() {
let player, level, story;
player = document.getElementById('input-name').value;
player = (player && (player!== ' ')&& (player!== ' ')&& (player!== ' ')&& (player!== ' '))? player : model.player.current;
level = document.getElementById('area-radio').innerHTML;
let i;
for (i = 0; i < model.levels.list.length; i++) {
if (level === model.levels.list[i]) {
break;
}
}
level = i;
for (i = 0; i < model.stories.list.length; i++) {
if (document.getElementById(model.stories.list[i]).getAttribute('class') === view.storiesDefaultClass + view.storySelectedClass) {
story = i;
}
}
model.createGame(player, level, story);
}, let innerContent ='<main>\n' +
' <h1 class="header-game"><span>Match Match</span> <span>Game</span></h1>\n' +
' <section>\n' +
' </section>\n' +
'</main>';
let innerContentPageMain = '<a class="button button-l single" id="'+ model.page.newGame +'">Play</a>\n' +
' <a class="button button-m row-3" id="'+ model.page.rules +'">Rules</a>\n' +
' <a class="button button-m row-3" id="'+ model.page.score +'">Score</a>\n' +
' <a class="button button-m row-3" id="'+ model.page.about +'">About</a>';
let innerContentPageRules = '<p>1. Start a new game</p>\n' +
' <p> 2. Click cards to see their picture</p>\n' +
' <p> 3. Match the same pictures in two clicks</p>\n' +
' <p> 4. Find all pairs to complete the game</p>\n' +
' <p> 5. Achieve the best time result</p>\n' +
' <a class="button button-m single" id="'+ model.page.home +'">OK</a>';let innerContent = `
<main>
<h1 class="header-game"><span>Match Match</span> <span>Game</span></h1>
//Do you real need section?????
<section>
</section>
</main>`;
let innerContentPageMain = `
<a class="button button-l single" id="${model.page.newGame}">Play</a>
<a class="button button-m row-3" id="${model.page.rules}">Rules</a>
<a class="button button-m row-3" id="${model.page.score}">Score</a>
<a class="button button-m row-3" id="${model.page.about}">About</a>`;if (check[0].getAttribute('value') == check[1].getAttribute('value')) {
check[0].style.opacity = 0;
check[1].style.opacity = 0;
check[0].style.visibility = 'hidden';
check[1].style.visibility = 'hidden';
score += 2;
check = [];
touchCard.addEventListener('click', openCard);
}function lowGame() {
menu.style.display = 'none';
menuButton.style.visibility = 'visible';
level1.style.display = 'flex';
}
function mediumGame() {
menu.style.display = 'none';
menuButton.style.visibility = 'visible';
level2.style.display = 'flex';
}
function hardGame() {
menu.style.display = 'none';
menuButton.style.visibility = 'visible';
level3.style.display = 'flex';
}....
<section class="level3">
<div id="memory_board3" ></div>
</section>
<section class="gameover">
<img src="img/win.png">
</section>
<script>
var menu = document.querySelector('.menu '),
level1 = document.querySelector('.level1'),
lowLevel = document.querySelector('.level1_button'),
level2 = document.querySelector('.level2'),
....winGame(){
if ((Array.from(document.querySelectorAll('.flip-container-disappear'))).length
=== this.size.x*this.size.y){
this.root.innerHTML = `<h2 class = "win_message">Congratulations! You win!<h2>
<p class="game_results">Your results: ${this.timeFormat(this.time)}</p>
<button class = 'btn-play-again'>Play again</button>`;
document.querySelector('.btn-play-again').addEventListener('click', playAgain);
this.isWin = true;
function playAgain(e){
e.preventDefault();
window.location.reload();
}
}
}
function playAgain(e) {
e.preventDefault();
window.location.reload();
}document.body.lastElementChild.children[this.flipArray[1]].querySelector('.flipper').classList.toggle('flip');serializeFinal(delay){
var sec = Math.floor(delay / 1000);
--sec;
var min = Math.floor(sec / 60);
var second = sec - min * 60;
if (min < 10) min = "0" + min;
if (second < 10) second = "0" + second;
var time = min + ":" + second;
return time
}function fNewBoard(difficulty){
memory_array =[];
var output = '';
gameField.innerHTML = output;
for (var q = 0; q<difficulty; q++){
memory_array[q] = etalon_array[q];
}
memory_array = memory_array.concat(memory_array);
memory_array.sort(compareRandom);
for (var i = 0; i < memory_array.length; i++){
var a = document.createElement("button"),
b = document.createElement("div"),
c = document.createElement("div"),
d = document.createElement("div");
a.setAttribute("id",'x'+i);
b.setAttribute("id",'y'+i);
a.classList.add("flip");
b.classList.add("card");
c.classList.add("face");
c.classList.add("front");
d.classList.add("face");
d.classList.add("back");
c.style.backgroundImage = 'url("img/'+skirt+'.jpg")';
gameField.appendChild(a);
a.appendChild(b);
b.appendChild(c);
b.appendChild(d);
d.style.backgroundImage = 'url("'+memory_array[i]+'")';
}
for(var j = 0; j < memory_array.length; j++){
var el1 = document.getElementById('x'+j);
el1.addEventListener("click",fFlip);
}
}(function() {
let startButton = document.querySelector('.start-game-button');
startButton.addEventListener('click', startGameClicked);
function startGameClicked() {
let difficulty = document.querySelector('[name="game-difficulty"]:checked').value;
let cardBack = document.querySelector('[name="card-back"]:checked').value;
var game = new Game(cardBack, difficulty);
game.start();
}
})()const DEFAULT_LEVEL = 1;
const MIDDLE_LEVEL = 2;
const HARD_LEVEL = 3;
const DEFAULT_CARD = "../images/card-back/card-back-default.png";
const FIRST_CARD = "../images/card-back/card-back-fireside.png";
const SECOND_CARD = "../images/card-back/card-back-legend.png";
const GAME_BORDER = "gameBorder";
let interval = undefined;
let currentLevel = DEFAULT_LEVEL;
let currentBackCard = DEFAULT_CARD;
let game = undefined;
let levels = document.getElementById("DROPDOWN-LEVELS-ID").children;
let backCards = document.getElementById("DROPDOWN-BACK-CARDS-ID").children;
document.getElementById("MENU-ID").addEventListener("click", () => {
if (game !== undefined) {
document.querySelector("main").removeChild(document.getElementById(GAME_BORDER));
game.close();
game = undefined;
document.querySelector("section").style.display = "initial";
}
dropUp();
});На что стоит обратить внимание?
class Timer {
constructor() {
this.timerElements = [];
this.ticker = 1000;
this.updateTimer = this.updateTimer.bind(this);
}
/**
*
* Init timer
*
*/
init() {
this.startedTimeMs = Date.now();
}
/**
*
* Turn 'delay' into 'hh:mm:ss'
* @param delay - this option turns into 'hh:mm:ss'
*
*/
serialize(delay) {
let seconds = parseInt((delay / 1000) % 60);
let minutes = parseInt((delay / (1000 * 60)) % 60);
let hours = parseInt((delay / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return `${hours}:${minutes}:${String(seconds)}`;
}Match-match game
By Anna Protasevich
Match-match game
Разбор типичных ошибок по игре match-match game
- 533