...

View Full Version : Javascript code optimization



amando96
12-31-2010, 07:41 PM
Hey guys, I'm new both to this forum and javascript, I have made this small game to get me used to the canvas element, and basically just to entertain myself.

http://beta.amando-filipe.co.cc/pong.html
Right, take a look at the source code, I had to make that big Start() function so it would work on firefox, I am used to google chrome and apparently even badly made javascript runs on it, so I had to do a quick fix for firefox, what is the other way? Apparently I can't call functions inside the start function with events, like onmousedown etc.

Here is the lates code, not yet uploaded to the site:


<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="http://i.imgur.com/N7PTg.png">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>canvasPong</title>

<style type='text/css'>
body{background-color:#333; text-align:center;}
#text{width:750px;text-align:left;margin:0 auto;color:#FFF;}
.painted{background-color:#222;border-ballRadius:5px; -moz-border-ballRadius:5px; padding:5px; margin: 5px;}
iframe{background-color:#999;padding:5px;border-ballRadius:5px; -moz-border-ballRadius:5px;}
</style>

<script type='text/javascript'>

var ballSpeedX = 1;
var ballSpeedY = 1; //5
var pause = false;
var lost = false;
var pts = 0;
timer = false;
var time = 0;
var scoreset = false;

function Start() { /* System variables */
var frameDelay = 20;
var players = document.getElementById('players');
var playerInfo = players.getContext('2d');
var screen = document.getElementById('screen'); // Set up animation screen
var ctx = screen.getContext('2d'); // Set up animation screen
var out = document.getElementById('out'); // Set up information screen
var writeTo = out.getContext('2d'); // Set up information screen
var WIDTH = document.getElementById('screen').width;
var HEIGHT = document.getElementById('screen').height;
var WWIDTH = document.getElementById('out').width;
var WHEIGHT = document.getElementById('out').height; /* END */
/* Coordinate variables */
/* Colour related variables */
var R = 0;
var G = 0;
var B = 0; /* end */
/* Object variables */
var ballRadius = 10;
var ballX = ballRadius + 2;
var ballY = ballRadius + 2; /* end */
var lap = 0; /* end */
var paddleY = 0;
var prevPadY = 0;
var paddleWidth = 10;
var paddleHeight = 60;
var padDistToWall = 5;
var paddleX = WIDTH - padDistToWall - paddleWidth;
var mousemoved = false;
var speed;
var key = 0;
var highScores = [0, 0, 0, 0, 0];
highScores.length = 5;
var usr = ["", "", "", "", ""];
usr.length = 5;
var pify = 8;
var playerY = 20;


function bounce() {
if (pts >= 10) {
lost = true;
}
if (lost === true) {
frameDelay = 10000;
paddleY += 0;
ballSpeedX += 0;
ballSpeedY += 0;
writeCtx("You lost", 200, 150, 'purple', 50);
writeCtx("Press space bar to start new game", 180, 210, 'purple', 15);
if (scoreset === false) {
checkScore();
}
} else if (pause === true) {
frameDelay = 10000;
ballSpeedX += 0;
ballSpeedY += 0;
paddleY += 0;
writeCtx("Paused", 200, 150, 'purple', 50);
writeCtx("Press space bar to resume", 195, 210, 'purple', 15);
} else {
ballX += ballSpeedX;
ballY += ballSpeedY;

if (ballX - ballRadius <= 0) {
ballSpeedX *= -1;
} else {
ballSpeedX *= 1;
}
if (ballY + ballRadius >= HEIGHT || ballY - ballRadius <= 0) {
ballSpeedY *= -1;
} else {
ballSpeedY *= 1;
}



if (ballY >= paddleY && ballY <= paddleY + paddleHeight && ballX + ballRadius > paddleX && ballX - ballRadius < paddleX + paddleWidth) { // Hits paddle horizontally
if (speed >= 30) {
ballSpeedX += 0;
ballSpeedY += 0;
} else {
ballSpeedX += Math.random();
ballSpeedY += Math.random() + 0.2;
}
ballSpeedX *= -1;
R = randomNum(100, 255);
G = randomNum(100, 255);
}

if(ballX >= paddleX && ballX <= paddleX + paddleWidth && ballY + ballRadius > paddleY && ballY - ballRadius < paddleY + paddleHeight){
ballSpeedY *= -1;
}

if (ballX + ballRadius >= WIDTH) {
pts += 1;
ballX = 20;
ballY = randomNum(20, 380);
writeCtx("OOOPS!", 200, 150, 'purple', 50);
}
}
}

function randomNum(min, max) {
var Xz = Math.random() * max;
while (Xz < min) {
Xz = Math.random() * max;
}
return Math.round(Xz);
}

function paddle() {
ctx.beginPath();
ctx.fillStyle = '#00CD00';
if (paddleY === undefined) {
paddleY = 0;
}
if (paddleY + paddleHeight >= HEIGHT) {
paddleY = HEIGHT - paddleHeight;
}
if (paddleY < 0) {
paddleY = 0;
}
ctx.fillRect(paddleX, paddleY, paddleWidth, paddleHeight);
}

function rect(x, y, w, h) {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fill();
}

function write(what, whereX, whereY, colour, size) {
writeTo.textBaseline = 'top';
writeTo.fillStyle = colour;
writeTo.font = "bold " + size + "px sans-serif";
writeTo.fillText(what, whereX, whereY);
}

function writeCtx(whatt, whereXt, whereYt, colourt, sizet) {
ctx.textBaseline = 'top';
ctx.fillStyle = colourt;
ctx.font = "bold " + sizet + "px sans-serif";
ctx.fillText(whatt, whereXt, whereYt);
}

function writePlayerInfo(whatz, whereXz, whereYz, colourz, sizez) {
playerInfo.textBaseline = 'top';
playerInfo.fillStyle = colourz;
playerInfo.font = "bold " + sizez + "px sans-serif";
playerInfo.fillText(whatz, whereXz, whereYz);
}

function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
writeTo.clearRect(0, 0, WWIDTH, WHEIGHT);
playerInfo.clearRect(0, 0, WWIDTH, WHEIGHT);
}

function round(x, y, rad, shape, colour) {
ballRadius = rad;
ctx.beginPath();
ctx.fillStyle = colour;
ctx.arc(x, y, rad, 0, Math.PI * 180, false);
ctx.fill();
}

function delay(millis) {
var date = new Date();
var curDate = null;

do {
curDate = new Date();
}
while (curDate - date < millis);
}

function checkScore() {
if ((time / 1000) > highScores[0] && (time / 1000) > highScores[1]) {
scoreset = true;
for (n = highScores.length; n > 0; n--) {
highScores[n] = highScores[n - 1]; // Scroll down.
usr[n] = usr[n - 1];
}
highScores[0] = (time / 1000);
usr[0] = prompt("You have set a new record, insert a nickname to save your score", "");
} else if ((time / 1000) > highScores[1] && (time / 1000) > highScores[2]) {
scoreset = true;
for (n = highScores.length; n > 1; n--) {
highScores[n] = highScores[n - 1]; // Scroll down.
usr[n] = usr[n - 1];
}
highScores[1] = time / 1000;
usr[1] = prompt("You have set a new record, insert a nickname to save your score", "");
} else if ((time / 1000) > highScores[2] && (time / 1000) > highScores[3]) {
scoreset = true;
for (n = highScores.length; n > 2; n--) {
highScores[n] = highScores[n - 1]; // Scroll down.
usr[n] = usr[n - 1];
}
highScores[2] = time / 1000;
usr[2] = prompt("You have set a new record, insert a nickname to save your score", "");
} else if ((time / 1000) > highScores[3] && (time / 1000) > highScores[4]) {
scoreset = true;
for (n = highScores.length; n > 3; n--) {
highScores[n] = highScores[n - 1]; // Scroll down.
usr[n] = usr[n - 1];
}
highScores[3] = time / 1000;
usr[3] = prompt("You have set a new record, insert a nickname to save your score", "");
} else if ((time / 1000) > highScores[4]) {
scoreset = true;
for (n = highScores.length; n > 4; n--) {
highScores[n] = highScores[n - 1]; // Scroll down.
usr[n] = usr[n - 1];
}
highScores[4] = time / 1000;
usr[4] = prompt("You have set a new record, insert a nickname to save your score", "");
}
}

function draw() {
clear();
round(ballX, ballY , ballRadius, 0, 'rgb(' + R + ',' + G + ',' + B + ')');
write('Ball X: ' + Math.round(ballX) + 'px', 2, 2, 'white', 12);
write('Ball Y: ' + Math.round(ballY) + 'px', 2, 14, 'white', 12);
write("pad height: " + Math.round(paddleY) + 'px', 2, 26, 'white', 12);
write('Balls lost: ' + pts + "/10", 2, 38, 'white', 12);
write("ball speed: " + (speed * 100) + "px/s", 2, 50, 'white', 12);
write("time: " + time / 1000 + "s", 2, 62, 'white', 12);
writePlayerInfo('Highscores', 29, 4, 'white', 16);
playerY = 20;
for (u = 0; u < highScores.length; u++) {
if (highScores[u] !== 0) {
writePlayerInfo(usr[u] + ", " + highScores[u] + 's', 8, playerY, 'white', 12);
playerY += 12;
}
}


speed = Math.round(Math.abs(Math.sqrt(ballSpeedX * ballSpeedX + ballSpeedY * ballSpeedY)));
if (mousemoved === false) {
writeCtx("Hello there, the computer is now controlling the paddle.", 10, 50, 'red', 22);
writeCtx("Move the mouse over the paddle to start playing.", 40, 80, 'red', 22);
writeCtx("Speed increases whenever the ball touches the paddle.", 10, 110, 'red', 22);
writeCtx("Use the space bar to pause.", 120, 140, 'red', 22);
paddleY = ballY ;
paddleY -= paddleHeight / 2;
}
paddle();
bounce();
}

function init() { // Set up stuff
draw();
return setInterval(draw, frameDelay);
}

function setStuff(e) {
timer = true;
mousemoved = true;
if (pause === true || lost === true) {
paddleY = paddleY;
} else {
prevPadY = paddleY;
paddleY = e.pageY - screen.offsetTop - 10 - (paddleHeight / 2);
}
}

function count() {
if (timer === true && lost === true) {
time += 0;
} else if (timer === true && pause === false && lost === false) {
time += 100;
}
}

init();
setInterval(count, 100);
screen.addEventListener('mousemove', setStuff, true);
}

function checkKey(event) {
key = event.keyCode;
if (key == 32 && lost === true) {
ballSpeedX = 5;
ballSpeedY = 5;
time = 0;
pts = 0;
lost = false;
scoreset = false;
} else if (key == 32 && pause === false) {
pause = true;
} else if (key == 32 && pause === true) {
pause = false;
}
}

function show_hide(what) {
var object = document.getElementById(what);
if (object.style.display == 'none') {
object.style.display = 'block';
} else {
object.style.display = 'none';
}
}

//]]>
</script>

</head>
<body>
<body onload="Start()" onkeydown="checkKey(event);">
<div id="text">canvasPong is the classic pong game done with the HTML5 canvas element.<br/>
You can only lose 10 balls, the person that lasts the longest time wins!<br/><br/>
<div class="painted" onclick="show_hide('brow');">Browser compatibility(click to show/hide):</div>
<ul id="brow" style="display:none">
<li>Google chrome: Good.</li>
<li>Safari: Works.</li>
<li>Firefox v3.5 and over: Laggy.</li>
<li>Untested but likely to work on: Opera and IE9+.</li><br/>
</ul>
<div class="painted" onclick="show_hide('bug');">Bugs and things to be fixed(click to show/hide):</div>
<ul id="bug" style="display:none;">
<li>Only your score is stored, working on saving ALL scores.</li>
<li>Sometimes the ball goes mad when it touches the paddle</li>
<li>"OOPS" is too fast</li>
<li>Ball physics could be better, I hate maths.</li>
</ul>
Coded by Amando Abreu<br/>
Last edited: 30/12/2010, 01:00</div>
<canvas id="players" width="150" height="400" style="border:2px solid blue;"></canvas>
<canvas id="screen" width="600" height="400" style="border:2px solid blue;"></canvas>
<canvas id="out" width="150" height="400" style="border:2px solid blue;"></canvas> <br/> <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fbeta.amando-filipe.co.cc%2Fpong.html&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=arial&amp;colorsche me=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe>

</body>


</html>


What else could be optimized for optimal performance? thanks a lot.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum