如何在我的JavaScript游戏中添加计数器?

如何解决如何在我的JavaScript游戏中添加计数器?

我用Javascript编写了这个游戏:

window.onload = function() {
    canv = document.getElementById("gc");
    ctx = canv.getContext("2d");
    document.addEventListener("keydown",keyPush);
    setInterval(game,1000 / 7);
}

px = py = 10;
gs = tc = 27;
ax = ay = 15;
xv = yv = 0;
trail = [];
tail = 2;

function game () {
    px += xv;
    py += yv;
    if (px < 0) {
        px = tc - 1;
    }
    if (px > tc - 1) {
        px = 0;
    }
    if (py < 0) {
        py = tc-1;
    }
    if (py > tc - 1) {
        py = 0;
    }
    ctx.fillStyle = "black";
    ctx.fillRect(0,canv.width,canv.height);
 
    ctx.fillStyle = "lime";
    for(var i = 0; i < trail.length; i++) {
        ctx.fillRect(trail[i].x * gs,trail[i].y * gs,gs - 2,gs - 2);
        if (trail[i].x == px && trail[i].y == py) {
            tail = 2;
        }
    }
    trail.push({ x: px,y: py });
    while(trail.length > tail) {
        trail.shift();
    }
 
    if (ax == px && ay == py) {
        tail++;
        ax = Math.floor(Math.random() * tc);
        ay = Math.floor(Math.random() * tc);
    }
    ctx.fillStyle = "red";
    ctx.fillRect(ax * gs,ay * gs,gs - 2);
}

function keyPush(evt) {
    switch(evt.keyCode) {
        case 37:
            xv = -1; yv = 0;
            break;
        case 38:
            xv = 0; yv = -1;
            break;
        case 39:
            xv = 1; yv = 0;
            break;
        case 40:
            xv = 0; yv = 1;
            break;
    }
}
<canvas id="gc" width="729" height="729"></canvas>

我想在页面上的任何地方添加一个计数器,以便计算“尾巴”的长度。
我自己做了一些尝试,但似乎没有用,有什么想法应该怎么做?

还有另一个问题...如何更改网页上的按钮或文本字段的代码?例如更改:
setInterval(game,1000/7);

setInterval(game,1000/9);
使用按钮或文本字段,您可以在其中键入数字并将其粘贴到代码中?

解决方法

要在setInterval计时器中使用预定义的值,您要做的就是找到获取用户输入的最佳方法,例如使用input box。然后,您可以使用javascript

获取值

例如

[HTML]
<input type="number" value="500" id="num">
[JS]

let num = document.getElementById('num').value;
num = +num; //cast the value to number since its returned as a string.

setInterval(game,num/nth); //nth is any value of your choice,or you can also grab from user input
```

For your first question,getting how long the tail is depends on how you want it.
you can use a variable and always increment it,each time your code condition is met.
,

为了在画布上记录路径长度,我添加了您的代码

ctx.fillStyle = "blue";
ctx.fillText(trail.length,100,100);
ctx.font = "bold 20px sans-serif";
ctx.textBaseline = "bottom";

那样,它将不断在左上角打印路径长度。 关于第二个问题,我在全局范围内添加了intervalTime变量,以便您可以更改它,然后下一个间隔将是您输入该变量的时间。

var intervalTime = 1000/7;

window.onload=function() {
    canv=document.getElementById("gc");
    ctx=canv.getContext("2d");
    document.addEventListener("keydown",keyPush);
    
    setInterval(game,intervalTime);
}

px=py=10;
gs=tc=27;
ax=ay=15;
xv=yv=0;
trail=[];
tail = 2;

function game() {
    px+=xv;
    py+=yv;
    if(px<0) {
        px= tc-1;
    }
    if(px>tc-1) {
        px= 0;
    }
    if(py<0) {
        py= tc-1;
    }
    if(py>tc-1) {
        py= 0;
    }
    ctx.fillStyle="black";
    ctx.fillRect(0,canv.width,canv.height);
    
    ctx.fillStyle = "blue";
    ctx.fillText(trail.length,100);
    ctx.font = "bold 20px sans-serif";
    ctx.textBaseline = "bottom";
 
    ctx.fillStyle="lime";
    for(var i=0;i<trail.length;i++) {
        ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
        if(trail[i].x==px && trail[i].y==py) {
            tail = 2;
        }
    }
    trail.push({x:px,y:py});
    while(trail.length>tail) {
    trail.shift();
    }
 
    if(ax==px && ay==py) {
        tail++;
        ax=Math.floor(Math.random()*tc);
        ay=Math.floor(Math.random()*tc);
    }
    ctx.fillStyle="red";
    ctx.fillRect(ax*gs,ay*gs,gs-2);
}

function keyPush(evt) {
    switch(evt.keyCode) {
        case 37:
            xv=-1;yv=0;
            break;
        case 38:
            xv=0;yv=-1;
            break;
        case 39:
            xv=1;yv=0;
            break;
        case 40:
            xv=0;yv=1;
            break;
    }
}
<canvas id="gc" width="729" height="729"></canvas>

,

我想在页面上的任何地方添加一个计数器,所以它计算 长“尾巴”是。我自己做了一点尝试,但似乎没有 工作,我有什么想法吗?

对于这个问题,您可以在页面上添加一个元素,然后在每次尾部更改长度时都使用javascript更新它的文本(使用元素的innerText属性)。

示例html元素:

<!-- inside the body element -->
<div>
    <span>Tail Count: </span>
    <span id="tail-counter">2</span>
</div>

和javascript:

while (trail.length > tail) {
    trail.shift();
    document.getElementById("tail-counter").innerText = tail;
}

if (ax == px && ay == py) {
    tail++;
    document.getElementById("tail-counter").innerText = tail;
    ax = Math.floor(Math.random() * tc);
    ay = Math.floor(Math.random() * tc);
}

另外一个问题...我该如何使用按钮或文本更改代码 网页上的字段?例如改变 setInterval(game,1000/7);设置setInterval(game,1000/9);用一个按钮 或文本字段,您可以在其中键入数字并将其粘贴 进入代码?

对于此问题,要基于文本字段更改代码,您需要首先将文本字段添加到页面:

<div>
    <span>Set Game Speed: </span>
    <input id="game-speed" type="number" value="7" />
</div>

然后,您可以使用javascript获取文本字段的值并将其用于代码中

game_speed = Number.parseInt(document.getElementById("game-speed").value);
interval = setInterval(game,1000 / game_speed);

现在全部在一起(请注意,该代码允许您在玩游戏时更改游戏速度。这是通过清除已经用clearInterval设置的间隔,然后用新的游戏速度设置新的间隔来实现的)

<canvas id="gc" width="729" height="729"></canvas>

<body style="overflow-x: hidden; overflow-y: hidden;">
    <div>
        <span>Tail Count: </span>
        <span id="tail-counter">2</span>
    </div>
    <div>
        <span>Set Game Speed: </span>
        <input id="game-speed" type="number" value="7" />
    </div>

</body>
<script>
    px = py = 10;
    gs = tc = 27;
    ax = ay = 15;
    xv = yv = 0;
    trail = [];
    tail = 2;
    game_speed = 7;
    interval = {};

    window.onload = function () {
        canv = document.getElementById("gc");
        ctx = canv.getContext("2d");
        document.addEventListener("keydown",keyPush);

        game_speed = Number.parseInt(document.getElementById("game-speed").value);
        interval = setInterval(game,1000 / game_speed);
    }

    function game() {

        let new_speed = Number.parseInt(document.getElementById("game-speed").value);
        if (new_speed !== game_speed) {
            clearInterval(interval);
            game_speed = new_speed;
            interval = setInterval(game,1000 / game_speed);
        }

        px += xv;
        py += yv;
        if (px < 0) {
            px = tc - 1;
        }
        if (px > tc - 1) {
            px = 0;
        }
        if (py < 0) {
            py = tc - 1;
        }
        if (py > tc - 1) {
            py = 0;
        }
        ctx.fillStyle = "black";
        ctx.fillRect(0,canv.height);

        ctx.fillStyle = "lime";
        for (var i = 0; i < trail.length; i++) {
            ctx.fillRect(trail[i].x * gs,trail[i].y * gs,gs - 2,gs - 2);
            if (trail[i].x == px && trail[i].y == py) {
                tail = 2;
            }
        }
        trail.push({
            x: px,y: py
        });
        while (trail.length > tail) {
            trail.shift();
            document.getElementById("tail-counter").innerText = tail;
        }

        if (ax == px && ay == py) {
            tail++;
            document.getElementById("tail-counter").innerText = tail;
            ax = Math.floor(Math.random() * tc);
            ay = Math.floor(Math.random() * tc);
        }
        ctx.fillStyle = "red";
        ctx.fillRect(ax * gs,ay * gs,gs - 2);
    }

    function keyPush(evt) {
        switch (evt.keyCode) {
            case 37:
                xv = -1;
                yv = 0;
                break;
            case 38:
                xv = 0;
                yv = -1;
                break;
            case 39:
                xv = 1;
                yv = 0;
                break;
            case 40:
                xv = 0;
                yv = 1;
                break;
        }
    }
</script>
<html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-