Demo

Tic Tac Toe Game

Experience the classic Tic Tac Toe game reimagined with LemonadeJS. Two players take turns marking spaces in a three-by-three grid with X or O. The first player to get three marks in a row wins!


live
<html>
<script src="https://cdn.jsdelivr.net/npm/lemonadejs/dist/lemonade.min.js"></script>
<div id='root'></div>
<script>
function Tictactoe() {
    const self = this;

    let text = [
        'can start the game',
        'turn to play',
        'won the game',
    ]
    self.players = [ 'O','X' ];

    const checkMatching = function(a, b, c) {
        if (self.board[a].player &&
            self.board[a].player === self.board[b].player &&
            self.board[b].player === self.board[c].player) {
            return true;
        }
        return false;
    }

    const isWinner = function() {
        return (checkMatching(0, 1, 2) || checkMatching(3, 4, 5) || checkMatching(6, 7, 8) ||
                checkMatching(0, 3, 6) || checkMatching(1, 4, 7) || checkMatching(2, 5, 8) ||
                checkMatching(0, 4, 8) || checkMatching(2, 4, 6));
    }

    self.click = function(e) {
        if (e.target.tagName === 'SPAN') {
            if (self.winner) {
                alert(self.title.textContent);
            } else {
                if (!e.target.textContent) {
                    let index = Array.prototype.indexOf.call(e.target.parentNode.children, e.target);
                    self.board[index].player = self.player;
                    self.text = text[1];
                    if (isWinner()) {
                        self.text = text[2];
                        self.winner = true;
                        alert(self.title.textContent);
                    } else {
                        self.player = self.player ? 0 : 1;
                    }
                }
            }
        }
    }

    self.reset = function() {
        self.player = 0;
        self.text = text[0];
        self.winner = false;
        self.board = [{},{},{},{},{},{},{},{},{}];
    }

    self.reset();

    return `<div class="tictactoe">
        <div class="title" :ref="self.title">{{self.players[self.player]}} {{self.text}}</div>
        <div :loop="self.board" class="board" onclick="self.click">
            <span>{{self.parent.players[self.player]}}</span>
        </div><br/>
        <input type="button" onclick="self.reset" value="Reset the game" />
    </div>`;
}

lemonade.render(Tictactoe, document.getElementById('root'));
</script>

<style>
.tictactoe {
    max-width: 244px;
}

.tictactoe .title {
    padding: 20px;
    text-align: center;
}

.tictactoe .board {
    display: grid;
    gap: 1px;
    grid-template-columns: repeat(3, 1fr);
}

.tictactoe .board > span {
    margin: 2px;
    width: 80px;
    height: 80px;
    background-color: #ddd;
    line-height: 80px;
    text-align: center;
    font-size: 22px;
    cursor: pointer;
}

.tictactoe button {
    width: 100%;
}
</style>
</html>