Permalink
Browse files

Add enemy class that shoots bullets

  • Loading branch information...
1 parent 0e3cca3 commit 82f898a188c4ccb04558cb6c48f023ad0a38d388 Daniel Mark Schwartz committed Nov 14, 2012
Showing with 46 additions and 4 deletions.
  1. BIN enemy.gif
  2. +46 −4 game.coffee
View
BIN enemy.gif
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
@@ -7,6 +7,9 @@ bulletImage.src = 'bullet.gif'
shipImage = new Image
shipImage.src = 'ship.png'
+enemyImage = new Image
+enemyImage.src = 'enemy.gif'
+
class Bullet
constructor: (@x, @y, @dx, @dy, @r) ->
@alive = true
@@ -24,6 +27,27 @@ class Bullet
if @collision
ctx.fillRect @x, @y, 10, 10
+class Enemy
+ constructor: (@x, @y, @dx, @dy, @bf, @bs) ->
+ @alive = true
+ @t = 0
+
+ update: (dt) ->
+ @x += @dx * dt
+ @y += @dy * dt
+ @t += dt
+ if @t > @bf
+ @t = 0
+ game.spawnBullet @x, @y, 0, @bs
+
+ if @x < 0 or @x > atom.width or @y < 0 or @y > atom.height
+ @alive = false
+
+ draw: (ctx) ->
+ ctx.drawImage enemyImage, @x - enemyImage.width/2, @y - enemyImage.height/2
+
+
+
class Ship
constructor: (@x, @y, @speed) ->
@@ -59,23 +83,32 @@ class Game extends atom.Game
atom.input.bind atom.key.DOWN_ARROW, 'down'
atom.input.bind atom.key.SPACE, 'space'
+ @t = 0
@updates = 0
setInterval (=> @fps = @updates; @updates = 0), 1000
@ship = new Ship atom.width * .5, atom.height * .7, 150
-
- @bullets = (new Bullet (randInRange 0, atom.width), (randInRange 0, atom.height), (randInRange -100, 100), (randInRange -100, 100), 25 for i in [0..50])
+ @bullets = []
+ @enemies = []
update: (dt) ->
@ship.update dt
b.update dt for b in @bullets
@bullets = @bullets.filter (b) -> b.alive
+ e.update dt for e in @enemies
+ @enemies = @enemies.filter (b) -> b.alive
+
collision = (@ship.collide b for b in @bullets).some (x) -> x
if collision
do @stop
+ @t += dt
+ if @t > 2
+ @spawnEnemy (randInRange 0, atom.width), 10, (randInRange -40, 40), 20, 1, (randInRange 80, 120)
+ @t = 0
+
@updates += 1
draw: ->
@@ -84,14 +117,23 @@ class Game extends atom.Game
@ship.draw atom.context
+ e.draw atom.context for e in @enemies
+
atom.context.fillStyle = 'red'
b.draw atom.context for b in @bullets
atom.context.font = '20px Georgia'
atom.context.fillStyle = 'blue'
- atom.context.fillText "#{@fps}", 10, 50
+ atom.context.fillText "#{@fps}", 10, 40
+
+ atom.context.fillText "Bullets: #{@bullets.length}", 10, 80
+ atom.context.fillText "Enemies: #{@enemies.length}", 10, 120
+
+ spawnBullet: (x, y, dx, dy) ->
+ @bullets.push new Bullet x, y, dx, dy, 25
- atom.context.fillText "Bullets: #{@bullets.length}", 10, 100
+ spawnEnemy: (x, y, dx, dy, bulletFreq, bulletSpeed) ->
+ @enemies.push new Enemy x, y, dx, dy, bulletFreq, bulletSpeed
game = new Game

0 comments on commit 82f898a

Please sign in to comment.