Tag Archives: guide

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
})

Introduction to programming in Java

Welcome to the Java programming tutorial series. In this tutorial, I will show you how to download the Java SDK and Netbeans IDE so you can begin coding in Java. You will also learn how to write your very first program in Java – a ‘Hello world’ program.

Watch the video below and then scroll down for the links to the Java SDK and Netbeans IDE downloads and to view the sample code for the example shown in the video.

Downloads

All downloads are available for Windows, Mac and Linux

Sample code

Here is the sample Java code for this tutorial. Keep in mind that the project name in the video example was HelloWorld and so the package in the sample code is also called helloworld.

package helloworld;
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
    
}

Adding a Details screen to the List app for iOS with Xamarin

In this tutorial, we will look at how to extend the iOS List app we made in the previous tutorial by adding a Details screen that will display more details about item the user has selected from the list.

This is what the app will look like…

detailsscreen

Note: The title bar of the app will normally display and should be presented when the app is tested on an actual iOS device, but a bug in the iOS Simulator used here prevents the title bar from showing.

Step 1

Drag a Navigation Controller from the Toolbox on to your storyboard.

image3

Right-click and Delete the Root View Controller that is not required (you may have to delete twice).

image4

Step 2

Hold down the Control (Ctrl) key while clicking and dragging from the Navigation Controller to the Table View screen. Then select Root.

image5

Step 3

Drag a View Controller from the Toolbox on to your storyboard next to the main screen.

image6

Step 4

Add an ImageView element and a Label element to your screen. The default Text value for the label can be set to City Name. You also need to give both elements a name. Set the Name value for the Image View to cityImageView and the Name value for the label to cityNameLabel.

image7
When you give the ImageView or Label element a name you will see a yellow warning icon in the Name field. Click this icon and then type in DetailsViewContoller and press the Enter key to generate a new class and codebehind for this screen.

image8

Step 5

Now Control-click (Crl + click) and drag from the row on the main screen to the new details screen and select Show. This means that when the user selects a city from the list, they will be taken to the city details screen.

image9

You can also double-click on the main screen’s title to change it.

image10

Step 6

Click on the arrow between the main screen and details screen. On the Properties panel, set the Identifier value to DetailsSegue. Remember its name because it will be used in the code.

image11

 

Step 7

Open the CitiesViewController.cs file and scroll down to the City class. We need to add a new property called ImagePath which will contain the image for each city in the class.

image12

 

Step 8

Right-click the project folder and select Add > New Folder. Name this folder Images.

image13

Now right-click the Images folder and click Add > Add Files from Folder.

image14

Browse for the folder containing your images and then click Open.

image15

Select the desired images and then click OK.

image16

Select Copy the file to the directory and Use the same action for all selected files. Then click OK.

image17

Step 9

Go back to the CitiesViewController.cs file and for each city in the cityList, add the lines highlighted below to specify the ImagePath for each city’s image. Remember to add a comma to the end of the line before the ImagePath line (see the commas at the end of lines 22 and 31).

image18

Step 10

Go to the DetailsViewController.cs file and add the public City selectedCity; line to the DetailsViewController : UIViewController class. Save the file.

image19

 Step 11

Now you need to add a PrepareForSegue override method. You can add this method after the GetCell method. Start typing public override PrepareForSegue and then select the PrepAreForSegue method from the list by double-clicking it or pressing Enter to autocomplete.

image20

Step 12

Add the following code to the new PrepareForSegue method. This will check if the segue is the DetailsSegue (in other words, if the user tapped one of the rows from the table on the main screen that takes them to the details screen). Then it will get the relevant data from the selected row to be displayed on the details screen.

image21

Step 13

Back in the DetailsViewController.cs file, add a public override ViewWillAppear method. To do this, start typing public override ViewWillAppear and then select that method from the list.

image22

Step 14

Inside the new ViewWillAppear method (which runs as soon as the second screen loads), add the following highlighted lines of code (replacing any existing default code inside the method). This will set the label text to display the name of the selected city and will also set the ImageView to display the image representing the selected city.

image23

All done! Make sure you save your files and then you can test your app!

You can extend this app by adding more properties to each City item so that the Details page can display more information about a city such as points of interest, activities, and even its location on a map.

In the next tutorial we will look at how to add thumbnail image previews to each row in the list.

Passing data between screens on Android with Xamarin

In this tutorial you will learn how to create an Android app that can pass data from one screen to another. This will be demonstrated in an example app that will ask the user for their age and will then convert their age to into animal years (of different types of animals). The user will select an animal by tapping a button and then the result will be displayed on another screen. The app will look like this…

pda_app

Step 1

Open Xamarin Studio. Click File > New Solution. Select Android App (C#) as the template.

pda1

Step 2

Give your app a name, for example AnimalAgeCalculator. Click Next.

pda2

Step 3

Confirm the project and solution name as well as the project folder location and click Create.

pda3

Step 3

Navigate to the Resources > layout folder and click the cog icon (or right-click the folder). Then Click Add > New File. We will be adding the second screen to the app.

pda4

Step 4

Select Android > Layout, give the new screen a name (eg. Result.axml) and then click New.

pda5

Step 5

Open the Main.axml folder in the Resources > layout folder. Add a Text (Large) element and change the Text value to say ‘Enter your age in years’.

pda6

Step 6

Now add a Plain Text element and change its Id to @+id/ageEditText .

pda7

Step 7

Now add a Text (Medium) element which says ‘Convert to…’. Underneath this, add some Button elements such as those shown below. Change their Text values and Id’s. The buttons below have the following Id’s in order:

@+id/dogButton

@+id/catButton

@+id/goatButton

@+id/hamsterButton

pda8

Save the file.

Step 8

Now open the Results.axml file and add a Text (Large) element – replace its Text value with ‘Result’. Then add a Text (Medium) element, change its Id value to @+id/resultTextView and give it a default Text value (it doesn’t matter what you put here as the result text will change).

pda8b

Step 9

Add some spacing and then a Button element. Rename the Id of this button @+id/backButton and change the Text value to ‘Go back’. Save the file.

pda9

Step 10 

Now click on the project folder (not the solution folder) and click the cog icon (or right-click) > Add > New File.

pda10

Select Activity from the Android list, name it ResultActivity and then click New.

pda11

Step 11

Open the MainActivity.cs file and delete the two sections of highlighted code shown below inside the MainActivity class. This code will not be required in this app.

pda12
Click image to view larger version.

Step 12

In the MainActivity class, define the EditText and Button elements, and create two float variables (age and animalAge) and a string variable (animal) as highlighted on lines 11-18 below. In the OnCreate method, add the following highlighted code (shown in lines 27-31).

pda13
Click image to view larger version.

Step 13 

In the OnCreate method, after adding the EditText and Button elements to the code, start typing dogButton.Click+= to create a button click event and then press the Spacebar key. You will see a list of options – double-click the DogButton_Click option to create a new method of the same name.

pda14
Click image to view larger version.

The new method called DogButton_Click will be created as shown below.

pda14b
Click image to view larger version.

Step 14

Repeat the last step for each button click event. You should now have click events and matching methods for the dog, cat, goat, and hamster buttons. This is where we will start adding code to convert the human years to animal years and take the user to another screen.

pda14c

Add the following code to the methods show below.

pda14d

Step 15

Make sure you have the line of code using Android.Content; at the top section of the MainActivity.cs file’s code.

pda15

Step 16

In the HamsterButton_Click method, change the animal variable’s value to “Hamster” and then create a new intent which will send the values of the animalAge and animal variables to the ResultActivity screen.

pda16

Step 17

The last step will need to be repeated for each button click method as shown below. Just change the value for the animal variable in each method to the appropriate animal as shown below. Save the file.

pda17

Step 18

Open the ResultActivity.cs file and make sure your code is the same as shown in the highlighted areas in the image below. You will need to define the resultTextView and backButton elements as well as get the animalAge and animal values from the Intent created in the MainActivity.cs file. The resultTextView element will display the result of the age conversion (the selected animal name and result in animal years). Save the file.

pda18
Click image to view larger version.

Now just add a click event and method for the backButton element which will take the user back to the main screen when they click on the button which says ‘Go back’.

pda18b
Click image to view larger version.

Step 19

The last step before testing is to go back to the Main.axml file and change the Input Type for the ageEditText element to number. Save the file and test your app.

pda19

Click the Build icon to test your app using an Android simulator.
pda19b

Improving the app

One last thing we can do is prevent any errors from occurring or the app from crashing if the user does not enter a value to convert before tapping a button. We can check if the text field has been left empty and only run the conversion and open the result screen if a value exists in the text input field. Here is an example of this in the HamsterButton_Click method.

pda20

You could repeat this step for all of the button click methods. Now go and test your app again – it should no longer crash if the user does not enter a value in the text field!

While loops in C#

While loops are used to repeat a section of code while a specified condition evaluates to true. For example, a user could keep being asked to enter a password while the password they are providing is incorrect. When the password they provide is correct, the loop will end.

The video below explains how to use while loops in C#. You can also scroll down to see the sample code.

Sample code

The sample C# code for a solution and project called MyApp is shown below. In this program, a variable called myNumber is created which is initially given an integer value of 1.

A while loop is created which checks if the value of myNumber is less than 10. While the value of myNumber is less than 10, the value is displayed to the user and then increased by 1, each time the loop repeats. Each repetition of a loop is called an iteration. Try the code below in your own program.

using System;

namespace MyApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Hello World!");
      int myNumber = 1;
      while(myNumber < 10)
      {
        Console.WriteLine(x);
        myNumber++;
      }
      Console.ReadLine ();
    }
  }
}

Next tutorial: For loops

What is Xamarin?

Welcome to the tutorial series on building mobile apps for Android and iOS with Xamarin and the C# programming language. In this tutorial series you will learn how to use the Xamarin platform to design and develop mobile apps for both major smartphone operating systems – Android and iOS.

Xamarin logo

With Xamarin, you can build native apps without having to know Swift, Objective-C, and Java. Most of the code you write in C# with Xamarin can be used for both Android and iOS, making it much easier to write native apps for both platforms. Xamarin allows you to write native apps for different platforms with native UI, native API access, and native performance using a shared C# codebase, the same IDE, language, and APIs anywhere.

In this tutorial series, we will start by installing and getting to know the Xamarin platform and basics of the C# language, and then we will learn how to make a basic Android and iOS app. The great thing about learning C# is that you will also be able to use that language to develop amazing 2D and 3D games for several platforms in Unity 3D by following the tutorials here.

The next tutorial will show you how to download and install Xamarin for Windows and Mac OS.

Note: CodeMahal is not endorsed by or associated with Xamarin in any way. CodeMahal provides free tutorials on using the Xamarin platform.

Entities and materials in PlayCanvas

In this tutorial you will learn more about entities and how to modify a Box entity to make a ground or floor for your game’s scenes. You will also learn how to use materials to give 3D objects some colour and apply detailed patterns and textures using assets.

A repeating grass pattern image like the one shown in this tutorial can be downloaded from here.

Tip: You can do a Google Images search for textures and patterns using keywords such as “brick pattern tiled”, “repeat brick pattern” or “brick pattern seamless”.

Getting started with PlayCanvas

PlayCanvas is a 3D game development environment in the cloud. You can use PlayCanvas to make your own 3D games and code them in the JavaScript programming language using a web browser like Chrome or Firefox.

In this tutorial you will learn about the PlayCanvas features and tools and how to create, move, rotate, and resize 3D shapes. Watch the video below to get started with PlayCanvas.

Getting started with PHP

In this tutorial, you will learn how to setup a PHP development environment on your computer using XAMPP. You will learn how to install and set up XAMPP and test it out so that you are ready for PHP development!

We will be starting out with PHP and working with MySQL a little later on after covering the basics of PHP. These tutorials will be presented on Mac using XAMPP but you are welcome to use Windows or Linux and the steps should be the same or fairly similar for whichever OS you use. You can also try out another PHP development environment but XAMPP is a good choice for all platforms. Click here to download XAMPP.

You can also use a web-based programming environment like Cloud9 to code in PHP.

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

Sample PHP code:

<?php
 echo "Hello world";
?>

Should I use the closing ?> tag?

If you are a beginner PHP programmer, it is recommended that you omit the closing ?> PHP tag at the end of your code if the file is pure PHP code. This will prevent any unwanted effects that may occur if you add whitespace after the closing tag.

If you do use the closing ?> then it is important that you do not add any other white space (spaces or new lines) after the tag. You can read the reasons why at the official PHP documentation site.

PHP Manual references:

Getting started with Unity

Welcome to the Unity 3D Game Development tutorial series! Unity is a game engine for building 2D and 3D games that can be played on a range of different platforms including Mac, Windows, iOS, Android, and more.

Unity allows you to create game objects and environments and then program your games using the C# (C Sharp) and JavaScript programming languages (you can also code in Boo but it is no longer documented by Unity 5). You can choose which language you would like to use but in these tutorials we will work with C#.

To get started with Unity, watch the video below. Make sure you also check out the Unity FAQ & Tips page to get the most out of Unity. Make sure you also get used to using Unity keyboard shortcuts so that you can work faster in Unity.

You can download the Unity game engine for Mac or Windows here. The Personal Edition is free to use and that is what will be used in these tutorials. When you install Unity, make sure you also include any standard assets, demo projects and files, and MonoDevelop in the installation.

Laser cutting with Adobe Illustrator

This tutorial explains how to set up your documents in Illustrator to use with a laser cutter so that you can mark, engrave and cut your own designs on a range of materials such as timber and plastic.

Watch the video below or scroll down to download the PDF instructions.

You can also download printable instructions here.

Download the PDF file

 

Getting started with Adobe Illustrator

This video tutorial introduces the basic tools and features of Adobe Illustrator to help you get started with your own designs, including:

  • Fill and stroke colours
  • Line tool
  • Pen and Brush tools
  • Shape tools
  • Zoom and Hand tools
  • Selection tools
  • Anchor points and curved lines
  • Eraser

Watch the video below or on YouTube.

You can download the PDF instructions here.

Getting started with HTML5 and CSS3

HTML (HyperText Markup Language) is the markup language that is used to create web pages. It is written using HTML elements, also known as tags. These tags are enclosed in angle brackets. Tags often come in pairs such as <p> and </p> but this is not always the case as some tags are unpaired, for example <br/>.

Web browsers such as Google Chrome, Internet Explorer, Safari or Firefox are able to read HTML files and display them as web pages on your screen. The tags tell the web browser what to display in the browser and how to display it. HTML files end in the .html file extension and can be edited in any text editing program.

HTML is the basic building block of all web pages but most websites today don’t just use standalone HTML. Web pages can be supported by CSS (Cascading Style Sheets) which define the look and layout of text and other elements on multiple pages, and other scripts written in languages such as JavaScript which can control how a web page behaves.

This tutorial is the first in the HTML5 and CSS3 video tutorial series. These videos will show you everything you need to begin creating your own website.

To begin writing the code for your own webpages you will need to download and install a good text editor for coding. The good news is that there are plenty of free text editors that can do this well. Here is a list of good text editors you can use to write your code:

I often choose to use Sublime Text or Atom on Mac (and you’ll see this in screenshots throughout this tutorial series) but you can choose any program you like – they are all fairly similar to use.

All of the main code editors are very easy to use. Basically you open a new file, save it as a file which ends in .html and then type in your code. You can usually see all your folders and files listed in the side as well.

Here is a screenshot of the Atom code editor. showing a list of folders on the left and the code on the right. You can work on multiple files in different tabs and also see the line numbers for your code next to each line of code.

atomdemo

Once you have dowloaded your HTML text editor, install and run it. Create a new file and save it as index.html – make sure that the file type is set to HTML (HyperText Markup Language). Your homepage should always be saved as index.html – by using the name index it will be recognised as the homepage in. You can name your other pages whatever you like eg. about.html or contactus.html – but it is good practice to not use spaces in your filenames.

Watch the video below to see how to build your very first web page and then scroll down to see the code and find out what is happening on each line of code.

Take a look at the sample HTML code below and then scroll down to find out what each line of code does.

<!DOCTYPE html>
<html>
<head>
 <title>My first web page</title>
 <meta charset="utf-8"/>
</head>

<body>
<p>This is my first web page.</p>
</body>

</html>

The first line tells the browser that the file or document type is HTML. The second line is the opening <html> tag for the HTML document which is paired with the closing </html> tag on the last line. The <html> tag indicates that your HTML code begins here. All of your code goes between the <html> and </html> tags.

<head> is the first section of the HTML document which contains background information about your webpage. This includes the character set that will be used (UTF-8, which represents every character in the Unicode set) and things such as the title of the web page which is usually displayed at the top of the browser window or as a label on your browser tab.

The webpage title shown in the browser tab.
The webpage title shown in the browser tab.

Note that the <head> tag is paired with the </head> tag. Whatever goes inside the <head> section is not actually displayed on your web page. It just includes background information about your webpage.

The next tag you will see is the <body> tag. Everything between the <body> and </body> tags is content that will be shown on your webpage. This includes text, images, tables, and other content.

The first HTML element (tag) we will use in the body section is the <p> tag which will make a paragraph of text. The content of your paragraph goes between the <p> and </p> tags. Create a new file and try it out!

Copy and paste the code from above in your new file, then click on File and Save As to save your text file as a HTML file. Choose a name for your file and end it in the .html file extension. If this is going to be your homepage, then name it index.html – also, if the option is available then make sure you choose “Hypertext Markup Language (.html)” next to “Save as Type”.

Saving your webpage
Saving your webpage

Save the file and open it with your web browser (eg. Chrome). Your page should look like this:

Your first webpage
Your first webpage

Making an LED Sensor Night Light with Arduino

This video tutorial explains how to use an Arduino Uno to make an LED night light. The project involves an Arduino Uno board, an LED, a light sensor which can detect different levels of light and return a value, a breadboard with jumper wires and resistor.

Basically the way the project works is as follows. Use the light sensor to get light readings constantly. You can specify a value which, when the light is less than this value an LED light will be turned on, and when the light is greater than this value the LED light will be turned off.

This project allows you to work with getting readings from a sensor (input), use if statements to test conditions, and use an LED to produce some form of output.

Watch the video below or click here to view it on YouTube.

Downloads:

The source code is also available here:

int lightLevel;
int led = 13;
void setup()
{
 pinMode(led, OUTPUT);
 Serial.begin(38400); // Go to Tools > Serial Monitor and change to 38400 bauds to see light value readings
}
 
// this loop will turn the light on when light reading is below value of 10
// there is a delay of 1 second between checking the light value
void loop()
{
 lightLevel = analogRead(A0);
 Serial.println(lightLevel, DEC); // this shows the light level reading in Arduino IDE (go to Tools > Serial Monitor)
 
 if (lightLevel < 50) // change this value to suit light conditions. Ranges from 0 (very dark) to 1023 (very bright).
 {
 digitalWrite(led, HIGH); // turns the light on
 } 
 else
 {
 digitalWrite(led, LOW); // turns the light off
 }
 delay(1000);
}

Photos

1

2 3 4

Light sensor readings
Light sensor readings