Jump to content

My first game!


madmenyo

Recommended Posts

Hey

 

I'm creating my first game. I am proud to say i just made a script that moves a square with the arrow keys OMG :D. But just as i thought i'm starting to understand javascript a problem occurs. When everything worked i wanted to add the function game() but that just does not change the background when i have squareman below that 350 or lower...

 

Heres the code:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head>
<title>Super squareman</title>

<style>

#gamebox {
	margin:auto;
	border: 1px solid black;
	width:512px;
	height:512px;
	background-color: rgb(192,192,192);
}

#squareman {
	position:relative;
	top: 240px;
	left: 240px;
	width:32px;
	height:32px;
	background-color:#900;
	border: 1px solid black;
}

</style>

<script language="javascript">

//instance squareman
var squareman;

var timer;

var squaremanTop = 240;
var squaremanLeft = 240;

function init()
{
	squareman = document.getElementById('squareman');
	document.onkeydown = keyListener;
	game()
}

//key detection function
function keyListener(e)
{
if(!e)
{
	e = window.event;
}
if (e.keyCode==37 && squaremanLeft > 0)
{
squaremanLeft -= 4;
squareman.style.left = squaremanLeft + 'px';
}
if (e.keyCode==39 && squaremanLeft < 480)
{
squaremanLeft += 4;
squareman.style.left = squaremanLeft + 'px';
}
if (e.keyCode==38 && squaremanTop > 0)
{
squaremanTop -= 4;
squareman.style.top = squaremanTop + 'px';
}
if (e.keyCode==40 && squaremanTop < 480)
{
squaremanTop += 4;
squareman.style.top = squaremanTop + 'px';
}
}	

function game()
{
if (squaremanTop < 350)
{
gamebox.style.backgroundColor = 'rgb(128,0,0)';
squareman.style.backgroundColor = 'rgb(0,128,0)';
}
}

</script>	

</head>

<body onload="init()">

<div id="gamebox">

<div id="squareman">
  
    </div>

</div>


</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/202599-my-first-game/
Share on other sites

I fixed the style problem with FF. I had to correctly refference the CSS element, or so i was told :D.

 

Instead of using:

 

gamebox.style.backgroundColor = 'rgb(128,0,0)';

 

I had to use:

 

document.getElementById('gamebox').style.backgroundColor = 'rgb(128,0,0)';

 

Still some questions on why this does work without the "correct" refference:

 

squareman.style.top = squaremanTop + 'px';

 

But i just give this thread the solved mark, hope this one can help some other people out.

 

Link to comment
https://forums.phpfreaks.com/topic/202599-my-first-game/#findComment-1065023
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.