I have been trying to recreate the oldschool game 'breakout' in javascript and have run into a problem which i can't for the life of me figure out.
It involves animation and the functions work correctly when i use the div style directly in the move() function, but as part of my assignment i've been asked to define ball as an object with methods
Here's the script and markup:
- Code: Select all
<
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=iso-8859-1"/>
<title>Web Programming Assignment 2 - Javascript Game</title>
<linkrel = "stylesheet"type = "text/css"href = "style.css"\>
<script>
var lives =2;
var score =0;
var ball;
var position;
var direction;
function initialize()
{
document
.getElementById('lives').innerHTML ="Lives: "+ lives;
document
.getElementById('score').innerHTML ="Score: "+ score;
ball
=new object('ball');
direction
="north";
}
function object(element)
{
this.style = document.getElementById(element).style;
this.move = move;
}
function move(object)
{
var me =this;
if(direction =="north")
{
position
= parseInt(object.style.top);
if(position >0)
{
position
--;
object
.style.top = position;
setTimeout
(me.move,0);
}
else
{
direction
="south";
}
}
if(direction =="south")
{
position
= parseInt(object.style.top);
if(position <287)
{
position
++;
object
.style.top = position;
setTimeout
(me.move,0);
}
else
{
direction
="north";
collide
();
}
}
}
function collide()
{
if(direction =="north")
{
move
();
}
}
</script>
</head>
<bodyonload = "initialize()">
<hr/>
<h1>Javascript Game</h1>
<hr/>
<ahref = "#">Home</a>
<p/>
<form>
<divid = "gameBoard">
<divid = "boundary">
<divid = "ball"style = "left:205px;right:210;
top:287px;bottom:292;"></div>
<divid = "paddle"></div>
</div>
<divid = "gameControl">
<divid = gameTitle>Breakout Game</div>
<divid = "lives"></div>
<divid = "score"></div>
<inputtype = "button"value = "Start"id = "buttonStart"onclick = "ball.move(ball)">
<br>
<inputtype = "button"value = "Stop"id = "buttonStop">
<br>
<inputtype = "button"value = "End Game"id = "buttonEnd">
<br>
</div>
</div>
Any help would be greatly appreciated