1
I am doing a school work, that is for tomorrow, and it is already ready, is the famous game 'Snake' in javascript and html, however hj I thought to put the player’s score in real time in the game. I’ve tried a lot of things but it only shows up 'Score: 0' regardless of how many apples you’ve eaten. Is it possible to do this in javascript? If so, how do I do this?
document.onkeydown = function(event){
pegadirecao(event.keyCode);
}
tabuleiro="<table align=center border=1>";
for (x=0;x<10;x++)
{ tabuleiro+="<tr>";
for(y=0;y<10;y++)
{tabuleiro+="<td id=td"+x+"_"+y+" style='width:30px; height:30px;'> </td>";
}
tabuleiro+="</tr>";
}
tabuleiro+="</table>";
document.getElementById('principal').innerHTML=tabuleiro;
cobra=[[5,0]];
direcao=2;
vivo=true;
function desenhapedaco(x,y)
{
document.getElementById('td'+x+'_'+y).style.background="#333333";
}
function apagapedaco(x,y)
{
document.getElementById('td'+x+'_'+y).style.background="#ffffff";
}
function geramaca()
{ mx=parseInt(Math.random()*10)
my=parseInt(Math.random()*10)
document.getElementById('td'+mx+'_'+my).style.background="#ff3333";
}
function anda()
{ apagapedaco(cobra[cobra.length-1][0], cobra[cobra.length-1][1]);
if(mx==cobra[0][0]&&my==cobra[0][1])
{
geramaca();
cobra[cobra.length]=[10,10];
}
for(x=cobra.length-1;x>0;x--)
{ cobra[x][0]=cobra[x-1][0];
cobra[x][1]=cobra[x-1][1];
}
if(direcao==0)cobra[0][1]--;
if(direcao==1)cobra[0][0]--;
if(direcao==2)cobra[0][1]++;
if(direcao==3)cobra[0][0]++;
if(cobra[0][0]<0||cobra[0][1]<0||cobra[0][0]>9||cobra[0][1]>9)
{vivo=false;
}
for(x=1;x<cobra.length;x++)
{if(cobra[x][0]==cobra[0][0]&&cobra[x][1]==cobra[0][1])vivo=false;
}
if(vivo)
{
desenhapedaco(cobra[0][0],cobra[0][1]);
setTimeout('anda();', 300);
}
else
{alert('Você perdeu, seu otario.\nVocê pegou '+(cobra.length-1)+' maçãs');
}
}
geramaca();
anda();
function pegadirecao(tecla)
{ //alert(tecla);
if(tecla==37) direcao=0;
if(tecla==38) direcao=1;
if(tecla==39) direcao=2;
if(tecla==40) direcao=3;
}
document.write('Pontuação: \n'+(cobra.length-1)+' Maçãs!');
<div id=principal></div>
<h1>
It is possible yes, just by creating a counter in the event that it "picks up" the apple.
– Jeferson Assis
Post the code.
– Diego Souza
Without the code it’s hard to help, but of course it’s possible.
– DontVoteMeDown
I already put the code in the post. If you can help me, I would appreciate it very much.
– J. Gaidzinski