战舰游戏
展示
基于 vue 开发,具体代码请看vue 写法
<js-2018_11_02_01-index/>
原生 js 代码
<div class="continuar">
<table cellpadding="0" cellspacing="0" id='tab'>
tr*7>td*7
</table>
<div class="enter">
<input type="text" placeholder="A0" maxlength="2" id="coordinate" value="">
<div class="btn" id='btnEnter'>输入</div>
</div>
</div>
* {
margin: 0;
padding: 0;
}
body {
background-color: black;
}
.continuar {
margin: 0;
width: 650px;
position: relative;
height: 650px;
background: url('../images/board.jpg') no-repeat;
background-size: contain;
}
table {
margin: 0 auto;
padding-top: 62px;
}
tr td {
width: 60px;
height: 60px;
border: 0px solid rgb(21, 172, 16);
}
td.ship {
background: url('../images/ship.png') no-repeat;
background-size: contain;
background-position: center;
}
td.miss {
background: url('../images/miss.png') no-repeat;
background-size: contain;
background-position: center;
}
.enter {
position: absolute;
right: 14%;
bottom: 0;
display: flex;
padding: 20px;
}
.enter input {
height: 35px;
color: #000000;
background-color: rgb(159, 255, 48);
display: block;
float: left;
border: 0;
}
.enter .btn {
height: 25px;
float: left;
padding: 0 5px;
cursor: pointer;
font-size: 12px;
color: aliceblue;
margin-left: 5px;
line-height: 25px;
user-select: none;
text-align: center;
background-color: #41510d;
border: 5px solid #46e234;
}
window.onload = function() {
let btnEnter = document.getElementById('btnEnter');
let coordinate = document.getElementById('coordinate');
// 给节点添加点击事件
btnEnter.onclick = btn;
coordinate.onkeypress = key;
function key(e) {
// 监听`enter`键是否被点击
if (e.charCode === 13) {
btn();
}
}
// 转化坐标
let digital = { A: 0, B: 7, C: 14, D: 21, E: 28, F: 35, G: 42 };
// 使用随机数,初始化战舰位置
let ships = {
0: Math.floor(Math.random() * 48),
1: Math.floor(Math.random() * 48),
2: Math.floor(Math.random() * 48),
};
console.log(ships);
// 获取所有的`td`
function btn() {
console.log(coordinate.value);
let patt1 = new RegExp(/^[a-g][0-6]/i);
if (patt1.test(coordinate.value)) {
// 截取字符串中的首位,将其转化为大写字母
let coordinateText = coordinate.value[0].toUpperCase();
// 玩家输入的战舰坐标
let coordinateNumber =
Number.parseInt(digital[coordinateText]) +
Number.parseInt(coordinate.value[1]);
// 获取所有名为 `td` 的节点
let tds = document.getElementsByTagName('td');
// 判断玩家输入的坐标上,是否有战舰存在,如果有的话,就击沉战舰
if (
ships[0] === coordinateNumber ||
ships[1] === coordinateNumber ||
ships[2] === coordinateNumber
) {
// 击沉战舰
tds[coordinateNumber].setAttribute('class', 'ship');
} else {
// 没有击沉战舰
tds[coordinateNumber].setAttribute('class', 'miss');
}
} else {
alert('请输入正确的坐标;\n如: A6!');
}
}
};
vue 写法
这里我做了一点改进,增加直接点击区域替换背景图标,详细功能请点击展示
<<< docs/.vuepress/components/js/2018_11_02_01/index.vue
标签:11,02,01,coordinateNumber,let,background,coordinate,td,Math From: https://www.cnblogs.com/honghaitao/p/18452436