Friday, June 11, 2010

Spacewar in under 100 lines?

I'm a little crazy, but I'm trying to code a clone of the ol' classic game "Spacewar" in under 100 lines in ActionScript 2. I did this before with code spread about on different movieclips and had a semi-playable game working. But now I'm trying something a little harder. This time I'm trying to keep all the actions together on the main timeline with the added challenge of trying to make better use of OOP conventions to better cover steps that repeat. So far I got it up to the point where it makes the bullets, but it doesn't quite shoot them. Hell, it's hard enough trying to figure out how I did it the first time around - being that I haven't done much in scripting for a long time. Anyhow... Here's the code:

// This is the section with the actual game.
// Create the Ship() constructor class.
function Ship(rot, xP, yP, player) {
this.rotation = rot;
this.xVelocity = 0;
this.yVelocity = 0;
this.hitPoints = 100;
this.player = player;
}
// Adding methods to Ship class.
Ship.prototype.applyThrust = function() {
trace("Applying thrust to "+this.player);
angleDeg = (this.rotation<0)*360+this.rotation;
angleRad = (angleDeg/180)*Math.PI;
this.xVelocity += (Math.sin(angleRad)*.75);
this.yVelocity -= (Math.cos(angleRad)*.75);
};
Ship.prototype.turnLeft = function() {
trace("Turning "+this.player+" left");
this.rotation -= 10;
};
Ship.prototype.turnRight = function() {
trace("Turning "+this.player+" right");
this.rotation += 10;
};
Ship.prototype.fireGun = function() {
trace(this.player+" is firing their gun.");
_root.attachMovie("bullet", this.player+"Shot_mc", 10);
_root[this.player+"Shot_mc"]._x = _root[this.player+"_Ship_mc"]._x;
_root[this.player+"Shot_mc"]._y = _root[this.player+"_Ship_mc"]._y;
};
Ship.prototype.calcMovement = function(clipID) {
clipID._rotation = this.rotation;
clipID._x += this.xVelocity+((clipID._x<0)*640)-((clipID._x>640)*640);
clipID._y += this.yVelocity+((clipID._y<0)*480)-((clipID._y>480)*480);
};
var P1_Ship = new Ship(0, 10, 10, "P1");
var P2_Ship = new Ship(0, 100, 10, "P2");
for (var prop in P1_Ship) {
trace("property "+prop+" value is "+P1_Ship[prop]);
}
function testLoop() {
if (Key.isDown(87) == true) {
P1_Ship.applyThrust();
}
if (Key.isDown(65) == true) {
P1_Ship.turnLeft();
}
if (Key.isDown(68) == true) {
P1_Ship.turnRight();
}
if (Key.isDown(83)) {
P1_Ship.fireGun(P1_Ship_mc);
}
if (Key.isDown(38)) {
P2_Ship.applyThrust();
}
if (Key.isDown(37)) {
P2_Ship.turnLeft();
}
if (Key.isDown(39)) {
P2_Ship.turnRight();
}
if (Key.isDown(40)) {
P2_Ship.fireGun(P2_Ship_mc);
}
P1_Ship.calcMovement(P1_Ship_mc);
P2_Ship.calcMovement(P2_Ship_mc);
}
setInterval(testLoop, 60);
stop();


Oh, and I'm using only 3 movieclips if you haven't figured it out. And adding sound shouldn't be too terrible either, even though I haven't got to that yet.

No comments: