基于 HTML 表格的游戏中的 Javascript 函数

标签 javascript html function html-table

这是我的第一个问题,所以请放轻松:)

我的 HTML 中有一个包含 td 的表,每个表都有自己的 id,与其 xy 值相对应。例如。 :

<td id = Y9X1></td>
<td id = Y9X2></td>

我想做的是使用函数“抓取”该项目,例如:

//the starting position of x and y
var x = 1;
var y = 1;

let id = 'Y' +y+'X'+x;

//grab the id 
function grabPoistion(id) {
    document.getElementById(id)
}
//move sprite on grid according to position
function moveSprite() {
    grabPoistion(id);
}

这就是我基本上想做的事情:

如果 x = 1 且 y = 1,则将“玩家”移动到 ID 为 Y1X1 的表格单元格。

这是我最初的代码,我只是希望有一种方法可以加快速度,而不必为每个单元格执行语句:

function moveSprite() {
	if(x==1 && y==1) {
		//move the player in the table to td with id =     Y1X1
	}
	else if(x==2 && y==1) {
		//move the player in the table to td with id =     Y1X2
	}	
}

最佳答案

使用表格时,您可以轻松使用其单元格。通常不需要为 td 使用 id。老实说,我不知道你在问什么,但我有一小段代码,可以通过按上、下、左、右箭头键在表格中移动 x。我留下了 leftright 为您工作,也许您可​​以掌握如何选择表格行及其在表格内的单元格并自己实现上下。脚本的扩展也应该相当简单——它故意变得非常冗长。

const directions = {
  '37': left,
  '39': right,
  '38': up,
  '40': down
},
table = document.getElementsByTagName('table')[0],
  position = {
    x: 0,
    y: 0
  }
table.rows[0].cells[0].innerText = 'x';

window.addEventListener('keyup', e => {
  if (![37, 38, 39, 40].includes(e.keyCode)) return;
  move(e.keyCode);
})

function move(direction) {
  [...table.rows].forEach(r => [...r.cells].forEach(c => c.innerText = ''));
  directions[direction]();
  table.rows[position.y].cells[position.x].innerText = 'x';
}

function left() {
  if (position.x === 0) {
    if (position.y === 0) return;
    position.y -= 1;
    position.x = table.rows[position.y].cells.length - 1;
    return;
  }
  position.x -= 1;
}

function right() {
  if (position.x === table.rows[position.y].cells.length - 1) {
    if (position.y === table.rows.length - 1) return;
    position.y += 1;
    position.x = 0;
    return;
  }
  position.x += 1;
}

function up() {
  console.log('have fun implementing');
}

function down() {
  console.log('have fun implementing');
}
tr, td {
  border: 1px solid red;
  height: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}

td {
  width: 25px;
}
<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

(单击“运行代码片段”,然后进入表格)

关于基于 HTML 表格的游戏中的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776938/

相关文章:

javascript - 如何使用 Monk 在 Javascript 的 forEach 循环中更新文档?

javascript - 同时处理两个API

javascript - 如何将数组从两列过滤为非空对?

javascript - 在html文件中<%标签

python - 如何停止并重复某个功能?

javascript - 如何在 Angular 表单上设置自定义验证?

用于 HTML5 输入验证的 Javascript 正则表达式语法

html - 用于显示聊天文本消息的最佳 html 标签?

c - 函数内的函数不起作用

javascript - with() 语句中的函数不接收定义的对象