Tag Archives: coding

Creating an emoji chase game with WoofJS

In this tutorial, you will learn how to create a game where the player is being chased and has to keep running for as long a possible without getting caught by the flying emoji. The smiley emoji has to avoid being caught by the ghost emoji. You can customise this game as much as you like with your own characters.

emojirun

Step 1

Go to woofjs.com, login and create a new project. The first thing we will do is change the backdrop colour. You can either provide the name of the desired colour eg. setBackdropColor(“green”) or if you want to use a specific colour you can use a colour code (colour codes begin with a # and contain a combination of 6 numbers and letters from a to f). You can find colour codes at www.codemahal.com/colourpicker. You can also use an image for your backdrop if you like (refer to the previous two tutorials).

Add the following line of code for a light green backdrop:

setBackdropColor("#8CFFC2")

emoji1

Step 2

Now we will create the player sprite. For the player sprite will use an emoji image, set its width and height to 40 and position it in the middle of the screen (0 on the x and y axis). Add the following code:

var player = new Image({
   url: “http://www.codemahal.com/sprites/smiley.png”,
   height: 40,
   width: 40,
   x:0,
   y:0
})

Tip: All of this code can be squashed into one line but to make it easier to read here, each property for the player variable has been added on a new line.

emoji2

Step 3

Next, we can add the “Game over” message text and “Press P to play again” text which will display on screen at the end of the game. Once you have added the two text objects, set them to be hidden using the gameOverText.hide() and playAgainText.hide() lines.

Add the following code:

var gameOverText = new Text({
  x: 0,
  y: 80,
  fontFamily: "Lato",
  size: 30,
  color: "#0B9957",
  text: "Game over!"
});
var playAgainText = new Text({
  x: 0,
  y: 40,
  fontFamily: "Lato",
  size: 20,
  color: "#0B9957",
  text: "Press P to play again"
});

gameOverText.hide()
playAgainText.hide()

Step 4

Now we can add movement for the player object. To do this, create a forever loop and add if statements checking if the arrow keys have been pressed on the keyboard. Add the relevant movement on the x or y axis for the player object in each if statement. Here is the code:

forever(() => {
  if (keysDown.includes('UP')) {
    player.y += 7;
  }
  if (keysDown.includes('DOWN')) {
    player.y -= 7;
  }
  if (keysDown.includes('RIGHT')) {
    player.x += 7;
  }
  if (keysDown.includes('LEFT')) {
    player.x -= 7;
  }
});

Now you should be able to move the player object (smiley emoji) around the screen using the arrow keys on the keyboard.

emoji3

Step 5

Now that we are able to move the player around, we can add enemies (in the form of ghost emojis) that will spawn in random locations at each edge of the screen pointing towards the player. Firstly, we create an empty array (an array is like a list) called enemies which will be used to store all of the enemy clones that will spawn during the game.

We will use the same enemy sprite (a ghost emoji) for each individual enemy but every half a second, clone the enemy sprite and then use random number variable to determine which position the enemy clone should start from at different edges of the screen. Once the enemy clone spawns at a random location at the edge of the screen it will be pointed towards the player and added to the enemies array.

var enemies = [];
every(0.5, "seconds", () => {
  var enemy = new Image({
    url: "http://www.codemahal.com/sprites/ghost.png",
    height: 30,
    width: 30,
    x: 0,
    y: 0
  })
  var randomNumber = random(1, 4);
  if (randomNumber == 1) {
    enemy.x = randomX();
    enemy.y = maxY;
  }
  if (randomNumber == 2) {
    enemy.x = randomX();
    enemy.y = minY;
  }
  if (randomNumber == 3) {
    enemy.x = maxX;
    enemy.y = randomY();
  }
  if (randomNumber == 4) {
    enemy.x = minX;
    enemy.y = randomY();
  }
  enemy.pointTowards(player.x, player.y);
  enemies.push(enemy);
});

emoji4

Step 6

Now that we can clone enemy sprites at different edges of the screen and point them towards the player, we will need to actually make them move towards the player. We can add a forever loop which will constantly get each individual enemy clone in the enemies array and move them (remember, each enemy clone is pointing towards the position of where the player was when that enemy clone spawned, so the enemy clones will move towards the player). We also make sure that each cloned enemy sprite is showing. Add the following code:

forever(() => {
  enemies.forEach(enemy => {
    enemy.move(6);
    enemy.show()
  })
});

emoji5

Step 7

Now we can setup the timer which records how long the player has been running around for without being caught by an enemy. First, we create a timer variable set to 0. Then we create the text which will display the timer on screen. Then, every second we increase the timer by 1 and display the updated time on screen. Add the following code:

var timer = 0
var timerText = new Text({
  x: 0,
  y: maxY - 60,
  fontFamily: "Lato",
  size: 30,
  color: "red",
  text: () => 'Timer: ' + timer
});

every(1, "second", () => {
  timer++;
  timerText.text = 'Timer: ' + timer
});

At this point this is what the game should look like:

emoji6

Step 8

Now we can add a forever loop which will go through each enemy that exists in the enemies array and check if they are touching the player. If an enemy touches the player, then the “Game over” and “Press P to play again” text will be displayed on screen. The player object will also be hidden and the freeze() function will be called which will freeze the screen.

forever(() => {
  enemies.forEach(enemy => {
    if (enemy.touching(player)) {
      gameOverText.show()
      playAgainText.show()
      player.hide()
      freeze();
    }
  })
});

emoji7

Step 9

Next, we add another forever loop. In this forever loop we check if the P key is pressed on the keyboard and if so, then show the player object on screen, hide the “Game over” and “Press P to play again” messages, and go through all the enemy clones which exist in the enemies array and delete each one. The enemies array is set to be an empty array again, the timer is set to 0, the player object is moved back to the centre of the screen, and the defrost() function is called which un-freezes the game. Add the following code:

forever(() => {
  if(keysDown.includes("P")){
    player.show()
    gameOverText.hide()
    playAgainText.hide()
    enemies.forEach(enemy => enemy.delete())
    enemies = []
    timer = 0
    player.x = 0
    player.y = 0
    defrost();
  }
})

emoji8

Step 10

The final step is to add some code which will ensure the player cannot leave the screen. By adding the following code in a forever loop, we can constantly check if the player is going beyond any edges of the screen, and if so, stop them going any further. Add the following code to your game:

forever(() => {
  if (player.x > maxX) {
    player.x = maxX;
  }
  if (player.x < minX) {
    player.x = minX;
  }
  if (player.y > maxY) {
    player.y = maxY;
  }
  if (player.y < minY) {
    player.y = minY;
  }
});

This is what the game and code will look like once you’re done!

emoji9

Now play your game and see how long you can last without getting caught by a ghost emoji! You can try adding a high score feature to the game and also adjust some of the variables to increase or decrease the speed of the enemy movements depending on how challenging you want the game to be. You could have the enemies start off moving slowly and gradually build up speed over time too. Make sure you save your work!

Complete code

// Based on the game at woofjs.com/create.html#poop-emoji

setBackdropColor("#8CFFC2")
var player = new Image({
  url: "http://www.codemahal.com/sprites/smiley.png",
  height: 40,
  width: 40,
  x: 0,
  y: 0
}) 

var gameOverText = new Text({
  x: 0,
  y: 80,
  fontFamily: "Lato",
  size: 30,
  color: "#0B9957",
  text: "Game over!"
});
var playAgainText = new Text({
  x: 0,
  y: 40,
  fontFamily: "Lato",
  size: 20,
  color: "#0B9957",
  text: "Press P to play again"
});

gameOverText.hide()
playAgainText.hide()

forever(() => {
  if (keysDown.includes('UP')) {
    player.y += 7;
  }
  if (keysDown.includes('DOWN')) {
    player.y -= 7;
  }
  if (keysDown.includes('RIGHT')) {
    player.x += 7;
  }
  if (keysDown.includes('LEFT')) {
    player.x -= 7;
  }
});

var enemies = [];
every(0.5, "seconds", () => {
  var enemy = new Image({
    url: "http://www.codemahal.com/sprites/ghost.png",
    height: 30,
    width: 30,
    x: 0,
    y: 0
  })
  var randomNumber = random(1, 4);
  if (randomNumber == 1) {
    enemy.x = randomX();
    enemy.y = maxY;
  }
  if (randomNumber == 2) {
    enemy.x = randomX();
    enemy.y = minY;
  }
  if (randomNumber == 3) {
    enemy.x = maxX;
    enemy.y = randomY();
  }
  if (randomNumber == 4) {
    enemy.x = minX;
    enemy.y = randomY();
  }
  enemy.pointTowards(player.x, player.y);
  enemies.push(enemy);
});

forever(() => {
  enemies.forEach(enemy => {
    enemy.move(6);
    enemy.show()
  })
});

var timer = 0
var timerText = new Text({
  x: 0,
  y: maxY - 60,
  fontFamily: "Lato",
  size: 30,
  color: "red",
  text: () => 'Timer: ' + timer
});

every(1, "second", () => {
  timer++;
  timerText.text = 'Timer: ' + timer
});

forever(() => {
  enemies.forEach(enemy => {
    if (enemy.touching(player)) {
      gameOverText.show()
      playAgainText.show()
      player.hide()
      freeze();
    }
  })
});

forever(() => {
  if (keysDown.includes("P")) {
    player.show()
    gameOverText.hide()
    playAgainText.hide()
    enemies.forEach(enemy => enemy.delete())
    enemies = []
    timer = 0
    player.x = 0
    player.y = 0
    defrost();
  }
})

forever(() => {
  if (player.x > maxX) {
    player.x = maxX;
  }
  if (player.x < minX) {
    player.x = minX;
  }
  if (player.y > maxY) {
    player.y = maxY;
  }
  if (player.y < minY) {
    player.y = minY;
  }
});

Coding an apple catcher game with WoofJS

In this tutorial, you will learn how to create an apple catcher game using JavaScript code in WoofJS. The aim of the game is to catch as many falling apples as you can and beat the high score.

applegame

Step 1

Add a background (backdrop) for the game. You can make your own backdrop or use one provided at codemahal.com/sprites such as the sky background used below.

To add a backdrop, use the following line of code with the link (URL) to your backdrop image:

setBackdropURL('http://www.codemahal.com/sprites/sky_background.png')

apple1

Step 2

The next step involves creating a variable that will store the user’s high score and display the high score text on screen. Firstly, we will create a highScore variable. In order to save the high score we will need to access to the user’s local storage using the code localStorage.getItem. We will store the high score in the user’s storage using the name “userhighscore”. However, if this is the user’s first time playing the game and they have no high score, then the high score will be set to 0. Add the following line of code:

var highScore = localStorage.getItem("userhighscore") || 0;

The line of code above basically can be interpreted as: When the game begins create a variable in the game called highScore, and set it to store the high score value that was saved last time this game was played by the user (using the name “userhighscore”), or if no high score exists then set the high score to 0.

Next, display the high score on screen using the following code:

var highScoreText = new Text({
  text: () => "High score: " + highScore,
  x: minX + 20,
  y: maxY - 20,
  size: 24,
  fontFamily: 'Arial',
  color: "yellow",
  textAlign: "left"
})

Your game should now look like this:

apple2

Step 3

Now that we have the high score displayed on screen we can go ahead and add the text heading for the current score on screen using the following code:

var scoreHeadingText = new Text({
  text: "Score:",
  x: 0,
  y: 100,
  size: 30,
  color: "blue",
  fontFamily: "Arial",
  textAlign: "center"
})

Your game should now look like this:

apple3

Step 4

When the game ends we will want to display a “Game over” message to the user and ask the user if they wish to play again. We can create this text to display on screen stored in two variables (gameOverText and playAgainText) and hide the text immediately so it doesn’t display until the game is over. Add the following lines of code:

var gameOverText = new Text({
  text: "GAME OVER",
  x: 0,
  y: 0,
  size: 50,
  color: "red",
  fontFamily: "Arial",
  textAlign: "center"
})

var playAgainText = new Text({
  text: "Press P to play again",
  x: 0,
  y: -50,
  size: 20,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

gameOverText.hide()
playAgainText.hide()

apple4

Step 5

Next, we create a variable to store the score for the current game which will be set to 0 at the beginning of the game, and we create the text to display the current score on screen (under the score heading text).

var score = 0;
var scoreText = new Text({
  text: score,
  x: 0,
  y: 60,
  size: 32,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

apple5

Step 6

Now we can create the apple and player object. The apple will be represented by a circle and the player will be represented by a rectangle/bar which can move left and right. To add the apple and player object, add the following code:

var apple = new Circle({
  radius: 10,
  color: "red",
  x: random(-160, 160),
  y: maxY-50
})

var player = new Rectangle({
  width: 40,
  x: 0,
  y: minY+20,
  height: 20,
  color: "green"
})

The game should now look like this:

apple6

Step 7

Now that we have created the apple and player objects, we can set the speed at which the apple will fall to the ground (eg. 8) and the player movement which will be controlled by the mouse (when the mouse moves left the rectangle moves left, when the mouse moves right the rectangle moves right). In a forever loop, we will make the rectangle (player) follow the position of the mouse movement on the x axis and make the apple fall at the set speed in a negative direction (down) on the y axis). Add the following code:

var appleSpeed = 8
forever(() => {
  player.x = mouseX
  apple.y -= appleSpeed
})

You’ll notice once the apple falls past the bottom of the screen it will keep falling! We will add some code shortly which will make the apple respawn at the top of the screen again.

apple7

Step 8

Inside the forever loop we just added, we can add code which will check if the apple is touching the player (rectangle) and if so, we will move the apple back to the top of the screen (on y axis) and in a random position across the screen (on x axis) so it can fall again. We will also increase the current score by 1, update the score text on screen to reflect the current score, check if the current score is higher than the high score and if so, update the high score. Make sure you close all brackets for the forever loop and if statements.

Add the following code inside the forever loop we added in the previous step:

if (apple.touching(player)) {
    apple.x = random(-160, 160)
    apple.y = maxY-50
    score = score + 1;
    scoreText.text = score;
    if (score > highScore) {
      highScore = score
      localStorage.setItem("userhighscore", highScore)
    }
}

apple8

Step 9

Now we need to add code which will end the game if the apple falls and the player doesn’t catch it (in other words, if the apple falls below the bottom edge of the screen). This will display the “Game over” message on screen and ask the player to press P to play again. We created this text earlier but it is hidden while the game is running. By adding the code below, the “Game over” and “Press P to play again” text will show at the end of the game.

Add the following code inside the forever loop we used in the previous steps. This code will check if the apple has fallen below the bottom edge of the screen, and if it has then the “Game over” and “Press P to play again” text will be displayed on screen.

if (apple.y < minY) {
    gameOverText.show()
    playAgainText.show()
}

When the game ends the screen should look like this:

apple9

Step 10

When the game ends, the player should be given an opportunity to play again. We can use an if statement to check if the P key on the keyboard is pressed by the user. If the P key is pressed we can set the score back to 0, reset the score text on screen to reflect a score of 0, hide the gameOverText and playAgainText text objects, and move the apple back up to the top of the screen so it can start falling again and so the player can start catching apples again. The apple speed will also be reset to 8 (in the next step we will make the apple speed increase over time). Add the following code inside the forever loop:

if (keysDown.includes('P')) {
    score = 0
    scoreText.text = score;
    gameOverText.hide()
    playAgainText.hide()
    apple.x = random(-160, 160)
    apple.y = maxY – 50
    appleSpeed = 8
}

This is what the game should now look like:

apple10

The last step is to add extra challenge to the game which involves making the apple’s speed increase over time. We can add some code so that every 10 seconds the apple’s falling speed variable will increase by 1. Outside the forever loop and at the very end of the code, add the following lines of code:

every(10, "seconds", () => {
  appleSpeed = appleSpeed + 1
})

And that’s it! This is what the completed game should look like:

apple11

Make sure you save your code! If you click on the  icon at the top right corner of the screen then the game will open in full screen in a new tab. You can also share the link in that tab with your friends so they can play your game.

What next?

  • Try changing the code so the game makes more use of the space available when playing in full screen
  • Try using keyboard controls to move the player object rather than the mouse
  • You could use an apple image instead of a circle for the apple object
  • You could also add sound effects or background music

The complete code

setBackdropURL('http://www.codemahal.com/sprites/sky_background.png')
var highScore = localStorage.getItem("userhighscore") || 0;
var highScoreText = new Text({
  text: () => "High score: " + highScore,
  x: minX + 20,
  y: maxY - 20,
  size: 24,
  fontFamily: 'Arial',
  color: "yellow",
  textAlign: "left"
})

var scoreHeadingText = new Text({
  text: "Score:",
  x: 0,
  y: 100,
  size: 30,
  color: "blue",
  fontFamily: "Arial",
  textAlign: "center"
})

var gameOverText = new Text({
  text: "GAME OVER",
  x: 0,
  y: 0,
  size: 50,
  color: "red",
  fontFamily: "Arial",
  textAlign: "center"
})

var playAgainText = new Text({
  text: "Press P to play again",
  x: 0,
  y: -50,
  size: 20,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

gameOverText.hide()
playAgainText.hide()

var score = 0;
var scoreText = new Text({
  text: score,
  x: 0,
  y: 60,
  size: 32,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

var apple = new Circle({
  radius: 10,
  color: "red",
  x: random(-160, 160),
  y: maxY - 50
})

var player = new Rectangle({
  width: 40,
  x: 0,
  y: minY + 20,
  height: 20,
  color: "green"
})

var appleSpeed = 7
forever(() => {
  player.x = mouseX
  apple.y -= appleSpeed

  if (apple.touching(player)) {
    apple.x = random(-160, 160)
    apple.y = maxY - 50
    score = score + 1;
    scoreText.text = score;
    if (score > highScore) {
      highScore = score
      localStorage.setItem("userhighscore", highScore)
    }
  }

  if (apple.y < minY) {
    gameOverText.show()
    playAgainText.show()
  }

  if (keysDown.includes('P')) {
    score = 0
    scoreText.text = score;
    gameOverText.hide()
    playAgainText.hide()
    apple.x = random(-160, 160)
    apple.y = maxY - 50
    appleSpeed = 8
  }

})

every(10, "seconds", () => {
  appleSpeed = appleSpeed + 1
})

Creating your first 2D game in WoofJS

In this tutorial, you will learn how to code your first 2D game in the JavaScript programming language using WoofJS – a free website for coding games! To get started making your own games in JavaScript, go to www.woofjs.com and click Start Coding.

The first game we will make is a 2D game where you have to move around and using the keyboard to catch as many monsters as you can in 20 seconds.

catchmonster

Step 1

Make sure you create your free account so you can save your games to your profile. Click on Login / Sign up and then provide your email address. On the next screen.

woof_step1

Step 2

Once you have created your account and logged in, click on your account name in the top left corner and then click New Project.

woof_step2

Step 3

A new empty project will open. Click on Save in the top right corner. Make sure you save your work regularly while you are coding.

woof_step3_a

Then give your project a name and click OK.

woof_step3_b

This is what the WoofJS window looks like…

woof_step3_c

Step 4

As you can see in the image above, there is already one line of code there. This line of code is used to specify the background for the game (or at least this part of the game – you might have many different levels and menus in your game, but let’s just start with one level). setBackdropURL is a function which takes a link (also known as URL, or Uniform Resource Locator) to an image (such as a GIF, PNG or JPG) and uses that image for the background or backdrop.

The link goes inside brackets and single quotes (you can use single or double quotes but they must be matching). For example, for a grass background add this code using the free image on CodeMahal.com:

setBackdropURL("http://www.codemahal.com/sprites/grass_background.png")

Tip: You can create your own game sprites (backgrounds, characters and other objects) at piskellapp.com and use those sprites in your WoofJS game. You can also download free sprites to use in your project from codemahal.com/sprites.

So now we have a nice grass backdrop for the game. The game can be played in full screen but at the moment we can just see a preview of it on the left side of the screen.

woof_step4

Step 5

Now that we have a backdrop, we can add our first character to the game which will be the player. We can use an image sprite for the player too so we will need to specify the image to use for the player before we can specify its width, height, position, etc.

Add the following line of code to specify the image sprite to use for the player:

var playerImage = 'http://www.codemahal.com/sprites/player.gif';

You have just used the var keyword to create a variable. A variable is like a container that is used to store some information. Variables can store numbers or text among other things. We use the var keyword and then specify the name of the variable – this variable’s name is playerImage and will store the link to the image which we will use for the character. Variable names can’t contain spaces and must begin with a lowercase letter – these are part of the rules of the JavaScript language.

There are rules that you must follow in programming language such as ending a statement/line with a semi-colon, using certain brackets, and correctly spelling keywords used in a language, for example, var and if. These rules are known as the programming language syntax. Because the image link is stored in a variable, whenever we want to use the image we just have to refer to the variable by its name rather than having to type in the long link every single time.

Step 6

At this point you should have a backdrop and specified the image for the player’s character in the game. You won’t be able to see the player sprite yet because we haven’t specified how big it should be and where it should be placed on the screen. To do that, you need to add the following code:

 

var player = new Image({
  url: playerImage,
  width: 32,
  height: 32,
  x: 0,
  y: 0
})

In the code above, we create a variable called player and use the image from the playerImage variable to represent the player character. We then specify the width and height of the player. Lastly, we specify the x and y position of the player on the screen (x is horizontal axis across screen, y is vertical axis). Hint: x: 0, y: 0 is the centre of the screen.

This is what you should now see on your screen:

woof_step5

Step 7

Now that we have the player in your game, we can add an enemy to chase after (a not-so-scary monster). We will firstly specify the image sprite to use for the enemy and then we will create the enemy object in the game specifying its sprite url, width, height, and initial position on the screen (x and y axes). We will make the x position of the enemy 60 so that it is next to the player (and not on top of it). To do this, add the following code:

var enemyImage = 'http://www.codemahal.com/sprites/enemy.png';
var enemy = new Image({
  url: enemyImage,
  width: 32,
  height: 32,
  x: 60,
  y: 0
})

This is what your game should now look like with the player and enemy next to each other in front of a grass backdrop:

woof_step7

Step 8

The next step is to make the player move! To do this, we need to check which keys on the keyboard are being pressed. We can use the up and down arrows on the keyboard to move the player up and down. We can also use the left and right keys on the keyboard to move the player left and right. Rather than just checking if a key has been pressed, we can check if keys are currently being pressed.

We can use a forever loop to keep checking if keys are being pressed. We can also use includes to check if multiple keys are being pressed at the same time instead of just checking one key at a time.

Create a forever loop and inside that forever loop you can add if statements that check if a key is being pressed and then move the player on the x or y axis in the direction according to the key that is being pressed.

woof_step8a

woof_step8b

Here is the code you need to add which will make the player move 5 spaces in the direction of the arrow key that is pressed on the keyboard:

forever(() => {
  if (keysDown.includes('LEFT')) {
    player.x -= 5
  }

  if (keysDown.includes('RIGHT')) {
    player.x += 5
  }

  if (keysDown.includes('UP')) {
    player.y += 5
  }

  if (keysDown.includes('DOWN')) {
    player.y -= 5
  }  
})

Your code and game should now look like this. If you click in the game preview window you can use the left, right, up, and down keys to move your character around!

woof_step8c

Tip: You can find different pieces of code to use for movement by clicking on Motion. You can use different pieces of code for control (eg. check if a condition is true, or repeat instructions) by clicking on Control. You can also find code for checking keypresses by clicking on Sensing.

Step 9

Now that we have a player and an enemy, we will need to allow them to interact. The aim of this game will be to catch as many enemies as possible in 20 seconds. When you catch an enemy another one will appear in a random location. A timer counts down from 20 seconds and the score is counted and displayed on screen.

Before we allow the player to catch an enemy, we will add text on screen to display the score, countdown timer, ‘Game over’ message, and ‘Press P to play again’ message that displays at the end of the game.

To add text on screen, you need to create a variable that will store the different text properties including the actual text displayed, font size, colour, font family, alignment, and x and positions on the screen.

Add the following code between the code you added to create the enemy sprite and the forever loop:

var scoreText = new Text({
  text: () => "Score: 0",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: minX + 20,
  y: maxY - 20
})

var timerText = new Text({
  text: () => "Time remaining: 20",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: maxX - 160,
  y: maxY - 20
})

var gameOverText = new Text({
  text: () => "GAME OVER!",
  size: 40,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 60
})

var playAgainText = new Text({
  text: () => "Press P to play again",
  size: 20,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 0
})

Your game should now look like this:

woof_step9

Step 10

Now we need to set the score to be 0 at the beginning of the game and set the timer to 20 at the beginning of the game (as the counter will count down from 20 to 0 seconds). Create a new variable called score and give it a value of 0. Then create a variable called time and give it a value of 0. We also don’t want the ‘Game over’ message or ‘Press P to play again’ message to display until after the game ends, so we will set these text objects to be hidden using the .hide() function. To do this, add the following code after the code you just added for the on-screen text:

var score = 0;
var time = 20;
gameOverText.hide()
playAgainText.hide()

After adding this code, you should now see that the ‘Game over’ and ‘Press P to play again’ text.

woof_step10

Step 11

Next, we can add the countdown timer functionality. We can use the every function to specify that every 1 second during the game we want the time variable to go down by 1 (the time variable will start at 20 at the beginning of the game and go down by 1 until it reaches 0 and the game ends). Every second the timer will also be updated on screen.

We can add the code if(time !== 0) so the timer won’t under 0 (into negative). !== is an a example of a comparison operator which means “is not equal to”. In other words, the game will only keep counting down if there is time left and once the time variable becomes 0 it will stop counting down. To implement the countdown timer, add the following code after the code that was just added in the previous step:

every(1, "seconds", () => {
  if (time !== 0) {
    time = time - 1;
    timerText.text = "Time remaining: " + time
  }
})

Once you have added this code you should see the timer start to count down and then stop once it reaches 0. This is what the game and code should look like so far:

woof_step11a

woof_step11b

Step 12

Now that we have a working countdown timer we can go ahead and add the ability to score points and make the enemy respawn in random locations on the screen.

Every time the player touches the enemy, the score variable will increase by 1 and the score text will be updated on screen. The enemy will then be moved to a random x and y position on the screen. minX is the minimum x position on screen (left edge of screen) and maxX is the maximum x position on screen (right edge of screen). minY is the minimum y position on screen (bottom edge of screen) and maxY is the maximum y position on screen (top edge of screen).

The enemy will respawn in random positions between those points. Note that in the code below we have the line enemy.y = random(minY, maxY – 30) which will place the enemy at a random y position on screen but 30 spaces below the top of the screen. This ensures that the enemy doesn’t respawn behind the score or time remaining text.

Add the following code inside the forever loop just below the code we added to make the player move using the arrow keys:

if (player.touching(enemy)) {
    score = score + 1;
    scoreText.text = "Score: " + score;
    enemy.x = random(minX, maxX)
    enemy.y = random(minY, maxY - 30)
  }

After adding this code as shown below, you will be able to collect points every time you catch the enemy. You can also improve this code by making sure the enemy doesn’t respawn too close to the edge of the screen where it might be partially hidden. You could also randomly respawn the player for extra challenge.

woof_step12

Step 13

Once the time has reached 0 we won’t want the player to keep moving around and collecting more points (they will have to start a new game). So we can say that if(time === 0) (which means “if time is equal to 0”), set the player and enemy sprites to be hidden and show the ‘Game over’ text and ‘Press P to play again’ text on screen. Add the following code after the code you added in the previous step (inside the forever loop).

if(time===0){
    player.hide()
    enemy.hide()
    gameOverText.show()
    playAgainText.show()
  }

woof_step13

Step 14

Lastly, we can check if the P key has been pressed on the keyboard and if so, set the score back to 0 and timer back to 20, show the player and enemy sprites on screen, reset the timer and score text on screen, and hide the ‘Game over’ and ‘Press P to play again’ text on screen. Add the following code inside the forever loop just below the code added in the previous step:

if (keysDown.includes('P')) {
    score = 0
    time = 20
    player.show()
    enemy.show()
    scoreText.text = "Score: 0";
    timerText.text = "Time remaining: 20";
    gameOverText.hide()
    playAgainText.hide()
  }

woof_step14

And that’s it! You have just completed building your first game in WoofJS using JavaScript code. Make sure you click on Save to keep your work.

woof_step14b

Questions

1. What do the following key terms mean? Can you give an example for each?

  • Syntax
  • Variable
  • Conditional statement
  • Loop
  • Function
  • URL

2. What is the JavaScript programming language used for. Provide three examples of apps or games you can find that were built using the JavaScript language.

3. Two main types of errors you might encounter when coding are logic errors and syntax errors. Explain the difference between these two different types of errors.

Tips

  • If you receive error messages or your code isn’t working, make sure you have closed brackets and quotes where necessary (or don’t have too many brackets or quotes), and make sure the brackets and quotes are matching
  • Save frequently so you don’t lose your hard work if the Internet drops out or your computer crashes
  • Look at all the different blocks for different pieces of code you can use – experiment with code and work out different ways of solving problems – it’s the best way to learn coding!

What next?

You could try adding a feature to your game that allows it to save high scores. You could also add hazards to avoid, make the player respawn in random locations, or make the monster move around. Also, try improving the appearance of text on screen by changing font family/style.

Complete code

Here is the complete code for the game:

setBackdropURL('http://www.codemahal.com/sprites/grass_background.png');
var playerImage = 'http://www.codemahal.com/sprites/hero.png';
var player = new Image({
  url: playerImage,
  width: 32,
  height: 32,
  x: 0,
  y: 0
})

var enemyImage = 'http://www.codemahal.com/sprites/enemy.png';
var enemy = new Image({
  url: enemyImage,
  width: 32,
  height: 32,
  x: 60,
  y: 0
})

var scoreText = new Text({
  text: () => "Score: 0",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: minX + 20,
  y: maxY - 20
})

var timerText = new Text({
  text: () => "Time remaining: 20",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: maxX - 160,
  y: maxY - 20
})

var gameOverText = new Text({
  text: () => "GAME OVER!",
  size: 40,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 60
})

var playAgainText = new Text({
  text: () => "Press P to play again",
  size: 20,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 0
})

var score = 0;
var time = 20;
gameOverText.hide()
playAgainText.hide()

every(1, "seconds", () => {
  if (time !== 0) {
    time = time - 1;
    timerText.text = "Time remaining: " + time
  }
})

forever(() => {
  if (keysDown.includes('LEFT')) {
    player.x -= 5
  }

  if (keysDown.includes('RIGHT')) {
    player.x += 5
  }

  if (keysDown.includes('UP')) {
    player.y += 5
  }

  if (keysDown.includes('DOWN')) {
    player.y -= 5
  } 
  
    if (player.touching(enemy)) {
    score = score + 1;
    scoreText.text = "Score: " + score;
    enemy.x = random(minX, maxX)
    enemy.y = random(minY, maxY - 30)
  }
  
    if(time===0){
    player.hide()
    enemy.hide()
    gameOverText.show()
    playAgainText.show()
  }
  
    if (keysDown.includes('P')) {
    score = 0
    time = 20
    player.show()
    enemy.show()
    scoreText.text = "Score: 0";
    timerText.text = "Time remaining: 20";
    gameOverText.hide()
    playAgainText.hide()
  }
  
})

Methods in C#

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Method names should follow a consistent naming convention throughout your code eg. using camel case or mixed case. Examples of suitable method names include CalculateScore, AddNumbers, MultiplyNumbers, GetUserDetails, etc.

Watch the video below and then scroll down for examples and sample code.

Creating methods

Lets break up the method into its different components and look at each component…

What is an access modifier?

Access modifiers include public and private (or just left empty). Public means other parts of the program can see and use this method. If we don’t want that we use private instead or no access modifier (leave it out).

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that many functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a calculator that is used to add two numbers together. There are two parameters in this method (separated by commas). The parameters in this method are num1 and num2. These are the two numbers that will be added together (they are of the float data type). Notice that the return type is also float meaning that the result of this method (the sum of num1 and num2) will be returned as a float value.

public static float AddNumbers(float num1, float num2)
 {
   float total = num1 + num2;
   return total;
 }

The method above will add two numbers together (the two parameters num1 and num2) and then return the answer as a float back to the part of the program that called the method.

The word static means that this particular method is associated with the class, not a specific instance (object) of that class. What this means is that you are able to call a static method without actually creating an object of the class.

Many methods have the word void in their declaration. The word void basically means that the method will not return any value to the part of the program that called it.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named AddNumbers, you would write:

AddNumbers();

If the method contained a parameter or multiple parameters (eg. the values 5 and 10), then they would be included inside the brackets like this:

AddNumbers(5,10);

The below example shows how to call a method and pass variables into the method. You do not need to write int inside the brackets where the function is called.

int number1 = 10;
int number2 = 30
AddNumbers(number1,number2);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method AddNumbers() in the example code above returns a value, then it should be stored in a variable or used in a statement, for example:

int result = AddNumbers(5,10);

Sample code

Here is an example using parameters and a return type of void. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      AddNumbers(5, 10);
    }
    public static void AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      Console.WriteLine("The sum of the two numbers is " + total);
    }
  }
}

Here is an example using parameters and a return type of int. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers(5, 10);
      Console.WriteLine(answer);
    }
    public static int AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      return total;
    }
  }
}

Here is an example using no parameters. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers();
      Console.WriteLine(answer);
    }
    public static int AddNumbers()
    {
      int total = 5 + 10;
      return total;
    }
  }
}

Foreach loops in C#

This tutorial explains how to use the foreach loop to go through each element in an array. A foreach loop is simpler and easier to use than a for loop if you want to loop through each and every element in an array. There is no need to use a counter, specify an increment, or a condition. The foreach loop will simply loop through every element in the array.

Foreach loops are written in a way that is easy to understand, for example:

foreach (string item in itemsList){
   Console.WriteLine(item);
}

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};

      // Store length of names array in variable
      int arrayLength = names.Length;

      // Go through each name in names array and display on new line
      foreach (string name in names) {
        Console.WriteLine(name);
      }
      // Wait for user input before quitting program
      Console.ReadLine();
    }
  }
}

Next tutorial: Methods

Arrays in C#

Arrays are basically a list of items of the same type that are grouped together in a single container. Unlike variables which can only contain one value at a time, arrays can contain many different values of the same type (eg. string, or integer). This tutorial explains how to create arrays, access elements in an array, and use for loops to work through the elements in arrays.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};
      // Create an array of int type
      int[] ages = {26,18,49,33};
      // Display second item in names array (array indexing starts at 0)
      Console.WriteLine(names[1]);
      // Display fourth item in ages array
      Console.WriteLine(ages[3]);
      // Store the names array's length (number of elements in array) in variable
      int arrayLength = names.Length;
      // Display names array's length
      Console.WriteLine(arrayLength);
      // Go through each element in names array and check if Sam exists in array
      for (int i = 0; i < arrayLength; i++) {
        if (names[i] == "Sam") {
          Console.WriteLine("Sam is here!");
        }
      }
    }
  }
}

Next tutorial: Foreach loops in C#

Do while loops in C#

A do while loop is a type of loop which repeats code while a certain condition evaluates to true. However, unlike a while loop which tests the condition first, a do while loop tests the condition after running instructions inside the loop. This means that the code inside the loop will always run at least once even if the condition evaluates to false. This is an example of post-test repetition.

Watch the video below and then scroll down to see the sample code.

Sample code

Take a look at the sample code below. The counter is set to 99 and the condition being tested is counter < 10. However, the code inside the loop runs the first time even though the condition evaluates to false because a do while loop runs the code inside the loop before testing the condition (meaning that the instructions inside the loop will always run at least once).

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 99;
      do
      {
        Console.WriteLine("Counter is: " + counter);
        counter++;
      } while(counter < 10);
      Console.ReadLine();
    }
  }

}

Next tutorial: Arrays in C#

For loops in C#

In this tutorial you will learn how to use the for loop to repeat sections of code in the C# language. For loops are useful for when you want to repeat code a certain number of times. They are also very useful for efficiently working through all the elements in an array or going through each character in a string. For loops have a built in counter, condition, and increment. Watch the video below and then scroll down for the sample code.

Sample code

Example 1 – using for loop as simple simple counted loop

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      for (int i = 0; i < 10; i++)
      {
        Console.WriteLine("Counter is: " + i);
      }
      Console.ReadLine();
    }
  }

}

Example 2 – using for loop to go through each character in string

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      string word = "dog";
      for (int i = 0; i < word.Length; i++)
      {
        if (word[i] == 'a')
        {
          Console.WriteLine("This word contains the letter a");
        }
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: Do while loops in C#

While loops in C#

This tutorial explains how to write a while loop in the C# language. A while loop is used to repeat a section of code while a condition evaluates to true. For example, keep asking for a password while the password being entered is wrong, or keep displaying a message a number is less than a certain number, or keep moving a character in a game to the right side of the screen while the right arrow key is being pressed on the keyboard.

A while loop is a pre-test loop meaning it tests a condition before running code inside the loop. If the condition being tested never evaluates to true then the loop will not run. After each iteration of a loop, if the condition being tested evaluates to false then the loop will exit and the rest of the program will run. It is important that you allow loops to eventually end by specifying a condition that will eventually evaluate to false, otherwise you will end up having an ‘infinite loop’ causing your program to crash.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 0;
      while (counter < 10)
      {
        Console.WriteLine("The counter is " + counter);
        counter--;
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: For loops in C#

Switch statements in C#

This tutorial explains how to write switch statements in C# language. Switch statements are used to select one from many different blocks of code. A switch statement can take a variable and check if its value matches one of many different specified values. Once the switch statement finds a matching case, it will run the code inside that case and the stop testing all the other cases.

Watch the video below and then scroll down to the sample code to see how switch statements work.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int myNumber = 5;
      switch (myNumber) {
        case 1:
          Console.WriteLine("The number is 1");
          break;
        case 2:
          Console.WriteLine("The number is 2");
          break;
        case 3:
          Console.WriteLine("The number is 3");
          break;
        default:
          Console.WriteLine("I don't know this number");
          break;
      }
    }
  }
}

Next tutorial: While loops in C#

Making comparisons in C# (if, else if, and else statements)

In this tutorial you will learn how to make comparisons in C# using the following conditional statements:

  • if
  • else if
  • else

We can check, for example, if a number is less than, greater than, less than or equal to, greater than or equal to, equal to, or not equal to another number. We can also check if a string variable is equal to another string value (for example, checking if a password is correct). To make comparisons, we will need to be familiar with comparison operators.

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Watch the video below which shows how to make comparisons using if, else if, and else statements (scroll down for the sample code).

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int x = 11;

      if (x > 10)
      {
        Console.WriteLine("x is greater than 10");
      }
      else if (x < 10)
      {
        Console.WriteLine("x is less than 10");
      }
      else{
        Console.WriteLine("x is equal to 10");
      }
    }
  }
}

Logical operators

We can also check if multiple conditions evaluate to true or if at least one of multiple conditions evaluate to true in a single if statement using logical operators. Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s first name is “Joe” AND their last name is also “Bloggs”.

if (firstName == "Joe" && lastName == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Watch the video below to see how you can use logical operators in conditional statements and then scroll down for the sample code.

Sample code using logical OR operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Smith";

      if (firstName == "Joe" || lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Sample code using logical AND operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Bloggs";

      if (firstName == "Joe" && lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Next tutorial: Switch statements in C#

Converting variable types in C#

This tutorial explains how to convert variable types in the C# language (eg. convert from string to integer or float, or convert from integer or float to string). Here is a summary of the methods used:

  • float.Parse() – converts to float type
  • int.Parse() – converts to int type
  • .ToString() – converts to string type

Watch the video below and then scroll down to see the sample code.

Example of converting from string to float:

float myFloatVariable = float.Parse(myStringVariable);

Example of converting from string to int:

int myIntVariable = int.Parse(myStringVariable);

Example of converting from int or float to string:

string myStringVariable = myFloatVariable.ToString();

Here is the full sample code from the tutorial video:

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Console.WriteLine("Enter your name: ");
      string username = Console.ReadLine(); // store user input as string
      Console.WriteLine("Hello there, " + username);

      Console.WriteLine("Enter two numbers");
      float num1 = float.Parse(Console.ReadLine()); // convert user input from string to float
      float num2 = float.Parse(Console.ReadLine()); // convert user input from string to float
      Console.WriteLine("The result is: " + (num1 + num2)); // display string of text and float result 

      int num3 = 5;
      int num4 = 10;
      Console.WriteLine(num3.ToString() + num4.ToString()); // convert int to string
    }
  }
}


Next tutorial: Making comparisons in C#

Combining types in output statements in C#

This tutorial shows you how you can combine types in a Console.WriteLine() output statement. For example, you can combine a string with an integer or float value. Watch the video below and scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f; // Assign value to num1 variable
      float num2 = 4f; // Assign value to num2 variable

      float result = num1 + num2 + 10f; // Add numbers

      result = num1 - num2; // Subtract
      result = num1 * num2; // Multiply
      result = num1 / num2; // Divide
      result = num1 % num2; // Mod

      int num3 = 30;
      num3--;

      Console.WriteLine(message + result); // String and float value combined in output statement
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Converting variable types in C#

Using comments in C#

Comments are useful for explaining the purpose of a piece of code or how it works. Comments can also be used to identify the author of code or when it was created or last updated.

In C# the // characters (two forward slashes) are used to add comments to your code. Any text on a line after the two forward slashes will not be treated as code. Comments are useful as they contain notes about what is happening in the code and can help others understand the algorithm. They won’t change the way a program runs and won’t be visible in the working program.

Here is an example of a comment:

// This is a comment

Watch the video below to see how to use comments and scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f; // Assign value to num1 variable
      float num2 = 4f; // Assign value to num2 variable

      float result = num1 + num2 + 10f; // Add numbers

      result = num1 - num2; // Subtract
      result = num1 * num2; // Multiply
      result = num1 / num2; // Divide
      result = num1 % num2; // Mod

      int num3 = 30;
      num3--;

      Console.WriteLine(result);
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Combining types in output statements

Arithmetic and assignment operators in C#

Operators

Operators are symbols that are used to perform operations on data. The range of different operations you can perform can usually be placed in these four categories:

  • Arithmetic operators
  • Assignment operators
  • Equality operators
  • Logical operators

In this tutorial we will look at arithmetic and assignment operators used in the C# language. Later on in these tutorials we will also look at equality and logical operators when we work with conditional statements.

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used on number variables eg. int and float (although they can be used for other things too eg. the  + operator can be used to join two strings together).

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5; (or int x = 5; if the variable’s type has not already been declared).

The table below shows the different assignment operators available in C#.

Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Watch the video below to see how arithmetic and assignment operators are used in the C# language and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f;
      float num2 = 4f;

      float result = num1 + num2 + 10f;

      result = num1 - num2;
      result = num1 * num2;
      result = num1 / num2;
      result = num1 % num2;

      int num3 = 30;
      num3--;

      Console.WriteLine(result);
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Comments