Core JavaScript

A Racing Game

Instructions: Avoid other cars. Use the right and left arrow keys to move. Press "Enter' to begin. The code files for the game above are shown below. The first one, "RaceGame.html" is a short html file that calls the longer "RaceGame.js" file that contains the game code. The additional image files, "Bush. png", EnemyCar.png", and "RaceCar.png" must be located in the same directory.

 

Output

 

RaceGame.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <title>XoaX.net</title>
</head>
<body>

<script type="text/javascript" src="RaceGame.js"></script>

</body>
</html>

RaceGame.js

// Game Variables
var iScore = 0;
var qrGameViewport;
var qrRoad;
var qrScoreBox;
var bGameOver;
var qrBody;
var qrGameOver;

// Car
var qrCar;
var iCarSpeed;

// Bushes
var qpBushes;
var qpBush;
var iBushSpacing;
var iLastBush;

// Enemy Cars
var qrEnemyCars;
var qrEnemyCar;
var iEnemySpacing;
var iLastEnemy;
var iEnemyCarSpeed;
var iEnemyFrequency;

// Game Initialization
function Initialization() {
	// Get the main body element
	qrBody = document.getElementsByTagName("body")[0];

	// Create the main viewport, background green
	qrGameViewport = document.createElement("div");
	qrGameViewport.style.backgroundColor = "#00aa00";
	qrGameViewport.style.width = "800px";
	qrGameViewport.style.height = "600px";
	qrGameViewport.style.position = "absolute";
	qrGameViewport.style.overflow = "hidden";
	qrBody.appendChild(qrGameViewport);

	// Create the road and place it
	qrRoad = document.createElement("div");
	qrRoad.style.backgroundColor = "#aaaaaa";
	qrRoad.style.width = "150px";
	qrRoad.style.height = "600px";
	qrRoad.style.position = "absolute";
	qrRoad.style.left = "325px";
	qrGameViewport.appendChild(qrRoad);

	// Create the car
	qrCar = document.createElement("img");
	qrCar.src = "RaceCar.png";
	qrCar.style.position = "absolute";
	qrCar.style.left = "50px";
	qrCar.style.top = "450px";
	qrRoad.appendChild(qrCar);

	// Create an element for the game score
	qrScoreBox = document.createElement("div");
	qrScoreBox.style.position = "absolute";
	qrScoreBox.style.color = "#ffffff";
	qrScoreBox.style.padding = "5px";
	qrScoreBox.innerHTML = "Score = " + 0;
	qrGameViewport.appendChild(qrScoreBox);

	qrGameOver = document.createElement("div");
	qrGameOver.style.backgroundColor = "#000000";
	qrGameOver.style.width = "800px";
	qrGameOver.style.height = "600px";
	qrGameOver.style.position = "absolute";
	qrGameOver.style.opacity = "0.5";
	qrGameOver.style.zIndex = "10";
	qrGameOver.style.color = "#ffffff";
	qrGameOver.style.padding = "335px";
	qrGameOver.innerHTML = "      Game Over<br />Press Enter to Begin";
	qrGameViewport.appendChild(qrGameOver);

	document.onkeydown = KeyHandler;

	qrEnemyCars = new Array()
	qpBushes = new Array();

	InitializeVariables();
	bGameOver = true;
	GameLoop();
}

function InitializeVariables() {
	iScore = 0;
	iCarSpeed = 10;
	iEnemyCarSpeed = 5;
	iEnemyFrequency = 500;
	iBushSpacing = 500;
	iLastBush = 600 - iCarSpeed;
	iEnemySpacing = 600;
	iLastEnemy = -900;
	bGameOver = false;
	qrGameViewport.removeChild(qrGameOver);

	// Remove any old enemy cars and bushes and clear the arrays
	for (var iCurrEnemy in qrEnemyCars) {
		qrRoad.removeChild(qrEnemyCars[iCurrEnemy]);
	}
	qrEnemyCars.splice(0, qrEnemyCars.length);
	for (var iCurrBush in qpBushes) {
		qrGameViewport.removeChild(qpBushes[iCurrBush]);
	}
	qpBushes.splice(0, qpBushes.length);
}

function StartGame() {
	InitializeVariables();

	// Start the game loop
	GameLoop();
}

function GameLoop() {
	UpdateBushes();
	UpdateEnemyCars();
	if (!bGameOver) {
		setTimeout(GameLoop,20);
	} else {
		qrGameViewport.appendChild(qrGameOver);
	}
}

function UpdateBushes() {
	// Decrement the last bush counter
	iLastBush = iLastBush + iCarSpeed;
	// Update the bush positions and remove any passed
	for (iCurrBush in qpBushes) {
		var iCurrY = parseInt(qpBushes[iCurrBush].style.top) + iCarSpeed;
		qpBushes[iCurrBush].style.top = iCurrY + "px";
		if (iCurrY > 600) {
			qrGameViewport.removeChild(qpBushes[iCurrBush]);
			qpBushes.splice(iCurrBush, 1);
		}
	}

	// Add Bushes in the ranges left (0-275, 0-550) and right (475-750, 0-550)
	while (iLastBush > 0) {
		// Add a new left bush
		var iX = GetRandomInteger(0, 276);
		var iY = GetRandomInteger(iLastBush - iBushSpacing, iLastBush);
		AddBushAt(iX, iY);
		// Add a new right bush
		iX = GetRandomInteger(475, 751);
		iY = GetRandomInteger(iLastBush - iBushSpacing, iLastBush);
		AddBushAt(iX, iY);
		// Decrement the last bush counter by the spacing
		iLastBush = iLastBush - iBushSpacing;
	}
}

function UpdateEnemyCars() {
	var iRelativeSpeed = iCarSpeed - iEnemyCarSpeed;
	// Decrement the last enemy counter
	iLastEnemy = iLastEnemy + iRelativeSpeed;

	// Update the enemy positions and remove any passed
	for (iCurrEnemy in qrEnemyCars) {
		var iCurrY = parseInt(qrEnemyCars[iCurrEnemy].style.top) + iRelativeSpeed;
		qrEnemyCars[iCurrEnemy].style.top = iCurrY + "px";
		if (iCurrY > 600) {
			qrRoad.removeChild(qrEnemyCars[iCurrEnemy]);
			qrEnemyCars.splice(iCurrEnemy, 1);
			// Increment the score here
			iScore = iScore + 1;
			// Speed up the car after every 10 cars passed
			if ((iScore % 5) == 0) {
				iCarSpeed = iCarSpeed + 1;
			}
			// Repaint the Score
			qrScoreBox.innerHTML = "Score = " + iScore;
		}
		if (CheckCarCollisions(qrCar, qrEnemyCars[iCurrEnemy])) {
			bGameOver = true;
		}
	}
	// Add Enemy Cars in the range (0-100, 0-700)
	while (iLastEnemy > 0) {
		// Add a new enemy
		var iX = GetRandomInteger(0, 101);
		var iY = GetRandomInteger(iLastEnemy - iEnemySpacing + 100, iLastEnemy - 100);
		AddEnemyCarAt(iX, iY),
		//Decrement the last enemy
		iLastEnemy = iLastEnemy - iEnemySpacing;
	}
}

function CheckCarCollisions(qrCar1, qrCar2) {
	// Car are always 50x100
	var iLeft1 = parseInt(qrCar1.style.left) + 2;
	var iTop1 = parseInt(qrCar1.style.top) + 5;
	var iRight1 = iLeft1 + 46;
	var iBottom1 = iTop1 + 90;

	var iLeft2 = parseInt(qrCar2.style.left) + 2;
	var iTop2 = parseInt(qrCar2.style.top) + 5;
	var iRight2 = iLeft2 + 46;
	var iBottom2 = iTop2 + 90;
	if ((iLeft1 > iRight2) || (iRight1 < iLeft2)) {
		return false;
	} else if ((iTop1 > iBottom2) || (iBottom1 < iTop2)) {
		return false;
	}
	return true;
}

function AddBushAt(x, y) {
	qpBush = document.createElement("img");
	qpBush.src = "Bush.png";
	qpBush.style.position = "absolute";
	qpBush.style.left = x + "px";
	qpBush.style.top = y + "px";
	qrGameViewport.appendChild(qpBush);
	qpBushes.push(qpBush);
}

function AddEnemyCarAt(x, y) {
	qrEnemyCar = document.createElement("img");
	qrEnemyCar.src = "EnemyCar.png";
	qrEnemyCar.style.position = "absolute";
	qrEnemyCar.style.left = x + "px";
	qrEnemyCar.style.top = y + "px";
	qrRoad.appendChild(qrEnemyCar);
	qrEnemyCars.push(qrEnemyCar);
}

// Generate a number from iLow to iHigh - 1
function GetRandomInteger(iLow, iHigh) {
	return (Math.floor(Math.random()*(iHigh-iLow)) + iLow);
}

function KeyHandler(qKeyEvent) {
    var iKeyDown = 0;
    var iLeftArrow = 37;
    var iRightArrow = 39;
    var iEnter = 13;

    if (qKeyEvent) {
        iKeyDown = qKeyEvent.which;
    } else {
        iKeyDown = window.event.keyCode;
    }

    var iCurrentCarPos = parseInt(qrCar.style.left);

    if (iKeyDown === iLeftArrow) {
	if (iCurrentCarPos > 0 && !bGameOver) {
		iCurrentCarPos = iCurrentCarPos - 50;
 		qrCar.style.left = iCurrentCarPos + "px";
        }
    } else if (iKeyDown === iRightArrow) {
        if (iCurrentCarPos < 100 && !bGameOver) {
        	iCurrentCarPos = iCurrentCarPos + 50;
		qrCar.style.left = iCurrentCarPos + "px";
        }
    } else if (iKeyDown === iEnter) {
    	if (bGameOver) {
	    StartGame();
	}
    }
    return false;
}

window.onload = Initialization;
 

© 2007–2024 XoaX.net LLC. All rights reserved.