JSFiddle - React, Tailwind, and code Playground
by Eric Abutaliev
HTML
<button id="start">Начать игру!</button>
<button id="restart">Играть еще!</button>
<div id="map"></div>
CSS
#start {
position: absolute;
width: 200px;
height: 100px;
border-radius: 20px;
background: green;
color: white;
font-size: 36px;
}
#restart {
display: none;
position: absolute;
width: 200px;
height: 100px;
border-radius: 20px;
background: green;
color: white;
font-size: 36px;
}
#map {
display: none;
height: 100%;
}
.area {
border: 1px solid black;
width: 98px;
height: 98px;
float:left;
cursor: pointer;
}
.area:nth-child(2n) {
border: 1px solid black;
width: 98px;
height: 98px;
float:left;
background: grey;
cursor: pointer;
}
.pressX:nth-child(n) {
line-height: 100px;
text-align: center;
font-size: 100px;
font-weight: bold;
color: red;
cursor: default;
}
.pressX:before {
content:"X";
}
.pressO:nth-child(n) {
line-height: 100px;
text-align: center;
font-size: 100px;
font-weight: bold;
color: blue;
cursor: default;
}
.pressO:before {
content:"O";
}
JavaScript
var maxSize = 7;
var minSize = 3;
$("#start, #restart").click(function () {
var size = prompt("Введите размер поля - нечетное, от " + minSize + " до " + maxSize + ".");
if (checkSize(size)) {
initGame(size);
$("#start, #restart").fadeOut();
} else {
alert("Введите корректный размер поля");
}
function checkSize(size) {
size = parseInt(size);
if (size % 2 == 0 || size > maxSize || size < minSize || isNaN(size)) {
return false;
} else {
return true;
}
}
});
function initGame(size) {
var area = {
strToAppend: "<div class='area' pressed='none'></div>",
size: 100
};
var map = $("#map");
map.size = size * area.size;
map.width(map.size);
map.countSize = Math.ceil(map.size / area.size);
map.createArea = function () {
var count = this.countSize;
for (var i = 0; i < count; i++) {
for (var j = 0; j < count; j++) {
this.append(area.strToAppend);
}
}
}
map.createArea();
map.slideDown();
var game = {
turn: 0,
whoTurn: 0,
mode: "computer",
speed: 400,
player1: "Eric",
player2: "Computer"
};
var elems = [];
for (var i = 0; i < map.countSize; i++) {
elems[i] = new Array(map.countSize);
for (var j = 0; j < map.countSize; j++) {
elems[i][j] = $(".area").eq(i * map.countSize + j);
}
}
var fields = $(".area");
fields.click(function () {
if ($(this).attr("pressed") != "none") {
return;
}
if (game.whoTurn == 0) {
$(this).addClass("pressX");
$(this).attr("pressed", "X");
game.turn++;
game.whoTurn = 1;
} else {
$(this).addClass("pressO");
$(this).attr("pressed", "O");
game.turn++;
game.whoTurn = 0;
}
...