Game Tutorial 3


  • 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.


**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){

  //move enemy
    enemy.turnCount = 0;

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(){

  //draw score
  TMS.insertTextAt(frame.x,frame.y-1,"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)){

  //draw player

  //draw enemy

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.


Add Comment

Login with SNS account to write comments. see details