JS1K

#2: the original

Source description for demo by Hayato Araki.

/** * move and draw an object to the canvas */ function P(o/*object*/, a/*isAsteroid=false*/) { c[a ? 'stroke' : 'fill']( c.arc( o[0] += (o[0] > W ? -W : o[0] < 0 ? W : 0) + o[3], o[1] += (o[1] > H ? -H : o[1] < 0 ? H : 0) + o[4], o[5], a ? 0 : o[2] - 2, a ? 6.3 : o[2] + 2, c.beginPath() ) ) } /** * hittest object against Asteroid(which is 'a') */ function T(o/*object*/, r/*objectRadius*/) { return M.sqrt(M.pow(o[0] - a[0], 2) + M.pow(o[1] - a[1], 2)) < a[5] + o[5] } //main loop function L() { //clear the canvas c.clearRect(0, 0, W, H); //update the Player i = u ? .2 : d ? -.08 : 0; p[3] = p[3] * .986 + X(t = p[2] += l ? -.12 : r ? .12 : 0) * i; p[4] = p[4] * .986 + Y(t) * i; //draw the Player P(p); //loop through the Asteroids for (i = 7; i--; /*hittest Asteroid against the Player*/ x |= T(p)) { //draw an Asteroid P( //create an Asteroid if there are less than 7 alive a = A[i] = A[i] || [ p[0] + W/4 + R() * W/2, //posX (1/4 to 3/4 of the stage away from the player) p[1] + H/4 + R() * H/2, //posY (1/4 to 3/4 of the stage away from the player) t = R() * 6.3, //direction X(t), //deltaX Y(t), //deltaY R() * 40 + 20 //radius (20-60) ], 1 ); //loop through the Bullets for hittests for (n in G) //hittest Asteroid against the Bullet T(g = G[n]) ? //if true s += g[6] | //add score G.splice(n, 1) | //remove Bullet A.splice(i, 1) //remove Asteroid : //if false check if we are 'not' in the last loop of Asteroids i ? //if true do nothing 0 : //if false check if frames are left --g[6] ? //if true draw the Bullet P(g) : //if false remove the Bullet G.shift() } //draw the score c.fillText("Score: " + s, 5, 14); //check for gameover x ? alert("GameOver") : setTimeout(L, 17) } L( //init vars D = document, C = D.body.children[0], //canvas C.style.position = 'fixed', C.width = W = innerWidth, C.height = H = innerHeight, c = C.getContext('2d'), //context M = Math, R = M.random, X = M.cos, Y = M.sin, p = [W/2, H/2, 0, 0, 0, 10],//Player [posX, posY, direction, deltaX, deltaY, radius] A = [], //Asteroids [[posX, posY, direction, deltaX, deltaY, radius]] G = [], //Bullets [[posX, posY, direction, deltaX, deltaY, radius, framesleft]] a = //single Asteroid g = //single Bullet l = u = r = d = z = //keyflags l=left, u=up, r=right, d=down i = n = t = //tmp vars x = //gameover flag s = 0, //score //init key events D.onkeyup = K = function(e, f) { t = e.keyCode - 32; //update the pressed key flag t ? t - 5 ? t - 6 ? t - 7 ? t - 8 ? 0 : d = f : r = f : u = f : l = f : z = z | !f ? f ://fire a Bullet G.push([ p[0], //posX p[1], //posY t = p[2], //direction p[3] + X(t) * 14, //deltaX p[4] + Y(t) * 14, //deltaY 4, //radius 30 //framesleft ]) }, D.onkeypress = D.onkeydown = function(e) { //update the pressed key flag to true K(e, 1); //return false for opera return !1 } )