Game Tutorial 3

Objective

  • Create enemy object that moves from the top of frame and to the bottom.
  • Reset the enemy with new x position and speed if it hits the bottom of frame.

Code

**View source code:game-tutorial3.js

I will only explain the code that is new or updated from the previous tutorial.

var enemy = {
  x: null,
  y: null,
  text: "X",
  turnCount: 0,
  turnCountMax: 5,
};

enemy object is created. The values for x and y is null which means they will be assigned later. turnCount and turnCountMax will be explain later in this post.

function calculate(){
  // check key and move player
  if(TMI.keyboard.checkKey(KEYSET.LEFT) && player.x>2) player.x--;
  if(TMI.keyboard.checkKey(KEYSET.UP) && player.y>1) player.y--;
  if(TMI.keyboard.checkKey(KEYSET.RIGHT) && player.x+player.text.length<frame.width-2) player.x++;
  if(TMI.keyboard.checkKey(KEYSET.DOWN) && player.y<frame.height-2) player.y++;

  //reset enemy
  if(enemy.y===null || enemy.y>frame.height-3){
    resetEnemy();
  }

  //move enemy
  if(++enemy.turnCount>enemy.turnCountMax){
    enemy.turnCount = 0;
    enemy.y++;
  }
}

The code added under //reset enemy and //move enemy.

//reset enemy: If it the beginning of the program(enemy.y===null)or enemy hits the bottom line of frame, it calls resetEnemy function.

//move enemy: enemy.turnCount increases by 1 every time calculate function is called. It moves enemy down and returns to 0 if it it's bigger than enemy.turnCountMax. Therefore enemy.turnCountMax determines the speed of enemy and it's fester when it's smaller.

function draw(){
  //clearScreen
  TMS.clearScreen();

  //draw score
  TMS.insertTextAt(frame.x,frame.y-1,"Score: ");
  TMS.insertText(frame.score);

  //draw frame
  for(var i=0; i<frame.height; i++){
    for(var j=0; j<frame.width; j++){
      if((i===0 || i==frame.height-1 || j===0 || j==frame.width-2)&&(j%2 === 0)){
        TMS.insertTextAt(frame.x+j,frame.y+i,"■");
      }
    }
  }

  //draw player
  TMS.insertTextAt(frame.x+player.x,frame.y+player.y,player.text);

  //draw enemy
  TMS.insertTextAt(frame.x+enemy.x,frame.y+enemy.y,enemy.text);
}

Code added to draw enemy under //draw enemy.

function resetEnemy(){
  enemy.x = 2+Math.floor(Math.random()*(frame.width-4));
  enemy.y = 1;
  enemy.turnCount = 0;
  enemy.turnCountMax = 3+Math.floor(Math.random()*10);
}

It's a function reset enemy.

Run Example

enemy is created and move by itself.

Comments

Add Comment

Login with SNS account to write comments. see details

UP