<!DOCTYPE HTML>
<html lang = 'en'>
<head>
<meta charset = 'UTF-8'/>
<style>
*{
margin:0;
padding:0;
}
.chess{
position:relative;
width:785px;
height:785px;
background-Image:url('img/棋盘.jpg');
background-size:100%;
}
</style>
</head>
<body>
<div class = 'chess'></div>
<script>
var grid;
var count = 0;//计数
var chess = document.getElementsByTagName('div')[0];
//页面加载完成,执行函数
window.onload = function(){
init();
}
function init(){
chessPosition();
}
//创建棋子落棋的地方(div)
function chessPosition(){
//1.创建一个二维数组 装div
grid = new Array(15);
for(var i = 0; i < grid.length; i++){
grid[i] = new Array(15);
}
//2.在二维数组每个元素中创建div,并且插入到棋盘中
for(var i = 0; i < grid.length; i++){
for(var j = 0; j < grid.length; j++){
grid[i][j] = document.createElement('div');
chess.appendChild(grid[i][j]);
}
}
//3.渲染落棋的地方(每个div)
for(var i = 0; i < grid.length; i++){
for(var j = 0; j < grid.length; j++){
grid[i][j].style.position = 'absolute';
grid[i][j].style.width = 50 + 'px';
grid[i][j].style.height = 50 + 'px';
grid[i][j].style.backgroundSize = 100 + '%';
//grid[i][j].style.backgroundOrigin = 'content-box';
//grid[i][j].style.padding = 5 + 'px';
grid[i][j].style.backgroundRepeat = 'no-repeat';
grid[i][j].style.boxSizing = 'border-box';
grid[i][j].style.borderRadius = 50 + '%';
grid[i][j].style.left = j * 50 + 18 + 'px';
grid[i][j].style.top = i * 50 + 18 + 'px';
}
}
//4.给每个div绑定点击事件
//1.点击已经有棋的div不能再下另一颗
//2.下白棋
//3.下黑棋
for(var i = 0; i < grid.length; i++){
for(var j = 0; j < grid.length; j++){
//value = 0表示这个地方没有棋子,可以下棋, 1 黑棋 2 白棋
grid[i][j].value = 0;
grid[i][j].onclick = function(){
if(this.value === 0){
//2.下白棋
//3.下黑棋
this.style.backgroundImage = "url(img/"+(count % 2 + 1)+".jpg)";
count++;
this.value = count % 2 + 1;
}else{
//1.点击已经有棋的div不能再下另一颗
return;
}
}
}
}
}
</script>
</body>
</html>
js写五子棋除了输赢没写
猜你喜欢
转载自blog.csdn.net/weixin_48727085/article/details/108092834
今日推荐
周排行