在本机javascript中移动棋子

时间:2014-12-17 18:12:40

标签: javascript chess


我的作业遇到了一些问题,那就是让国际象棋棋子无需在本机javascript中使用ID即可自由移动。我已设法将它们设置在船上,并且还试图通过点击一块来获取坐标,然后通过点击船上某处获得坐标并将所选择的块分配给新获得的坐标,但似乎没有任何工作正常。
我真的很感激一些帮助:)

<head>
<meta charset="utf-8">
<style>
body 
    {
    padding: 20px;
    }
h1
    {
    text-align: center
    }
table 
    {
    margin-left:auto;
    margin-right:auto;
    border: 4px solid black;
    border-collapse: collapse;
    }
td
    {
    width: 40px; 
    height: 40px;
    text-align: center;
    }
.up
    {
    border-top-style: hidden;
    border-left-style: hidden;
    border-right-style: hidden;
    border-bottom-style: solid;
    background-color: white;
    font-weight: bold
    }
.down
    {
    border-top-style: solid;
    border-left-style: hidden;
    border-right-style: hidden;
    border-bottom-style: hidden;
    background-color: white;
    font-weight: bold
    }
.left
    {
    border-top-style: hidden;
    border-left-style: hidden;
    border-right-style: solid;
    border-bottom-style: hidden;
    background-color: white;
    font-weight: bold
    }
.right
    {
    border-top-style: hidden;
    border-left-style: solid;
    border-right-style: hidden;
    border-bottom-style: hidden;
    background-color: white;
    font-weight: bold
    }
.gray
    {
    background-color: gray;
    }
.white
    {
    background-color: white;
    }
</style>
</head>
<body>
<script> // chessboard
document.write("<h1>Game</h1>");
document.write("<table><tr class=up><td></td>");
for (var k=0; k<=7; k++){ //letters on top, 97 is a, 104 is h
    document.write("<td>" + String.fromCharCode(k+97) + "</td>");
}
document.write("</tr>");
for (var j=8; j>0; j--){ //numbers dropping on sides
    document.write("<tr onclick='indexRow(this)'><td class=left>" + j + "</td>");
    if((j%2)==0){
        for (var i=0; i<8; i++){
            if((i%2)==0){
                document.write('<td onclick="indexCell(this)" class=white></td>'); //grab index
            } else{
                document.write('<td onclick="indexCell(this)" class=gray></td>'); //grab index
            };
        }
    } else{
        for (var i=0; i<8; i++){
            if((i%2)==0){
                document.write('<td onclick="indexCell(this)" class=gray></td>'); //grab index
            } else{
                document.write('<td onclick="indexCell(this)" class=white></td>'); //grab index
            };
        }
    };
    document.write("<td class=right>" + j + "</td>");
}
document.write("<tr class=down><td></td>");
for (var k=0; k<=7; k++){ //letters on top,97 is a, 104 is h
    document.write("<td>" + String.fromCharCode(k+97) + "</td>");
}
document.write("</tr></table>");

//pieces
var pieces=new Array( //pieces
                new Array(" "," "," "," "," "," "," "," "," "),
                new Array(" ","&#9814"," "," ","&#9812","&#9813","&#9815","&#9816","&#9814"),
                new Array(" ","&#9817","&#9817","&#9817"," "," ","&#9817","&#9817","&#9817"),
                new Array(" "," "," "," "," ","&#9817"," "," "," "),
                new Array(" "," "," "," ","&#9817"," "," "," "," "),
                new Array(" "," "," "," ","&#9816"," "," ","&#9815"," "),
                new Array(" "," "," ","&#9822"," "," "," "," "," "),
                new Array(" ","&#9823","&#9823","&#9823","&#9822","&#9823","&#9823","&#9823","&#9823"),
                new Array(" ","&#9820"," ","&#9821","&#9818","&#9819","&#9821"," ","&#9820")
            );

//sets up the board
function setUp(){
    for (i = 1; i <=8; i++){
        for (j = 1; j <=8; j++){
            document.getElementsByTagName('tr')[j].getElementsByTagName('td')[i].innerHTML = pieces[j][i];
        }
    }
}
setUp();
//attempts with making things move
var clickedon = false;
var save_x = 0;
var save_y = 0;
var piece = 0;
var _x = 0;
var _y = 0;

//gets cell index
function indexCell(x)
{
//alert("Cell index is: " + x.cellIndex);
_x = x.cellIndex;
if(clickedon == false)
{
if(pieces[_x][_y] != " ")
{  
    figura = pieces[_x][_y];
    save_x = _x;
    save_y = _y;
    clickedon = true;
    alert(piece)    
}  
}
else
{
if(pieces[_x][_y] == " ")
{
    pieces[save_x][save_y] = " ";
    pieces[_x][_y] = piece;
    setUp();
    clickedon = false
}       
}
}
//grabs row index
function indexRow(y){
//alert("Row index is: " + x.rowIndex);
_y = y.rowIndex;
}

</script>
</body>

编辑:我现在已经发布了这个版本,我试图让棋子移动并且周围有数字和字母。

2 个答案:

答案 0 :(得分:0)

您需要做的是为每个表格单元设置一个onclick事件,并有几个全局变量来保存国际象棋棋盘的状态。

所以这是我建议的尝试:

var state = false //false if no piece has been selected
var currentPiece;
var currentCell;

var cells = document.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
   cells[i].onclick = function(){
       getCell(this);
   };
}

function getCell(that) {
    if(!state) { //this means if the state is false (i.e. no piece selected
        state = true; //piece has been selected
        currentPiece = that.innerHTML; //get the current piece selected
        currentCell = that; //get the current cell selection
    }
    else { //else, you are moving a piece
        that.innerHTML = currentPiece; //Set the selected space to the piece that was grabbed
        currentCell.innerHTML = ""; //remove the piece from its old location
        state = false; //piece has been placed, so set state back to false
    }
}

请记住,这只是我如何处理这个问题的粗略布局。我没有考虑到碎片的类型或某些例外或类似的东西。

答案 1 :(得分:0)

document.addEventListener("DOMContentLoaded", function () {
	var restartBtn = document.createElement("BUTTON"),
		mainDiv = document.createElement("DIV");

	restartBtn.innerHTML = "RESTART";
	restartBtn.id = "restartBtn";
	mainDiv.id = "chessboard";
	document.body.appendChild(restartBtn);
	document.body.appendChild(mainDiv);
	restartBtn.addEventListener("click", function () {
		reset();
	});

	function reset() {
		document.getElementById("chessboard").innerHTML = "";
		chessboardGame();
	}


	var chessboardGame = function () {
		for (var i = 1; i <= 8; i++) {
			var colorClass, child, grandChild;

			for (var j = 1; j <= 8; j++) {
				if ((i + j) % 2 === 0) {
					colorClass = "black";
				} else {
					colorClass = "white";
				}

				child = document.createElement("DIV");
				child.id = "column-" + i + j;
				grandChild = document.createElement("DIV");
				child.classList.add("box");
				child.classList.add(colorClass);
				child.classList.add("chess-column");
				grandChild.id = "coin-" + i + j;
				grandChild.classList.add("border-column");

				document.getElementById("chessboard").appendChild(child);


				if (i < 3) {
					document.getElementById("column-" + i + j).appendChild(grandChild);
					grandChild.classList.add("white-coin");
					grandChild.classList.add("black-border");
				} else if (i > 6) {
					document.getElementById("column-" + i + j).appendChild(grandChild);
					grandChild.classList.add("black-coin");
					grandChild.classList.add("white-border");
				}
			}

		}
		var chessColumns = document.getElementsByClassName("chess-column");
		for (var k = 0; k < chessColumns.length; k++) {

			chessColumns[k].onclick = function (e) {

				var el = chessColumns[0];
				while (el) {
					if (el.tagName === "DIV") {
						el.classList.remove("red-border");
					}
					el = el.nextSibling;
				}
				onColumnClick(e, this);
			};
		}

	};




	function onColumnClick(e, el) {
		el.classList.add("red-border");
		if (el.children[0]) {

			var currentActiveColumn = getActiveColumn();
			if (currentActiveColumn && currentActiveColumn !== el) {
				setActiveColumn(currentActiveColumn);
				setActiveCoin(currentActiveColumn.children[0]);
			} else {
				setActiveColumn(el);
				setActiveCoin(el.children[0]);
			}
		}

		var activeColumn = getActiveColumn(),
			activeCoin = getActiveCoin();

		if (activeColumn && activeColumn !== e.currentTarget) {
			if (Math.abs(activeColumn.offsetLeft - e.currentTarget.offsetLeft) > 80 || Math.abs(activeColumn.offsetTop - e.currentTarget.offsetTop) > 80) {
				alert("Move not allowed!");
				e.currentTarget.classList.remove("red-border");
				activeCoin.parentNode.classList.add("red-border");
			} else {
				moveCoin(activeColumn, el, activeCoin);

			}

		}
	}
	chessboardGame();
	function moveCoin(activeItem, targetItem, coin) {
		if (targetItem.firstChild) {
			var activeItemClassList = coin.classList,
				targetItemClassList = targetItem.firstChild.classList;

			if (activeItemClassList[1] === targetItemClassList[1]) {
				alert("Move not allowed!");
				targetItem.classList.remove("red-border");
				activeItem.classList.add("red-border");
				return;
			}
		}

		while (activeItem.firstChild) {
			activeItem.removeChild(activeItem.firstChild);
		}
		while (targetItem.firstChild) {
			alert("Good Move there!");
			targetItem.removeChild(targetItem.firstChild);
		}
		targetItem.appendChild(coin);
		setActiveColumn(targetItem);
	}

	function setActiveColumn(el) {
		this.activeColumn = el;
	}

	function getActiveColumn() {
		return this.activeColumn;
	}

	function setActiveCoin(coin) {
		this.activeCoin = coin;
	}

	function getActiveCoin() {
		return this.activeCoin;
	}
});
#chessboard {
    width: 640px;
    height: 640px;
    margin: 20px;
    border: 2px solid #333;
    position: relative;

}
.black {
    float: left;
    width: 80px;
    height: 80px;
    background-color: #333333;
    font-size:50px;
    text-align:center;
    display: table-cell;
    vertical-align:middle;
    cursor:pointer;
    font-weight:bold;
}
.white {
    float: left;
    width: 80px;
    height: 80px;
    background-color: #ffffff;
    font-size:50px;
    text-align:center;
    display: table-cell;
    vertical-align:middle;
    cursor:pointer;
}

.black-coin{
    background: black;
    width: 20px;
    height: 20px;
    cursor:pointer;
    position: relative;
    margin: 37% auto;
    transition: left .5s ease-in, top .5s ease-in;
}

.white-border{
    border: 2px solid white;
}

.white-coin{
    background: white;
    width: 20px;
    height: 20px;
    position: relative;
    margin: 37% auto;
    cursor:pointer;
    transition: left .5s ease-in, top .5s ease-in;
}

.black-border{
    border: 2px solid black;
}


.red-border{border: 2px solid red; box-sizing: border-box;}
<html lang="en">
<head>
    <link rel="stylesheet" href="css/style.css">
    <title>CHESSBOARD</title>

</head>
<script src="js/script.js"></script>
</html>