Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // tslint:disable member-ordering
  2.  
  3. class Game {
  4.     // Global attributes for canvas
  5.     // Readonly attributes are read-only. They can only be initialized in the constructor
  6.     private readonly canvas: HTMLCanvasElement;
  7.     private readonly ctx: CanvasRenderingContext2D;
  8.  
  9.     // Some global player attributes
  10.     private readonly player: string;
  11.     private readonly score: number;
  12.     private readonly lives: number;
  13.     private readonly highscores: object[]; // TODO: do not use 'any': write an interface!
  14.  
  15.     public constructor(canvasId: HTMLCanvasElement) {
  16.         // Construct all of the canvas
  17.         this.canvas = canvasId;
  18.         this.canvas.width = window.innerWidth;
  19.         this.canvas.height = window.innerHeight;
  20.         // Set the context of the canvas
  21.         this.ctx = this.canvas.getContext("2d");
  22.  
  23.         this.player = "Player one";
  24.         this.score = 400;
  25.         this.lives = 3;
  26.  
  27.         this.highscores = [
  28.             {
  29.                 playerName: "Loek",
  30.                 score: 40000,
  31.             },
  32.             {
  33.                 playerName: "Daan",
  34.                 score: 34000,
  35.             },
  36.             {
  37.                 playerName: "Rimmert",
  38.                 score: 200,
  39.             },
  40.         ];
  41.  
  42.         // All screens: uncomment to activate
  43.         this.startScreen();
  44.         // this.levelScreen();
  45.         // this.titleScreen();
  46.  
  47.     }
  48.  
  49.     // -------- Splash screen methods ------------------------------------
  50.     /**
  51.      * Method to initialize the splash screen
  52.      */
  53.     public startScreen() {
  54.         // 1. add 'Asteroids' text
  55.         this.writeTextToCanvas("Asteroids", 140, this.canvas.width / 2, 150);
  56.  
  57.         // 2. add 'Press to play' text
  58.         this.writeTextToCanvas("PRESS PLAY TO START", 40, this.canvas.width / 2, this.canvas.height / 2 - 20);
  59.  
  60.         // 3. add button with 'start' text
  61.         const asteroidFileName = "./assets/images/SpaceShooterRedux/PNG/UI/buttonBlue.png";
  62.         this.loadImage(asteroidFileName, this.writeStartButtonToStartScreen);
  63.         // 4. add Asteroid image
  64.         const startButtonFileName = "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_big1.png";
  65.         this.loadImage(startButtonFileName, this.writeAsteroidImageToStartScreen);
  66.     }
  67.  
  68.     /**
  69.      * Writes the loaded asteroids image pixels to the start screen
  70.      *
  71.      * @param {HTMLImageElement} img the loaded image object
  72.      */
  73.     private writeAsteroidImageToStartScreen(img: HTMLImageElement) {
  74.         // Target position: center of image must be the center of the screen
  75.         const x = this.canvas.width / 2 - img.width / 2;
  76.         const y = this.canvas.height / 2 + img.height / 2;
  77.  
  78.         this.ctx.drawImage(img, x, y);
  79.     }
  80.  
  81.     /**
  82.      * Writes the loaded start button image to the start screen and writes a text on top of it
  83.      *
  84.      * @param {HTMLImageElement} img the loaded image object
  85.      */
  86.     private writeStartButtonToStartScreen(img: HTMLImageElement) {
  87.         const x = this.canvas.width / 2;
  88.         const y = this.canvas.height / 2 + 219; // 219 is a nice spot for the button
  89.  
  90.         this.ctx.drawImage(img, x  - img.width / 2, y);
  91.  
  92.         this.writeTextToCanvas("Play", 20, x, y + 26, "center", "black");
  93.     }
  94.  
  95.     // -------- level screen methods -------------------------------------
  96.     /**
  97.      * Method to initialize the level screen
  98.      */
  99.     public levelScreen() {
  100.         // 1. load life images
  101.         const lifeImageFileName = "./assets/images/SpaceShooterRedux/PNG/UI/playerLife1_blue.png";
  102.         this.loadImage(lifeImageFileName, this.writeLifeImagesToLevelScreen);
  103.  
  104.         // 2. draw current score
  105.         this.writeTextToCanvas(`Your score: ${this.score}`, 20, this.canvas.width - 100, 30, "right");
  106.  
  107.         // 3. draw random asteroids
  108.         const asteroids: string[] = [
  109.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_big1.png",
  110.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_big2.png",
  111.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_big3.png",
  112.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_big4.png",
  113.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_med1.png",
  114.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_med3.png",
  115.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_small1.png",
  116.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_small2.png",
  117.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_tiny1.png",
  118.             "./assets/images/SpaceShooterRedux/PNG/Meteors/meteorBrown_tiny2.png",
  119.         ];
  120.  
  121.         const maxAsteroidsOnScreen: number = 5;
  122.  
  123.         for (let i = 0; i < maxAsteroidsOnScreen; i++) {
  124.             const index = this.randomNumber(0, asteroids.length);
  125.             // we use the random number to select a file name from the array
  126.             this.loadImage(asteroids[index], this.writeAsteroidImageToRandomLocationOnLevelScreen);
  127.         }
  128.  
  129.         // 4. draw player spaceship
  130.         const playerSpaceShipFileName = "./assets/images/SpaceShooterRedux/PNG/playerShip1_blue.png";
  131.         this.loadImage(playerSpaceShipFileName, this.writePlayerShipToLevelScreen);
  132.     }
  133.  
  134.     /**
  135.      * Uses the loaded life image to remaining lives of the player on the rop
  136.      * left of the screen.
  137.      *
  138.      * @param {HTMLImageElement} img the loaded image object
  139.      */
  140.     private writeLifeImagesToLevelScreen(img: HTMLImageElement) {
  141.         let x = 10;
  142.         const y = img.height - 10;
  143.         // Start a loop for each life in lives
  144.         for (let life = 0; life < this.lives; life++) {
  145.             // Draw the image at the curren x and y coordinates
  146.             this.ctx.drawImage(img, x, y);
  147.             // Increase the x-coordinate for the next image to draw
  148.             x += img.width + 10;
  149.         }
  150.     }
  151.  
  152.  
  153.     /**
  154.      * Writes a loaded asteroid image at a random location on the screen.
  155.      *
  156.      * @param {HTMLImageElement} img the loaded image object
  157.      */
  158.     private writeAsteroidImageToRandomLocationOnLevelScreen(img: HTMLImageElement) {
  159.         const x = this.randomNumber(0, this.canvas.width - img.width);
  160.         const y = this.randomNumber(0, this.canvas.height - img.height);
  161.         this.ctx.drawImage(img, x, y);
  162.     }
  163.  
  164.     /**
  165.      * Writes the loaded Player Ship image to the center of the screen
  166.      *
  167.      * @param {HTMLImageElement} img the loaded image object
  168.      */
  169.     private writePlayerShipToLevelScreen(img: HTMLImageElement) {
  170.         // Target position: center of image must be the center of the screen
  171.         const x = this.canvas.width / 2 - img.width / 2;
  172.         const y = this.canvas.height / 2 - img.height / 2;
  173.         this.ctx.drawImage(img, x, y);
  174.     }
  175.  
  176.     // -------- Title screen methods -------------------------------------
  177.  
  178.     /**
  179.      * Method to initialize the title screen
  180.      */
  181.     public titleScreen() {
  182.         const x = this.canvas.width / 2;
  183.         let y = this.canvas.height / 2;
  184.  
  185.         // 1. draw your score
  186.         this.writeTextToCanvas(`${this.player} score is ${this.score}`, 80, x, y - 100);
  187.  
  188.         // 2. draw all highscores
  189.         this.writeTextToCanvas("HIGHSCORES", 40, x, y);
  190.  
  191.         for (let i = 0; i < this.highscores.length; i++) {
  192.             y += 40;
  193.             const text = `${i + 1}: ${this.highscores[i].playerName} - ${this.highscores[i].score}`;
  194.             this.writeTextToCanvas(text, 20, x, y);
  195.         }
  196.     }
  197.  
  198.     // -------Generic canvas methods ----------------------------------
  199.  
  200.     /**
  201.      * Writes text to the canvas
  202.      * @param {string} text - Text to write
  203.      * @param {number} fontSize - Font size in pixels
  204.      * @param {number} xCoordinate - Horizontal coordinate in pixels
  205.      * @param {number} yCoordinate - Vertical coordinate in pixels
  206.      * @param {string} alignment - Where to align the text
  207.      * @param {string} color - The color of the text
  208.      */
  209.     public writeTextToCanvas(
  210.         text: string,
  211.         fontSize: number = 20,
  212.         xCoordinate: number,
  213.         yCoordinate: number,
  214.         alignment: CanvasTextAlign = "center",
  215.         color: string = "white",
  216.     ) {
  217.         this.ctx.font = `${fontSize}px Minecraft`;
  218.         this.ctx.fillStyle = color;
  219.         this.ctx.textAlign = alignment;
  220.         this.ctx.fillText(text, xCoordinate, yCoordinate);
  221.     }
  222.  
  223.  
  224.     /**
  225.      * Loads an image file into the DOM and writes it to the canvas. After the
  226.      * image is loaded and ready to be drawn to the canvas, the specified
  227.      * callback method will be invoked. the method will be called with the
  228.      * loaded imageElement as a parameter.
  229.      *
  230.      * The callback method MUST be a method of this class with a header like:
  231.      *
  232.      *   private yourMethodNameHere(img: HTMLImageElement)
  233.      *
  234.      * In the body of that callback you can draw the image to the canvas
  235.      * context like:
  236.      *
  237.      *   this.ctx.drawImage(img, someX, someY);
  238.      *
  239.      * This is the simplest way to draw images, because the browser must and
  240.      * shall wait until the image is completely loaded into memory.
  241.      *
  242.      * @param {string} source - the name of the image file
  243.      * @param {Function} callback - method that is invoked after the image is loaded
  244.      */
  245.     private loadImage(source: string, callback: Function) {
  246.         const imageElement = new Image();
  247.  
  248.         // We must wait until the image file is loaded into the element
  249.         // We add an event listener
  250.         // We'll be using an arrow function for this, just because we must.
  251.         imageElement.addEventListener("load", () => {
  252.             callback.apply(this, [imageElement]);
  253.         });
  254.  
  255.         // Now, set the src to start loading the image
  256.         imageElement.src = source;
  257.     }
  258.  
  259.     /**
  260.      * Renders a random number between min and max
  261.      * @param {number} min - minimal time
  262.      * @param {number} max - maximal time
  263.      */
  264.     public randomNumber(min: number, max: number): number {
  265.         return Math.round(Math.random() * (max - min) + min);
  266.     }
  267. }
  268.  
  269. // This will get an HTML element. I cast this element in de appropriate type using <>
  270. let init = function() {
  271.     const Asteroids = new Game(document.getElementById("canvas") as HTMLCanvasElement);
  272. };
  273.  
  274. // Add EventListener to load the game whenever the browser is ready
  275. window.addEventListener("load", init);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement