Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // title: space invaders
- // author: nooh alavi
- // desc: pls subscribe <3
- // script: js
- var ship;
- var bullets = [];
- var enemies = [];
- var spawnRate = 5; //seconds before enemies spawn
- var eTime = 0;
- var secs = 0;
- //
- function Bullet(_x, _y, _e) {
- this.x = _x;
- this.y = _y;
- this.isEnemyBullet = _e;
- this.render = function() {
- if (this.isEnemyBullet) {
- spr(4, this.x, this.y, 0);
- } else {
- spr(2, this.x, this.y, 0);
- }
- }
- this.update = function() {
- if (this.isEnemyBullet) {
- this.y++;
- } else {
- this.y--;
- }
- }
- this.isCollidingWith = function(obj) {
- return (this.x + 8 > obj.x && this.y + 8 > obj.y && obj.x + 8 > this.x && obj.y + 8 > this.y );
- }
- }
- function Enemy(_x, _y) {
- this.x = _x;
- this.y = _y;
- this.dir = 1;
- this.render = function() {
- spr(3, this.x, this.y, 0);
- }
- this.update = function() {
- this.x += this.dir;
- if (this.x < 0) {
- this.x = 0;
- this.y += 8;
- this.dir = 1;
- } else if (this.x > 240-8) {
- this.x = 240-8;
- this.y += 8;
- this.dir = -1;
- }
- if (Math.random() <= 0.01) {
- this.shoot();
- }
- }
- this.shoot = function() {
- bullets.push(new Bullet(this.x, this.y, true));
- }
- }
- //
- function init() {
- ship = {
- x: 120,
- y: 100
- }
- bullets = [];
- enemies = [];
- var secs = 0;
- }
- function shoot(x, y, e) {
- bullets.push(new Bullet(x, y, e));
- }
- function spawnEnemies() {
- for (var i = 0; i < 240/8; i++) {
- enemies.push(new Enemy(i * 8, 0));
- }
- }
- function update() {
- eTime++;
- if (key(23)) {
- ship.y--;
- } else if (key(19)) {
- ship.y++;
- }
- if (key(1)) {
- ship.x--;
- } else if (key(4)) {
- ship.x++;
- }
- if (keyp(48)) {
- shoot(ship.x, ship.y, false);
- }
- if (ship.x + 8 > 240) {
- ship.x = 240 - 8;
- } if (ship.x < 0) {
- ship.x = 0;
- } if (ship.y < 0) {
- ship.y = 0;
- } if (ship.y + 8 > 136) {
- ship.y = 136 - 8;
- }
- for (var i =0; i < bullets.length; i++) {
- bullets[i].update();
- for (var j = 0; j < enemies.length; j++) {
- if (bullets[i].isCollidingWith(enemies[j]) && !bullets[i].isEnemyBullet) {
- enemies.splice(j, i)
- }
- if (bullets[i].isCollidingWith(ship)) {
- init();
- }
- }
- if (bullets[i].y < 0 || bullets[i].y > 240) {
- bullets.splice(i, 1);
- }
- }
- for (var i =0; i < enemies.length; i++) {
- enemies[i].update();
- }
- secs = (eTime/60);
- if (secs % spawnRate == 0.5) {
- spawnEnemies();
- }
- }
- function render() {
- cls();
- map(0);
- spr(1, ship.x, ship.y, 0);
- for (var i=0; i < bullets.length; i++) {
- bullets[i].render();
- }
- for (var i=0; i < enemies.length; i++) {
- enemies[i].render();
- }
- }
- init()
- function TIC() {
- update();
- render();
- }
Advertisement
Add Comment
Please, Sign In to add comment