简体   繁体   English

画布蛇游戏中的Javascript按钮

[英]Javascript buttons in canvas snake game

I am messing around with a script I found for a snake game. 我在弄乱我为蛇游戏找到的脚本。 It works fine, but the only way to control it is through the keyboard. 它可以正常工作,但是控制它的唯一方法是通过键盘。

Here is the script for the controls: 这是控件的脚本:

window.addEventListener('keydown', function(e) {
    if (e.keyCode === 38 && direction !== 3) {
        direction = 2; // Up
    } else if (e.keyCode === 40 && direction !== 2) {
        direction = 3; // Down
    } else if (e.keyCode === 37 && direction !== 0) {
        direction = 1; // Left
    } else if (e.keyCode === 39 && direction !== 1) {
        direction = 0; // Right
    }
});

My question is, how do I make buttons to control the game rather than using the keyboard? 我的问题是,如何制作按钮来控制游戏而不是使用键盘?

Is it possible to make buttons with onclick="function()" and the function giving value to direction? 是否可以使用onclick="function()"和功能赋予方向值的按钮来制作按钮?

If so how is this done? 如果是这样,怎么做? If not, do you have any suggestions? 如果没有,您有什么建议吗?

Here is my JSFiddle 这是我的JSFiddle

Simply add some button elements: 只需添加一些按钮元素:

<button id="up" type="button">Up</button>
<button id="down" type="button">Down</button>
<button id="left" type="button">Left</button>
<button id="right" type="button">Right</button>

And then add click handlers for each button: 然后为每个按钮添加点击处理程序:

document.getElementById("up").addEventListener("click", function() {
    direction = 2;
});
// and so forth for the other buttons

Updated demo: http://jsfiddle.net/WKQff/1/ 更新的演示: http : //jsfiddle.net/WKQff/1/

Note that I left your existing keydown handler in the demo, and that the snake can be controlled both by using the arrow keys and by using the buttons that I added. 请注意,我在演示中保留了现有的keydown处理程序,并且可以使用箭头键和添加的按钮来控制蛇。 Obviously if you want it to work only with buttons then you should remove the keydown handler. 显然,如果您希望它与按钮一起使用,则应删除keydown处理程序。

You can of course use <img> elements with appropriate direction icons instead of button elements. 当然,您可以将<img>元素与适当的方向图标一起使用,而不是按钮元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM