Click here to Skip to main content
15,890,845 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i got this game coded in Javascript:
JavaScript
<pre><canvas id="gc" width="729" height="729"></canvas>
<body style="overflow-x: hidden; overflow-y: hidden;">
</body>
<script>
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,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,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>
And i want to add a counter anywhere on the page, so it counts how long the "tail" is.
I have tried a little myself but it dosen't seem to work, any ideas how i do?

What I have tried:

I have tried some html like
<div id="counter">0</div>
but it just messes everything up.

I think this is where the counter script should be:
if(ax==px && ay==py) {
???
}
Posted
Updated 6-Oct-20 4:22am
Comments
ZurdoDev 5-Oct-20 13:37pm    
Just create a global variable and then decrement it whenever you need to.

1 solution

I don't see anything in the supplied code that would affect your <div id='counter'>

It won't change unless you make it change. Unfortunately, since it's a <div> element it does not have a value= property.

What you need to do to modify the content is to change the content of the element like so:
document.getElementByID('counter').innerHTML = (the new value)
. You can actually set it to pretty much anything with any sort of value and not just numeric values.

See also: HTML DOM innerHTML Property[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900