Редактирование: Крестики-нолики на js

Перейти к: навигация, поиск

Внимание! Вы не авторизовались на сайте. Ваш IP-адрес будет публично видимым, если вы будете вносить любые правки. Если вы войдёте или создадите учётную запись, правки вместо этого будут связаны с вашим именем пользователя, а также у вас появятся другие преимущества.

Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 6: Строка 6:
 
Группа 3630103/4  Кафедра Теоретической механики
 
Группа 3630103/4  Кафедра Теоретической механики
 
==Визуализация==
 
==Визуализация==
{{#widget:Iframe |url=https://gigantmisli228.github.io/XOgame/ |width=1000 |height=600 |border=1  }}
+
{{#widget:Iframe |url=https://gigantmisli228.github.io/XOgame/index.html |width=1000 |height=600 |border=1  }}
 
 
 
==Код программы==
 
==Код программы==
 
<div class="mw-collapsible mw-collapsed">
 
<div class="mw-collapsible mw-collapsed">
Строка 13: Строка 12:
 
<syntaxhighlight lang="javascript" line start="1" enclose="div">
 
<syntaxhighlight lang="javascript" line start="1" enclose="div">
  
var origBoard;
+
var area = document.getElementById('area');
 +
var cell = document.getElementsByClassName('cell');
 +
var currentPlayer = document.getElementById('curPlyr');
  
 +
var player = "x";
 +
var stat = {
 +
    'x': 0,
 +
    'o': 0,
 +
    'd': 0
 +
}
 +
var winIndex = [
 +
    [1,2,3],
 +
    [4,5,6],
 +
    [7,8,9],
 +
    [1,4,7],
 +
    [2,5,8],
 +
    [3,6,9],
 +
    [1,5,9],
 +
    [3,5,7]
 +
];
  
const huPlayer = 'O';
+
for(var i = 1; i <= 9; i++) {
const aiPlayer = 'X';
+
    area.innerHTML += "<div class='cell' pos=" + i + "></div>";
 +
}
  
const winCombos = [
+
for (var i = 0; i< cell.length; i++) {
    [0, 1, 2],
+
     cell[i].addEventListener('click', cellClick, false);
     [3, 4, 5],
+
}
    [6, 7, 8],
 
    [0, 3, 6],
 
    [1, 4, 7],
 
    [2, 5, 8],
 
    [0, 4, 8],
 
    [6, 4, 2]
 
]
 
  
const cells = document.querySelectorAll('.cell');
+
function cellClick() {
startGame();
 
 
  
function startGame() {
+
     var data = [];
     document.querySelector(".endgame").style.display = "none";
+
      
     origBoard = Array.from(Array(9).keys());
+
     if(!this.innerHTML) {
 
+
         this.innerHTML = player;
     for (let index = 0; index < cells.length; index++) {
+
    }else {
         cells[index].innerText = '';
+
         alert("Ячейка занята");
         cells[index].style.removeProperty('background-color');
+
         return;
         cells[index].addEventListener('click', turnClick, false);
 
 
     }
 
     }
}
 
  
function turnClick(square) {
+
    for(var i in cell){
 
+
        if(cell[i].innerHTML == player){
    if (typeof origBoard[square.target.id] == 'number') {
+
            data.push(parseInt(cell[i].getAttribute('pos')));
        turn(square.target.id, huPlayer)
+
        }
        if (!checkTie()) turn(bestSpot(), aiPlayer);
 
 
     }
 
     }
}
 
  
function turn(squareId, player) {
+
    if(checkWin(data)) {
    origBoard[squareId] = player;
+
        stat[player] += 1;
    document.getElementById(squareId).innerText = player;
+
        restart("Выграл: " + player);
    let gameWon = checkWin(origBoard, player);
+
     }else {
     if (gameWon) gameOver(gameWon)
+
        var draw = true;
}
+
        for(var i in cell) {
 
+
            if(cell[i].innerHTML == '') draw = false;
function checkWin(board, player) {
+
        }
    let plays = board.reduce((a, e, i) =>
+
         if(draw) {
        (e === player) ? a.concat(i) : a, []);
+
             stat.d += 1;
    let gameWon = null;
+
             restart("Ничья");
    for (let [index, win] of winCombos.entries()) {
 
         if (win.every(elem => plays.indexOf(elem) > -1)) {
 
             gameWon = {index: index, player: player};
 
             break;
 
 
         }
 
         }
 
     }
 
     }
  
     return gameWon;
+
     player = player == "x" ? "o" : "x";
updateStat();
+
    currentPlayer.innerHTML = player.toUpperCase();
 
}
 
}
  
function gameOver(gameWon) {
+
function checkWin(data) {
     for (let index of winCombos[gameWon.index]) {
+
     for(var i in winIndex) {
         document.getElementById(index).style.backgroundColor =
+
         var win = true;
         gameWon.player == huPlayer ? "blue" : "red";
+
         for(var j in winIndex[i]) {
    }
+
            var id = winIndex[i][j];
    for (var i = 0; i < cells.length; i++) {
+
            var ind = data.indexOf(id);
        cells[i].removeEventListener('click', turnClick, false);
 
    }
 
    declareWinner(gameWon.player == huPlayer ? "Вы выиграли!" : "Вы проиграли!")
 
updateStat();
 
}
 
  
function declareWinner(who) {
+
            if(ind == -1) {
    document.querySelector(".endgame").style.display = "block";
+
                win = false
    document.querySelector(".endgame .text").innerText = who;
+
            }
}
+
        }
 
 
function emptySquares() {
 
    return origBoard.filter(s => typeof s == 'number');
 
}
 
  
function bestSpot() {
+
        if(win) return true;
 
 
    return minimax(origBoard, aiPlayer).index;
 
}
 
 
 
 
 
function checkTie() {
 
    if (emptySquares().length == 0) {
 
        for (var i = 0; i < cells.length; i++) {
 
            cells[i].style.backgroundColor = "green";
 
            cells[i].removeEventListener('click', turnClick, false);
 
        }
 
        declareWinner("Ничья!");
 
        return true;
 
 
     }
 
     }
 
     return false;
 
     return false;
updateStat();
 
 
}
 
}
 
  
 
+
function restart(text) {
function minimax(newBoard, player) {
+
      
    var availSpots = emptySquares(newBoard);
+
     alert(text);
 
+
     for(var i = 0; i < cell.length; i++) {
    if (checkWin(newBoard, player)) {
+
         cell[i].innerHTML = '';
        return {score: -10};
 
     } else if (checkWin(newBoard, aiPlayer)) {
 
        return {score: 10};
 
     } else if (availSpots.length === 0) {
 
        return {score: 0}
 
    }
 
 
 
    var moves = [];
 
     for (let index = 0; index < availSpots.length; index++) {
 
        var move = {};
 
        move.index = newBoard[availSpots[index]];
 
        newBoard[availSpots[index]] = player;
 
 
 
        if (player == aiPlayer) {
 
            var result = minimax(newBoard, huPlayer);
 
            move.score = result.score;
 
        } else {
 
            var result = minimax(newBoard, aiPlayer);
 
            move.score = result.score;
 
        }
 
 
 
        newBoard[availSpots[index]] = move.index;
 
 
 
        moves.push(move);
 
    }
 
 
 
    var bestMove;
 
    if (player === aiPlayer) {
 
        var bestScore = -10000;
 
        for(var i = 0; i < moves.length; i++) {
 
            if (moves[i].score > bestScore) {
 
                bestScore = moves[i].score;
 
                bestMove = i;
 
            }
 
        }
 
    } else {
 
        var bestScore = 10000;
 
         for(var i = 0; i < moves.length; i++) {
 
            if (moves[i].score < bestScore) {
 
                bestScore = moves[i].score;
 
                bestMove = i;
 
            }
 
        }
 
 
     }
 
     }
 +
    updateStat();
 +
}
  
     return moves[bestMove];
+
function updateStat() {
 +
     document.getElementById('sX').innerHTML = stat.x;
 +
    document.getElementById('sO').innerHTML = stat.o;
 +
    document.getElementById('sD').innerHTML = stat.d;
 
}
 
}
</syntaxhighlight>
 
</div>
 
Вам запрещено изменять защиту статьи. Edit Создать редактором

Обратите внимание, что все добавления и изменения текста статьи рассматриваются как выпущенные на условиях лицензии Public Domain (см. Department of Theoretical and Applied Mechanics:Авторские права). Если вы не хотите, чтобы ваши тексты свободно распространялись и редактировались любым желающим, не помещайте их сюда.
Вы также подтверждаете, что являетесь автором вносимых дополнений или скопировали их из источника, допускающего свободное распространение и изменение своего содержимого.
НЕ РАЗМЕЩАЙТЕ БЕЗ РАЗРЕШЕНИЯ МАТЕРИАЛЫ, ОХРАНЯЕМЫЕ АВТОРСКИМ ПРАВОМ!

To protect the wiki against automated edit spam, we kindly ask you to solve the following CAPTCHA:

Отменить | Справка по редактированию  (в новом окне)