tutorials Archives - CodeWizardsHQ The leading online coding academy for kids and teens ages 8-18 Thu, 28 Nov 2024 06:42:04 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 https://www.codewizardshq.com/wp-content/uploads/2019/10/cropped-cropped-blueHorizontal-32x32.png tutorials Archives - CodeWizardsHQ 32 32 How to Make a Maze in Scratch in 7 steps https://www.codewizardshq.com/how-to-make-a-maze-in-scratch-in-7-steps/ Mon, 18 Nov 2024 02:35:31 +0000 https://www.codewizardshq.com/?p=66538 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

A maze is a simple puzzle where you try to find your way from the beginning to the end. Completing a maze tests your memory, problem-solving skills, and patience. Coding does the same! Both require having to think logically and in order.   In this tutorial, I’ll show you an easy and fun way to code […]

The post How to Make a Maze in Scratch in 7 steps appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

A maze is a simple puzzle where you try to find your way from the beginning to the end. Completing a maze tests your memory, problem-solving skills, and patience. Coding does the same! Both require having to think logically and in order.  

In this tutorial, I’ll show you an easy and fun way to code a maze in Scratch where you control the player with your arrow keys. As a bonus, I’ll also teach you how to animate your character and add a timer. 

You can learn to build a maze and other fun Scratch games with a live instructor in our top-rated coding classes. My elementary school students really enjoy how engaging and easy Scratch coding is. They just have to drag and drop to create cool games and programs. By coding a maze, we’ll learn about loops, collision detection, and events. 

Complete this tutorial to code a maze Scratch!

Completed maze game

Play and remix the complete maze game now. 

In this game, the baby penguin, Pesto, has lost his hat. Mom is going to be mad! Help him find his winter hat to win.

We can break down this game into 3 main components: 

1. The maze: A drawing of a maze obstacle players have to avoid and make their way through.

  • Draw the maze

2. The player: the player, the penguin, moves around the maze and returns to the beginning when they touch the edge.

  • Add and position the player
  • Move the player around the maze
  • Detect player collision with the maze

3. The goal: the goal, the winter hat, is placed at the end of the maze and the player wins when they reach the goal.

  • Add and position the goal
  • Detect player collision with the goal

What you need:

Scratch account: Create a free Scratch account

No coding experience is necessary for this Scratch tutorial. Beginner-friendly for kids ages 8 and up. Give it a try!

Steps to Make a Maze Game in Scratch

Let’s turn each of the parts we discussed previously into steps:

  1. Create a new Scratch project
  2. Add a backdrop
  3. Draw the maze
  4. Add and position the player 
  5. Move the player around the maze
  6. Detect player collision with the maze
  7. Add and position the goal
  8. Detect player collision with the goal

Step 1: Create a New Scratch project

First, we need to set up a new project in Scratch where we will edit our code. 

  • Visit scratch.mit.edu
  • Login to your Scratch account
  • Click on the Create button
Create a new Scratch project
  • A new project will open, rename your project to Penguin Maze Game
  • Hover over the cat sprite and click the trash can to delete it
Name Scratch project Penguin maze game

Now we have a fresh new project to code our maze game!

Hint: You can also remix the Penguin Maze project to see the completed code.

Step 2: Add a Backdrop

Set the stage for your game by adding a background image.

  • Click the Choose a Backdrop button
Choose a backdrop button
  • Select the Arctic backdrop
select the arctic backdrop in scratch

You should now see the backdrop in your preview area. 

see the backdrop in Scratch preview

Hint: Get creative and select a backdrop that matches your theme. You can also select Surprise to let Scratch choose for you. 

Step 3: Draw the maze

A maze is simple to draw with just horizontal and vertical lines. We’ll draw our own maze, make sure you leave enough room for your player to get through. 

  • Hover over the choose a sprite button, select Paint
select paint button
  • Click on the line icon
  • Select an outline color and change the size of your lines to 20
  • Click and drag lines to represent the maze. Adjust it to fit the game preview.
outline maze sprite
  • Click the Code tab and rename the sprite to Maze.
rename the maze sprite

Do you see your maze in the preview screen like this? Great!

see the maze in the preview

Hint: You can make the maze as easy or hard as you want. Add more lines and dead ends to make the maze harder. 

Step 4: Add and position the player

We want to add our player, the penguin. The penguin is going to start at the top left every time the game starts. Before we move the penguin, position it at the top with our code.

  • Click the Choose a Sprite button in the right corner
choose a sprite button
  • Select the Penguin 2 sprite from the library
select the penguin sprite
  • Change the size to fit your maze, my penguin is 20.
change the penguin sprite size

Next, add this code to the penguin so that it goes to the starting position every time the game starts. 

  • Add a When green flag clicked block from events category.
  • Add Go to x y position block from motion category. Use the x and y value of your sprite at the starting position.
go to x y
see the penguin move

Now, try moving your player away from the starting position. When you click the green flag, it should return there. If your test works, you’re ready for the next step. 

Hint: You can get creative and draw your own sprite, just hover over the add a sprite button and go up to Paint.

Step 5: Move the player around the maze

The penguin is on the screen, but he can’t move. The penguin needs to move up, down, right, and left when we press the arrow keys. We need to control him with the arrow keys.

Let’s add the logic to the arrow keys. To move the sprite right and left, add this code: 

  • In the Events category, add When right arrow key pressed block
  • Add a Change x by block from the motion category and change the value to 10
  • Right click on When key pressed block and Duplicate the entire code block
  • Then change the dropdown to When left arrow key pressed and change x by to -10
when right or left arrow key pressed blocks

To move the sprite up and down, add this code: 

  • In the Events category, add When right arrow key pressed block
  • Add a Change y by block from the motion category and change the value to 10
  • Right click on When key pressed block and Duplicate the entire code block
  • Then change the dropdown to When left arrow key pressed and change x by to -10
when up or down arrow key pressed blocks
complete code for penguin movement

Your penguin can move now! Try pressing the arrow keys and make sure the penguin is moving in the right direction.

Hint: To move the player faster or slower, change the x and y values. 

Step 6: Detect player collision with the maze

We need to code what happens when the player touches the maze. The penguin should say ‘Oh no!’ and go back to the starting position.

  • On the player sprite, add a Forever block.
  • Inside the Forever block, add an If then block
  • From the sensing category, add the Touching block inside the if then block. Change the dropdown to the Maze sprite.
  • From the looks category, add a say block and update the message to “Oh no!”
  • Finally, add a go to block and use the same x y position as the starting position 
detect a collision with if then block
detect a collision final code

Now, you can try touching the maze with your player sprite. Does it return to the starting position?

It’s working, let’s keep going! 

Hint: You can customize the message your sprites says or change what happens after the sprites touch. 

Step 7: Add and position the goal

Our player is in place and can move around the maze. Now, let’s place the goal at the end of the maze. 

  • Click the Choose a Sprite button in the right corner
  • Select a sprite from the library. I’m using one from the Scratch library called Winter Hat.
choose the winter hat sprite
  • Change the size to fit your maze. Mine is size 40.
change your maze to size 40
  • Add a “when green flag clicked” block
  • In the preview, position the hat at the end of the maze. Then add a Go to x y position block using those coordinates. Mine is positioned at x = 195 and y = -135.
position the hat
position the hat code

Once you’re done, click the green flag to test your game. Your hat should go to the end of the maze when the green flag is clicked.

Hint: You can customize the goal sprite to fit your theme by drawing or uploading a sprite.

Step 8: Detect player collision with the goal

To win the game, the player needs to reach the goal. When the player teaches the goal, they say “I found it!” and the game ends.

  • On the player sprite, inside the forever block, add an if then loop
  • From the sensing category, add the Touching block inside the if then loop. Change the dropdown to “Winter Hat”
  • Add say block and update the message to “I found it!”
  • From the control category, add a stop all block to end the game
detect a collision with the goal
penguin code for collision detection

Hint: You don’t have the complete the maze to test your game. Just drag your character sprite to the end in your game preview.

Your maze game is complete! Play the maze game.

Click the green flag and give it a try. If you want to share it with other people and let them remix it, click the “Share” button at the top. 

completed maze game gif

You can “see inside” the completed maze game to view the full Scratch code. 

Challenge yourself by adding the bonus features to your maze. 

Bonus: Animate the player 

We can animate the penguin by making it look left and right when it moves. To do this, we’ll create a costume for each look.

1. Create the costumes

  • Click on the costumes tab, you will see different poses for the penguin on the left
costumes tab in scratch
  • Rename the first costume, penguin2-a to look front 
  • Rename the last costume, penguin2-d to look right
choose the look front penguin costume
  • To create a penguin looking left, right click and duplicate the look right costume
duplication the look right costume
  • Highlight the new costume in the paint canvas and click flip horizontal. You should now have a penguin looking left.
  • Rename this new sprite to look left
flip the costume horizontal

The final costumes will look like this:

rename the costume look left

Your penguin now has different costumes to show which direction he’s facing.

2. Change the costume with arrow keys

Go back to the Code tab to add code to the penguin sprite. Under each key press, we will switch the costume to match the direction the penguin is facing.

  • Under the when right key pressed, add a switch costume to look right
  • Under the when left key pressed, add a switch costume to look left
  • Under the when up key pressed, add a switch costume to look front
  • Under the when down key pressed, add a switch costume to look front
switch costumes block added to arro key blocks

Try pressing the arrow keys and see if your penguin is facing the right direction.

3. Set the costume when the game starts

But, when we press the green flag the penguin isn’t always facing forward.

  • Under the when green flag clicked block, add a switch costume to look front
switch costume to look front
completed code to switch costumes

Start the game over by pressing the green flag. Your penguin should start looking forward, then look right or left depending on which direction it’s moving. 

Now your penguin is animated to look like it’s walking.

Bonus: Add a timer 

We can add a timer to make the maze more challenging. Let’s give the player 60 seconds to complete the maze game before the penguin disappears.

1. Create a Time variable

A variable is used to hold information that changes. Our time decreases every one second, so we can use a variable to save that value.

  • Go to variable category, right-click my variable and rename it to Time
  • Check off the box next to the Time variable

You should see the Time variable in your game preview now.

2. Start the Timer 

If we want the player to have 60 seconds to play, we should set the timer to start at 60. 

  • Add a When green flag clicked block
  • From the variable category, drag a set Time to 60
set time to 60

Press the green flag to see the time reset.

3. Count down the timer

Use a loop to count down the timer every 1 second. 

  • Add a Repeat until loop under the set Time block
  • In the operators category, add a less than block in the repeat until loop. Repeat until Time < 1.
  • Add a wait 1 second block inside the loop
  • Then decrease the time variable using change Time by -1
loop to count down the timer
showing timer in game preview

Press the green flag to see the time counting down.

4. Show and hide the penguin

The penguin should show when the game starts, but hide after the time runs out. 

  • After the When green flag clicked block, add a show block
  • After the Repeat until loop, add a hide block
add show and hide blocks
show and hide penguin

That’s it! Press the green flag to test your timer one more time. It should be counting down the time and hiding the penguin once the time runs out.

Give yourself a pat on the back. You completed the maze game tutorial. See the complete game with bonuses and remix it

More Scratch Tutorials for Kids

Try making another Scratch game using a fun step-by-step tutorial:

Download Free Printable Scratch Coding Tutorials PDF

Get the Rocketship Landing game and Flying Space Cat Scratch tutorials in a printable format.

Code more games in Scratch!

Continue coding games in Scratch with the guidance of a live, expert instructor. We teach kids how to code and practice analytical thinking, computational thinking, problem-solving, and logical reasoning.

Kids, ages 8-10, who want to learn more about Scratch coding can join the Elementary School Core Track. We offer a structured Scratch curriculum with project-based learning for hands-on practice. Enroll today to get started.

Learn to make games in Scratch in our top-rated coding classes for kids.

The post How to Make a Maze in Scratch in 7 steps appeared first on CodeWizardsHQ.

]]>
How to Make a Jumping Game on Scratch https://www.codewizardshq.com/how-to-make-a-jumping-game-on-scratch/ Wed, 28 Feb 2024 07:45:23 +0000 https://www.codewizardshq.com/?p=60835 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Hey there, young explorers! Ready to learn how to make a jumping game on Scratch? We’re building a Rocket Jump game where you’ll zoom through space going from platform to platform. Before we start building our game, let’s talk about Scratch. Scratch is a super cool place where you can make your own stories, games, […]

The post How to Make a Jumping Game on Scratch appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Hey there, young explorers! Ready to learn how to make a jumping game on Scratch? We’re building a Rocket Jump game where you’ll zoom through space going from platform to platform. Before we start building our game, let’s talk about Scratch. Scratch is a super cool place where you can make your own stories, games, and animations — like a digital LEGO set that’s all about your ideas!

📌 [Download] Printable Scratch Coding Tutorials Get 2 printable Scratch tutorials, Rocket Landing and Flying Space Cat, to code your own games step by step. Download Now

It’s like learning to speak the language of computers! And the best part? You don’t have to type any words or numbers. Instead, you snap together colorful blocks that look a bit like puzzle pieces. Each block is a command that tells your characters and objects what to do.

In our elementary school curriculum, students start their coding journey with Scratch. As kids build games and animations with Scratch, they’re laying the groundwork for computational thinking—a vital skill set for coding with actual code. 

Let’s start our coding journey together!

Complete this tutorial to create a jumping game on Scratch.

Play and remix the Rocket Jump game now.

What you need:

No coding experience is necessary for the Rocket Jump tutorial. Beginner-friendly for kids ages 8 and up. Give it a try!

Steps to make a jumping game in Scratch:

  • Step 1: Setup the scratch project
  • Step 2: Make the rocket move with keyboard keys
  • Step 3: Add “gravity” to make the rocket fall.
  • Step 4: Add the platform
  • Step 5: Make the rocket jump when touching the platform.
  • Step 6: Change platform position everytime rocket touches it.
  • Step 7: Add scores in the game.
  • Bonus 1: Change costumes of the Rocketship sprite
  • Bonus 2: Increase difficulty as the game progresses

In this game, players guide a rocketship through the starry cosmos using the arrow keys to navigate left and right. The rocket automatically falls due to gravity, but upon touching the platform, it jumps upwards to earn points. Each successful landing on the platform boosts the rocket higher and changes the platform’s position, making each jump a new challenge. The aim is to keep the rocket aloft as long as possible while racking up jumps for a high score.

Step 1: Setup the Scratch project

Create a New Scratch Project

  • Open Scratch, and you’ll see a button that says “Create”. Click it, and you’re on your way!
  • At the top, you’ll find the name “Untitled”. Click on it and type in “Rocket Jump” to name your game.


Set the Stage

  • Every game needs a background. Look at the bottom-right corner for a little picture that looks like mountains. That’s the backdrop. Click it!
  • Choose a backdrop with stars to make it look like outer space. You can pick one or even draw your own.
choose a game background
  • Next, click on the picture of the cat to select a sprite. You can pick a rocket from the ones they have. 
choose a scratch sprite
  • Set its size as per your need. For rocket sprite, a size of 40 works the best.
resize the rocket in the jumping game

After we have both backdrop and sprite setup, you should have something like below in the game preview area:

Step 1 results, rocketship sprite with background

Step 2: Make the rocket move with keyboard keys

Moving Right

  • Let’s get our rocket moving. Click on the Events category, and you’ll find a block that says “when space key pressed”. Drag it out.
  • We want to move right when we press the right arrow, so click on the little dropdown arrow on that block and choose the “right arrow”.
  • Now, click on the Motion category (it’s the blue one), and find “change x by 10”. Drag that and snap it right under the “when the right arrow key pressed”.
move the rock et right and left

Moving Left

  • Our rocket should move left too! Let’s duplicate the blocks you just made. Right-click on them and choose “duplicate”.
Duplicate blocks to move
  • Change “right arrow” to “left arrow” and “10” to “-10”. Now, when you press the left arrow, your rocket will move left!
Add arrow key to move

Step 3: Add “gravity” to make the rocket fall.

Setting the Fall

  • In space, things float down slowly. We’ll make our rocket do that. Find the Events category again and use the “when green flag clicked” block.
  • We need to tell the rocket where to start. Go to Motion, find “go to x: y:” and fill in “x: -144” and “y: 123”.
  • To make it keep falling, go to Control (the orange category), find “forever,” and drag it under your “go to” block.
  • Inside “forever,” go back to Motion and find “change y by”. Put “-4” in it to make our rocket fall.
Add gravity to make the rocket fall

Step 4: Add the Platform

Creating the Platform

  • Our rocket needs a platform to jump from. Click the paintbrush to make a new sprite.
  • The click the square icon and draw a rectangle at the center of the screen. This is your platform. It can be any color you like!
Create a platform for your jumping game

Positioning the Platform

  • Let’s put the platform in place. Under Events, use “when green flag clicked” again.
  • In Motion, find “go to x: y:” and fill in “x: -154” and “y: -55”. That’s where the platform will wait for our rocket.
position the platform for the rocket to jump on

Step 5: Make the rocket jump when touching the platform.

The rocket jumps!

  • We want our rocket to bounce when it touches the platform. Inside the rocket’s “forever” loop, add the “if then else” block from the Control category. 
  • From the Sensing category (it’s the light blue one), grab “touching” and select the “Sprite1” (your platform sprite) from the dropdown.
  • In the “else” part, move the “change y by -4” block you made before.
  • For the “if” part, first, we make the rocket jump. Grab “repeat” from Control and type “15” in it.
  • Inside “repeat,” add “change y by 4” from “Motion” and “wait 0.05 seconds” from Control after it. This makes the rocket go up for a bit, like it’s bouncing!
make the rocket jump when touching platform
make the rocket jump when touching platform

Step 6: Change the platform position every time the rocket touches it.

Moving the Platform

In the rocketship sprite

  • We’ll make the platform move every time the rocket jumps. In the rocket’s code, in the “if” part, find Events and use “broadcast message1”.
change the platform position in scratch

In the platform sprite

  • Wait for that broadcast message. Use “when I receive message1” from Events
  • To change the spot, use “glide 1 secs to x: y:” from Motion.
    • Set the value of y with y position block from the Motion category. This will make sure the platform remains at the same height.
    • For x, add a random block from Operators category, and set the lower limit to -200 and upper limit to 200
broadcast message to glide

This completes our game logic, we can now move our rocket to go left and right, and use the platform to stay afloat.

rocketship jumping, game logic complete

Step 7: Add scores in the game.

Keeping track of scores

A game is no fun without the scores. To set up scores, create a new variable named Scores.

  • Click on the Variables category and choose “Make a Variable”
  • Name it Scores, press ok, and you should see it appear in your variables list. Make sure it’s checked off so it shows in your game.
make a scores variable

In your rocketship sprite, 

  • Drag the set the value of Scores variable and position it below the “When flag clicked”. Set its value to 0.
  • Inside the if condition, in the “forever” block, add the change value by 1 block. And select the Scores variable from the dropdown.
set the score in the jumping game

Your game is complete!

Bonus 1: Change costumes of the Rocketship sprite 

Change costume when jumping

To add the rotate effect in the rocket, we can change its costume when it goes up.

In the Rocketship sprite

  • Drag the “next costume” block from the looks category, and place it inside the repeat 15 block, in the if condition.
  • To reset the costume, drag the “switch costume to” block from the Looks category, and place it below the “when green flag clicked” block.
  • Select the default costume value. For the rocketship sprite, the costume rocketship-e makes perfect sense, as it doesn’t have any ignition.
change costumes
completed jumping game in scratch

Bonus 2: Increase difficulty as the game progresses

Draw more costumes in platform sprite

To increase the difficulty of the game, add costumes to the platform sprite with a smaller size of platform.

  • Select the platform sprite, and go to the Costumes tab.
  • Right click on the Costume, and select duplicate.
  • Decrease the size of the platform in the duplicated sprite.

In the Code tab of the platform sprite,

  • Add the “if then” block from the Control category and place it below “when I receive message1” block.
  • For the condition of the “if” block, use the > block from the Operators category.
  • Inside > block, add scores variable on left side, and any value of scores when you want to change platform on right side. For example, we can use 15.
  • Inside the “if” block, add the “Switch Costume” block from the Looks category, and select the costume with decreased size.
  • Add another switch costume block and place it below the “when green flag clicked” block. 

Let’s play!

It’s time to test your game by pressing the green flag above your game’s screen. 

Compete with your friends and see who can score the most scores.

Download Free Printable Scratch Coding Tutorials PDF

Get the Rocketship Landing game and Flying Space Cat Scratch tutorials in a printable format.

Make More Games in Scratch

CodeWizardsHQ firmly believes that initiating the exploration of technology and programming during childhood can pave the way for future success. We have designed a structured program for elementary school coding, that leverages the power of Scratch to teach coding principles.

In the first course, Animation and Games with Scratch, students delve into essential programming concepts, including variables, loops, and conditionals. By the end of this course, they will possess the ability to create their own games and animations using Scratch. This prepares them for their journey toward a future in the ever-evolving world of technology.

Our coding classes for kids allow children to nurture their skills, unleash their imaginations, and experience the joy of learning!

The post How to Make a Jumping Game on Scratch appeared first on CodeWizardsHQ.

]]>
How to Make a Platformer on Scratch https://www.codewizardshq.com/how-to-make-a-platformer-on-scratch/ Mon, 25 Sep 2023 02:23:30 +0000 https://www.codewizardshq.com/?p=57710 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

In this tutorial, I’m going to show you how to make a platformer game in Scratch. Scratch is a simple drag-and-drop coding language for children to learn basic programming skills. Kids can build all kinds of games and apps in Scratch. With the Scratch classes I’ve taught, kids always enjoy the exceptional interactivity and enjoyment […]

The post How to Make a Platformer on Scratch appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

In this tutorial, I’m going to show you how to make a platformer game in Scratch. Scratch is a simple drag-and-drop coding language for children to learn basic programming skills. Kids can build all kinds of games and apps in Scratch.

With the Scratch classes I’ve taught, kids always enjoy the exceptional interactivity and enjoyment Scratch offers. In our Elementary School Core Track, students can craft their own interactive games while learning fundamental programming concepts like variables, loops, and more.

📌 [Download] Printable Scratch Coding Tutorials Get 2 printable Scratch tutorials, Rocket Landing and Flying Space Cat, to code your own games step by step. Download Now

Try this tutorial to learn about accepting user input, adding player controls, checking for collisions between two sprites, and more. Let’s get started!

Play and remix the Chick’s Adventure game now.


What you need:

  1. Scratch account: Create a free Scratch account

No coding experience is necessary for this Scratch tutorial. Beginner-friendly for kids ages 8 and up. Give it a try!

How to Make a Platformer on Scratch

  1. Set up the Project
  2. Set the Scene
  3. Add Gravity to the sprite
  4. Add platforms for the sprite to jump on
  5. Add the user controls
  6. Change the levels
  7. Bonus: Make a way to win or lose

Step 1: Set up the Project

In this section, you will create a new Scratch project, give it a name, and save it so you can get started on your platformer game!

1. Login to Scratch

2. Create a New Scratch Project

  • Once you are logged in, click the Create button at the top of the page.

3. Name the project and delete the Scratch cat

  • In the top textbox on the Scratch editor, name your project whatever you would like!
  • Then, delete the Scratch cat by clicking the trash can next to the sprite in the spite area.

4. Save the project

  • Click File, then Save now. You’re now ready to make your platformer game!

Step 2: Set the Scene

For this section, you will add the backdrop and a sprite for the player to control, which will set the scene for your platformer game! 

1. Add a backdrop to your game!

  • Click on the Add a backdrop button on the bottom right-hand side of your editor.

  • Choose whatever backdrop you’d like! I chose Blue Sky 2 for my project. When you’re ready, click your chosen backdrop.

Great, now your backdrop should show up!

2. Select a Player Sprite

  • On the bottom right-hand side of your page, click on the Choose a Backdrop button.
  • Click any sprite you would like. In this tutorial, I decided to select the Chick sprite.
  • You can change the size of the sprite if you’d like as well. Edit the Size textbox in the sprite area to do this!

Awesome job, you should now have a sprite on your screen that is sized how you want. Click and drag the sprite around to move it to a new spot!

Step 3: Add Gravity to the Sprite

In this section, you will learn how to use multiple motion blocks to change the player’s position and move them downwards on a loop, which will simulate gravity.

1. Detect when the game is being played

  • In the Code block tab, click on the Events category.
  • Then, select the When Green Flag clicked block and drag it into your code area.

2. Make the sprite move downwards on a loop

  • Go to the Control category and drag a forever block into the code area and attach it under the When green flag clicked block.


  • Then, go to the Motion category and click and drag a change y by block. In the textbox, you can change the number if you’d like. The higher the number, the faster they fall.


  • Change the number in the change y by textbox to a negative number to make it go downwards.


3. Set the sprite’s initial position

  • In the Motion category, click and drag a go to x and y block and connect it under the when green flag clicked block, but above the forever block.

  • Press the Green Flag above the game area. Does your sprite fall? Every time you press the Green Flag, your sprite should start from the beginning and fall down!

Step 4: Add platforms for the sprite to jump on

In this section, you will add platforms for the player to jump on to avoid falling. Once the player touches a platform, you will make it so gravity turns off until they aren’t touching the platform anymore!

1. Add a platform for the sprite

  • In the bottom-right corner of the Scratch editor, click Choose a Sprite.

  • Choose whatever sprite you want in the menu. For this tutorial, I chose the Clouds sprite.

  • Move the new sprite to a position under the player’s sprite and press the Green Flag button. Does it work as intended?

2. Make it so the sprite can’t go through the platform

  • Click on the Chick sprite. Make sure that it is selected before moving on to the next step.

  • Then, in the Code tab, go to the Control category and click and drag an if then block to under the change y by block.

  • Go to the Sensing category and drag a touching block into the code area. Click the block and change the dropdown selection to the sprite you recently added to the game. In my case, I selected the Clouds sprite.

  • In the Motion category, drag a change y by block to be in the if then block. Make sure that the number in the change y by block is the positive version of the one outside of the if then block. If you had a -10 in the first change y by block, you should have a 10 in the new one.

  • Press the Green Flag button. Does your player sprite stop when it touches the platform?

Recommended: How to Make a Game on Scratch

Step 5: Add the user controls

In this section, you will allow the player to move their sprite back and forth in the game, which will make it so they can eventually switch levels. You will also make it so the player can jump from platform to platform!

1. Allow the player to move left or right

  • In the Control category, drag two if then blocks to inside the forever block.


  • Then, go to the Sensing category and drag two key pressed blocks into the if then blocks you added. Change one of them to left arrow and the other to right arrow in their dropdowns.


  • Go to the Motion category and drag two move steps blocks into the left and right arrow key pressed blocks. Keep them both the same number.


  • Next, in the Motion category, drag a point in direction block into both the key pressed blocks. Then, change the number in the left arrow key pressed block to -90. The right arrow one should be 90.


  • In the Motion category again, drag a set rotation style block to under the Green Flag clicked block.



Great work so far! Does your sprite move back and forth with the left and right arrow keys?

2. Make the player jump

  • Go to the Events category and drag a when key pressed block into the code area. Change the dropdown in that block to up arrow or spacebar.


  • Then, in the Control category, drag a repeat block under the when key pressed block.

  • Get a change y by block from the Control category and place it in the repeat block. Change the number in the change y by block to be about 15, or a number bigger than the gravity number.

  • To add a delay between jumps, go to the Control category and drag a wait block under the repeat block.

  • Press the Green Flag button, does the sprite jump when you press the up or spacebar key?

Step 6: Change the levels

In this section, you will create a checkpoint that the player must touch to switch to the next level. You will be able to use your creativity to develop multiple levels using this method.

1. Add a checkpoint

  • Choose another sprite to serve as a checkpoint the player has to get to in order to get to the next level. For my project, I chose a Sun sprite. Feel free to change the size of the sprite as well.


2. Change levels when the checkpoint is touched

  • Go to your Code tab and select My Blocks. Then, click the Make a Block button.


  • There will be a popup. In that window, change the name in the textbox to Next Level. Then, click the Ok button.


  • You will notice a define block in your code area now. This is called a function, and basically is a small segment of code that performs an action. We will use it to change levels!



  • Then, attach a go to x and y block to the define block. Make sure the x and y values are similar to the ones you originally created in the when green flag clicked block.


  • Next, in the Events category, click and drag a broadcast block in to the define block as well. In the text portion, change it to something like Next Level.


  • Click on the checkpoint image in the sprites list area on the right of the page to make sure you’re changing the correct sprite. Then, in the Events category, move a when I receive block to the code area. It should say When I receive Next Level.


  • Then, from the Looks category, drag a next costume block under the when I receive block.


  • Then, click on the Costumes tab for your platform. You can click the Zoom out button – shaped like a magnifying glass with a minus on it, which is situated in the bottom right corner of the picture editor. This allows you to edit more of the image all at once.


  • Create another platform for the player to jump on by clicking and dragging to select the whole drawing. Then, click the Copy and the Paste buttons, and drag the new one to a better position.


  • You should now have two platforms to jump on!


  • Next, get an if then block from the Control category and drag it under the if right arrow pressed block.


  • Then, find a touching block from the Sensing category and put it in that newly added if then block.



  • Go back to the My Blocks category and click and drag the Next Level block into that if then block.



  • Click on the Platform sprite again. From the Events category, add a when green flag clicked. Then, go to the Looks category and put a switch costume to block to reset the platforms whenever the game is started.



Nice job! Do the platforms switch? From here, you can adjust each costume to make new levels.



Bonus Step: Make a way to win or lose

In this bonus section, you will make a way for the player to win by reaching a certain level, or lose by falling from the platforms! You will also create win and lose game screens for when this happens.

1. Create the win and lose backdrops

  • First, click on the Backdrops section on the bottom right of the editor in the Stage menu.


  • Once you do that, click on the Backdrops tab. Then, right-click on the backdrop you’re using in this project. Click duplicate to make an exact copy.


  • When you’re in the new backdrop, click on the Text button in the menu. Edit the text to say something like You Win!


  • Next, right-click and duplicate that new backdrop with the text as well.


  • Click the text and edit it to say something like You lose. Now you should have both the win and lose backdrops in your game!


2. Make the player lose if they fall off the platform

  • First, click on the player’s sprite. Then, go to the Looks category and get a switch backdrop to block and drag it under the when green flag clicked block. Make sure to set the backdrop to the first backdrop – not the win or lose ones. This is so that it resets whenever the player starts the game again.


  • Then, select Paint a new sprite.


  • In the Costumes tab of the new sprite, make a rectangle that is positioned at the bottom of the game screen. We’ll make it so that when the player touches this, they lose.


  • Then, go to the Code tab again and drag an if then block in the main forever block loop.


  • Next, go to the Sensing category and get a touching block and move it into the condition of the if then block you just added. Change the dropdown selection to the new sprite you created.


  • Now, go to the Looks category, get a switch backdrop to block, and change the dropdown selection to the lose backdrop.


  • Finally, go to the Control category and get a stop all block. Place it under the switch backdrop to block.


Does the lose screen display when the player falls off a platform?



3. Make the player win if they beat the last level

  • Select the platform sprite. Then, go to the Control category and place an if then block under the next costume block.


  • Then, go to the Operators category and grab a contains block. Put that in the if then block.


  • Go to the Looks category and put a costume number block in the left textbox of the contains block.


  • Finally, go to the Looks category and get a switch backdrop to block and put it in the if then block. Make sure it goes to the You Win backdrop.


Test your game, can you win?

Check Out Our Other Scratch Tutorials

Keep coding with one of these fun Scratch tutorials!

  • How to Make a Flappy Bird Game – Make an interactive game where the player must make a bird flap its wings to avoid incoming obstacles!
  • Flying Space Cat – Assist Space Cat in its space exploration mission by developing an enjoyable crystal-collecting game using the Scratch programming platform.
  • Code a Rocket Landing Game – Finish this Scratch programming tutorial designed for children and create a game where you safely land a rocket.
  • Valentines Day Card Scratcher – Create a Valentine’s Day scratch-off card with a personal touch by following this easy-to-follow Scratch programming tutorial.
  • Holidays Advent Calendar – Use Scratch to program a customized Advent Calendar for the holiday season and gradually unveil presents, treats, or activities to share with your friends adn family.
  • Halloween Candy Collector Game – Follow this simple Scratch programming tutorial and create a personalized game where you collect candies on Halloween.

Download Free Printable Scratch Coding Tutorials PDF

Get the Rocketship Landing game and Flying Space Cat Scratch tutorials in a printable format.

Try a Scratch Coding Class for Kids

At CodeWizardsHQ, we believe that learning about technology and programming during a student’s formative years can pave the way for future success. Our specialized program tailored for elementary school children utilizes Scratch as a foundational tool for imparting coding skills.

In our inaugural course, Animation and Games with Scratch, young learners delve into crucial programming concepts such as variables, loops, and conditionals. Upon completing this course, they will possess the proficiency to craft their own games and animations through Scratch, thus equipping them for more advanced coding endeavors and a promising future in the realm of technology. Our program fosters the development of children’s skills and imagination, all while ensuring an enjoyable and educational experience.

The post How to Make a Platformer on Scratch appeared first on CodeWizardsHQ.

]]>
How to Make Flappy Bird on Scratch https://www.codewizardshq.com/how-to-make-flappy-bird-on-scratch/ Fri, 28 Apr 2023 19:04:44 +0000 https://www.codewizardshq.com/?p=55986 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Scratch is a great tool for kids to learn how to code and it’s completely free! Anyone can use Scratch to make fun games, stories, and animations by dragging and dropping different blocks of code. It’s really easy to use and perfect for beginners who want to be creative and solve problems with coding. In […]

The post How to Make Flappy Bird on Scratch appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Scratch is a great tool for kids to learn how to code and it’s completely free! Anyone can use Scratch to make fun games, stories, and animations by dragging and dropping different blocks of code. It’s really easy to use and perfect for beginners who want to be creative and solve problems with coding. In this article, I’ll show how to make a flappy bird game on Scratch without any text-based code.

📌 [Download] Printable Scratch Coding Tutorials Get 2 printable Scratch tutorials, Rocket Landing and Flying Space Cat, to code your own games step by step. Download Now

In the Flappy Bird game, the player guides a bird through the sky avoiding a series of obstacles. When the bird collides with an obstacle, the game is over. This type of project has proven to be highly interactive and fun in the Scratch classes I’ve taught here at CodeWizardsHQ. In the Elementary School Core Track, students learn how to build their own interactive games while mastering important programming concepts such as variables, loops, and more.

It’s amazing to see how much kids enjoy this type of project and how much they learn along the way.

Complete this Scratch tutorial for kids to build a Flappy Bird game.

completed flappy bird scratch game

Play and remix the Flappy Bird game now. Avoid the obstacles to increase your score.

What you need:

  1. Scratch account: Create a free Scratch account

No coding experience is necessary for this Scratch tutorial. Beginner-friendly for kids ages 8 and up. Give it a try!

Video Tutorial: How to Make Flappy Bird in Scratch

How to Make Flappy Bird on Scratch

  1. Login to Scratch
  2. Create a New Project
  3. Name Your New Project
  4. Choose a Backdrop
  5. Choose a Sprite
  6. Resize and position the sprite
  7. Add the first code block
  8. Set the sprite’s starting position
  9. Add gravity to the game
  10. Make gravity slower
  11. Make the bird fly up
  12. Design the Game’s Obstacle
  13. Animate the Obstacle
  14. Randomly Position the Obstacle
  15. End the Game Upon Collision
  16. Test your game!

1. Login to Scratch

Login to scratch to build flappy bird

2. Create a New Project

  • Once you are logged in, click the blue Create button at the top of the page.
create a new scratch project

3. Name Your New Project

  • Give your project a name, for example, “Flappy Bird Game”. 
  • Then delete the Scratch cat by clicking the trash can icon next to the sprite.
How to Make Flappy Bird on Scratch Name your project

4. Choose a Backdrop

  • Select the Choose a Backdrop option at the bottom right-hand side of your screen.
choose a backdrop
  • When the Choose a Backdrop screen opens up, select a background for your Flappy Bird game. In this tutorial, I chose “Jungle”, but you can choose whatever you’d like!
Choose a backdrop

5. Choose a Sprite

  • Then, go to the Choose a Sprite option, which is next to the “Choose a Backdrop” section.
Choose a sprite
  • Select a bird sprite of your choosing. We selected the Parrot sprite, which is suggested if you want to create a flapping motion for the character.
select parrot sprite

6. Resize and position the sprite

  • Resize your sprite by changing the Size textbox, we changed it to 50 in this tutorial. 
  • Then, click and drag the sprite shown to the left of the game, since the pipes will be moving from the right to the left.
How to Make Flappy Bird on Scratch resize and position scratch sprite

7. Add the first code block

  • Go to the Events category, then click and drag a when green flag clicked events block into your code area.
Add when green flag clicked

8. Set the sprite’s starting position

  • Go to the Motion category and drag a go to x and y block under your when green flag clicked block. This will make sure the player begins at the same place every time the game is loaded.
How to Make Flappy Bird on Scratch Set sprite position

9. Add gravity to the game

  • Then, in the Control block category, drag a forever block and attach it under the go to x and y block.
Add gravity to game
  • Go back up to the Motion category and get a change by y motion block, then drag it directly into the forever block. 
  • Change the value in the textbox of the change by y block to -15. Now when you press the green flag icon above your game, the bird will drop really fast!
Add change position block

10. Make gravity slower

  • To fix the bird from falling so quickly, put a wait block from the Control category before the change y by block. 
  • Change the value in the textbox to about 0.1.
Slow down gravity

11. Make the bird fly up

  • Now let’s make it so the player can interact with the game! Grab a when space key pressed block from the Events category and drag it into the code area.
How to Make Flappy Bird on Scratch When space key pressed block
  • Go to the Motion category and get a change y by block and put it below the when space key pressed block. Now the player can make the bird fly up! NOTE: Check out the bonus after this tutorial which will show you how to make the bird’s wings flap as they fly.
Motion block

12. Design the Game’s Obstacle

  • Click on the paint option from the New Sprite button to create a pipe sprite.
scratch game obstacle
  • Select a color of your choice from the Fill option, then select the square from the list of tools.
Draw obstacles
  • Click and drag the square to create two pillars or tubes that will be obstacles for the game. Reposition and resize the pipes as needed.
draw obstacles

13. Animate the Obstacle

  • Click on the Code tab and drag a when green flag clicked block from the Events category into the code area. Attach a forever block from the Control category.
How to Make Flappy Bird on Scratch animate scratch obstacle
  • Next, go the the Motion category and drag a set y to block, set x to block, and a glide to x and y block inside the forever block. 
  • In the set x to block, change the textbox to say 275. This makes it so the pipes will start on the right side of the screen!
animate scratch motion block
  • Update the glide block to glide for 2 seconds and change the x value to -275, so that it moves to the left of the screen. 
  • Then, in the Motion category, drag a y position block inside of the y value in the glide block.
glide block

14. Randomly Position the Obstacle

  • Test your project, you’ll notice that the pipes stay at the same position every time they move toward the player. 
  • To fix this, go to the Operators category and grab a pick random block and drag it into the set y to block. 
  • Change its values to something like -65 and 65.
position obstacles in scratch

15. End the Game Upon Collision

  • Nothing happens when the parrot collides with the pipe! Let’s get a when green flag clicked block from the Events category and a forever block from the Control category to set this up.
How to Make Flappy Bird on Scratch game collision in scratch
  • From the Control category, get an if then block and put it inside the forever block.
game collision in scratch
  • Then, go to the sensing category and get a touching mouse-pointer block. Drag that into the if then block. 
  • Click the mouse-pointer option to change it to Parrot instead
if then block
  • Go to the Control category and get a stop all block and put that inside the if then block. This will stop the game when the Parrot and pipes collide!
if then block

16. Test your game!

  • The game should stop when the bird collides with the pipes. Check out the completed project here.
completed flappy bird scratch game


Bonus 1 – Adds a points system

1. Create a variable

  • In your Flappy Bird Project, go to the Variables category and right-click on the variable called my variable. It’s right below the Make a Variable button.
  • Then, select the Rename Variable option.
bonus 1 step 1 flappy bird



2. Name the variable

  • In the popup window, type score for the name, then click OK.
bonus 1 step 2 flappy bird

3. Display the Score

  • Then, click the checkbox next to the score variable. This makes the score show up in your game.
bonus 1 step 3 flappy bird

4. Update the score

  • Then, in the Variables category, drag a set score to 0 block right under the when green flag clicked block. 
  • Also get a change score by 1 block and put it under the glide block.
bonus 1 step 4 flappy bird

5. Test the game!

  • Test your game, you should be able to get a score now when you play the game

Bonus 2 – Make the bird’s wings move as you play the game

1. Select the Sprite

  • First, make sure you click the Parrot sprite from the sprites list.
bonus 2 step 1 flappy bird

2. Switch the Sprite’s costume

  • Go to the Looks category and grab a switch costume block for inside the forever block and under the when space key pressed block. 
  • Make sure that you are using parrot-a in the forever block and parrot-b under the when space key pressed block.
bonus 2 step 2 flappy bird

3. Test the Game

  • Do your Parrot’s wings flap? Then, your project is complete, great job!
bonus 2 step3 flappy bird

What is Scratch coding?

Scratch is a block coding language that helps kids learn about computer science. It runs on it’s own web-based platform and is free for anyone to use. It works by taking snippets of code and grouping them into colorful blocks. The blocks can be snapped together to form longer, more complex codes. The more blocks that you use, the more complex the code becomes creating exciting games and apps. It is often used as an educational platform and we highly recommend it for kids ages 8-10 because it doesn’t require strong typing skills. This is a fun and safe coding sandbox for kids to learn fundamental coding concepts and develop their problem-solving and computational thinking. Find out more about Scratch coding for kids.

More Scratch Tutorials & Games

Now that you’ve built your Flappy Bird Game in Scratch, check out these other fun Scratch game tutorials!

  • Flying Space Cat – Assist Space Cat in its space exploration mission by developing an enjoyable crystal-collecting game using Scratch programming platform.
  • Code a Rocket Landing Game – Finish this Scratch programming tutorial designed for children and build a game where you safely land a rocket.
  • Valentines Day Card Scratcher – Create a Valentine’s Day scratch-off card with a personal touch by following this easy-to-follow Scratch programming tutorial.
  • Holidays Advent Calendar – Use Scratch to program a customized Advent Calendar for the holiday season and gradually unveil presents, treats, or activities to share with your friends and family.
  • Halloween Candy Collector Game – Follow this simple Scratch programming tutorial and create a personalized game where you collect candies on Halloween.

Download Free Printable Scratch Coding Tutorials PDF

Get the Rocketship Landing game and Flying Space Cat Scratch tutorials in a printable format.

Try a Scratch Coding Class for Kids

At CodeWizardsHQ, we believe that learning about technology and programming at a young age can help you succeed in the future. Our coding program for kids in elementary school uses Scratch to teach them how to code.

In the first course, Animation and Games with Scratch, students learn important programming concepts like variables, loops, and conditionals. By the end of the course, kids will be able to make their own Scratch games and animations. This helps them get ready for more advanced coding and a future in technology. Enroll your child in our top-rated coding classes today.

Coding games in Scratch lets kids learn a useful skill while having fun and discovering something new!

The post How to Make Flappy Bird on Scratch appeared first on CodeWizardsHQ.

]]>
Python Tutorial for Kids: Random Dad Joke App https://www.codewizardshq.com/python-tutorial-dad-joke-app/ Mon, 05 Dec 2022 14:00:00 +0000 https://www.codewizardshq.com/?p=53203 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Whether you love them or hate them, dads always have them at the ready. It’s the classic dad joke.  We’ve turned dad’s favorite jokes into a Python app, so anyone can tell a great dad joke at any time. The Random Dad Joke App picks an awesome dad joke from a database and shows it […]

The post Python Tutorial for Kids: Random Dad Joke App appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Whether you love them or hate them, dads always have them at the ready. It’s the classic dad joke. 

We’ve turned dad’s favorite jokes into a Python app, so anyone can tell a great dad joke at any time. The Random Dad Joke App picks an awesome dad joke from a database and shows it to you so you can deliver the punchline. These jokes are so bad and corny, they might actually make you laugh! 

📌 [Download] Free Python Lesson Plans Get free 1-week Python lesson plans and slides for kids ages 11-13 to start learning about Python coding. Download Now

Complete this Python coding tutorial to build your own Random Dad Joke App.

Make your friends and family laugh with a few funny dad jokes.

See the completed Random Dad Joke App.

What you need:

1. Text editor

We’ll be using the CodeWizardsHQ editor to write and run our Python code. If you’re a CodeWizardsHQ student, download the x_hour_of_code_2022 project for the completed code. 

You can also use an online text editor like replit that allows you to author and run Python programs in a web browser.

2. An empty Python file

Create a new empty Python file and add your code there. 

Our file is named main.py, and if you’re a CWHQ student you must use this name. If you’re using another platform to write and execute your code, you can choose whichever name you like.

This tutorial is for beginner Python programmers ages 11+. Let’s get started!

Step 1: Display a welcome message to the user

Display a message to the users that explains how the Random Dad Joke app works.

  • Create a variable called welcome_message that equals a multi-line string. This string contains your welcome message and instructions.
welcome_message = """
    Welcome to the 'Random Dad Joke' app!

    This app uses an API to fetch a random setup
    and punchline to a dad joke. The setup will
    be displayed to you, and if you guess the punchline,
    a message like "That's correct!" will be displayed.
    Otherwise, you'll be shown the punchline.
"""
  • Use the print() function to display this message on the page. Note, the ... symbols are just there to make the code easier to read. Don’t type that!
welcome_message = """
  ...
"""

print(welcome_message)

Hint: Change the message inside the “”” to personalize your welcome message.

Step 1 Output:

python tutorial step 1

Step 2: Display the options the app accepts

Show the user the possible options the app accepts and prompt them for their choice.

  • Create a Python string representing the options for your user: 1) get a dad joke or 2) exit
welcome_message = """
  ...
"""

options = "(1) Get Dad Joke (2) Exit: "

print(welcome_message)
  • Add a while loop that shows the user the options.
  • Convert the user’s response to an int (integer) data type so we can easily process their choice. It’s much easier to compare integers versus string values that may have spaces, different casing, etc.
print(welcome_message)

while True:
    user_choice = int(input(options))
  • Add a break statement to exit the loop after the options are displayed. This stops the options from being continuously presented.
while True:
    user_choice = int(input(options))
    break

Hint: Create more options as an additional challenge.

Step 2 Output:

python tutorial step 2

Step 3: Process the user’s choice

Next, we want the users to choose an option by entering the number 1 or 2 and we will execute their choice. 

  • Create named constants for each option: GET_JOKE if they select 1 and EXIT if they select 2

options = "(1) Get Dad Joke (2) Exit: "

GET_JOKE = 1
EXIT = 2

print(welcome_message)

while True:
    ...
  • Now we can add logic for each choice and remove the break statement from the while loop.
while True:
    user_choice = int(input(options))
    break  # Remove this!
  • Add an if...elif conditional statement to handle both user options. 
  • If the user selects 1, we’ll want to show a joke. For now, use the pass statement in the GET_JOKE condition. We’ll implement the logic for that statement at a later time. 
  • If the user selects 2, they exit the game. Make sure the EXIT option exits the loop with the break statement! 
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        pass
    elif user_choice == EXIT:
        break

Hint: Create more options as an additional challenge.

Step 3 Output:

python tutorial step 3

Step 4: Get a random dad joke from the Dad Jokes API

Now, let’s get retrieve some hilarious dad jokes! We will be connecting to a CodeWizardsHQ API that holds a database of jokes.

  • Define a function called get_random_joke(). Function definitions go at the top of your file, before any variable declarations or other statements in the main area of your program.
  • Inside the function, create three variables: BASE_URL, endpoint, and request_url using the values listed below. The BASE_URL represents the location on the internet where the API lives. The endpoint is a special URL path that the API provides to get a random joke. The request_url combines the BASE_URL and endpoint into a single str representing the full URL that we’ll request data from.
def get_random_joke():
    BASE_URL = "https://dad-joke-api.apps.codewizardshq.com"
    endpoint = "/random/jokes"

    request_url = f"{BASE_URL}{endpoint}"

welcome_message = """
    ...
"""
  • Use from to import the urlopen() function from the urllib.request module. This is a built-in Python module for making requests over a network. Import statements always come first, at the very top of your file.
from urllib.request import urlopen


def get_random_joke():
    ...
  • Use a with statement and the urlopen() function to make a request to the Dad Jokes API (at the request_url) and save the API’s response in a response variable. The with statement is a context manager, and it allows us to safely deal with opening and closing a network request. 
from urllib.request import urlopen


def get_random_joke():
    BASE_URL = "https://dad-joke-api.apps.codewizardshq.com"
    endpoint = "/random/jokes"

    request_url = f"{BASE_URL}{endpoint}"

    with urlopen(request_url) as response:
        joke = response.read()
  • After the with statement, display the contents of the joke variable with the print function.
def get_random_joke():
    ...
    with urlopen(request_url) as response:
        joke = response.read()

    print(joke)
  • Going back to the while loop, call the get_random_joke() function when the user chooses GET_JOKE.
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        get_random_joke()
    elif user_choice == EXIT:
        break

Hint: If you see a really long response when trying to get a dad joke, wait about 10 seconds and then try again. The API has to “wake up” from being asleep if it hasn’t been used recently!

Step 4 Output:

python tutorial step 4

Step 5: Correctly format the data from the Dad Jokes API

Now we have the information (the joke) from the API, we need to format it in a way users can read it.

  • At the top of your file, import the loads() function from Python’s built-in JSON module.
from urllib.request import urlopen
from json import loads


def get_random_joke():
    ...
  • In the get_random_joke() function, use the loads() function to ensure the response is converted to a dict. The dict data structure maps keys to values and will make it easy to get the setup and punchline from the API response.
def get_random_joke():
    ...

    with urlopen(request_url) as response:
        joke = loads(response.read())

    print(joke)

Hint: An API is an application programming interface which allows interactions between multiple software programs. Programmers (you!) then have access to data and info from external software (CodeWizardsHQ’s dad joke database).

Step 5 Output:

python tutorial step 5

Step 6: Return the setup and punchline from the get_random_joke() function

Now, let’s separate the setup and the punchline as we will want to present them independently later. 

  • Remove the print() statement from the get_random_joke() function. 
def get_random_joke():
    ...
    with urlopen(request_url) as response:
        joke = loads(response.read())

    print(joke) # Remove this!
  • Use the return statement to send the setup and punchline out of the function. Separating return values with a comma (,) allows you to send multiple values out of a function easily. The [] allow you to pull the values from the dict based on a key (the “setup” and “punchline” strings are the keys).
def get_random_joke():
    ...
    with urlopen(request_url) as response:
        joke = loads(response.read())

    return joke["setup"], joke["punchline"]
  • In the while loop, create the setup and punchline variables. You can use multiple assignment to store both the setup and punchline returned from get_random_joke(). Whenever a function returns multiple values, you can use this syntax to assign the values to variables in one line. You just need to make sure to have variables for every value and place them in the same order that the values are returned from the function.
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
    elif user_choice == EXIT:
        break
  • Use f-strings and the special f"{variable_name=}" syntax to ensure each variable represents the values you expect.
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
        print(f"{setup=}")
        print(f"{punchline=}")
    elif user_choice == EXIT:
        break

Hint: An f-string is a formatted string literal. It lets you include the value of a variable inside a string with the prefix “f”.

Step 6 Output:

python tutorial step 6

Step 7: Ask the user to guess the punchline and tell them if they’re right or wrong

After the user selects 2, we will prompt them to guess the punchline and also check if they guessed correctly.

  • In the while loop, remove the f-strings that displayed the setup and punchline with the f"{variable_name=}" syntax.
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()

        print(f"{setup=}")      # Remove this!
        print(f"{punchline=}")  # Remove this!

    elif user_choice == EXIT:
        break
  • Use print() to display the setup and prompt the user to guess the punchline.
  • Create a variable called user_guess that stores the user’s response.
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
        print(setup)

        user_guess = input("Guess the punchline: ")
    elif user_choice == EXIT:
        break
  • Using an if...else conditional statement, display a message like “That’s correct!” if the user guessed the punchline correctly. Otherwise, display a message like “Sorry, that wasn’t the punchline.” and then display the punchline.
while True:
    user_choice = int(input(options))

    if user_choice == GET_JOKE:
        setup, punchline = get_random_joke()
        print(setup)

        user_guess = input("Guess the punchline: ")

        if user_guess == punchline:
            print("That's correct!")
        else:
            print("Sorry, that wasn't the punchline.")
            print(f"The punchline was: {punchline}")

    elif user_choice == EXIT:
        break

Hint: Change the text inside the print() function to customize your user message.

Step 7 Output:

python tutorial step 7

Your app is complete!

Check out the finished Random Dad Joke App.

python tutorial dad jokes complete

Download the project files and open main.py to view the completed project.

Now, you’re ready with a great dad joke in every situation. 

Download 1-Week Python Lesson Plans

Kds ages 11-13 can start learning Python in a structured way. Download a FREE 1-week lesson plan with activities and slides. Enter your name and email to receive the free lesson plans in your inbox today.

If you want to build games and apps in Python, join CodeWizardsHQ’s live coding classes for kids. It’s the most fun and effective way for kids to learn Python and advance to a real-world coding internship. 

Students in our middle school and high school core track start by learning fundamental coding concepts in Python. They work with a live, expert instructor who supports them every step of the way. Classes are engaging and you’ll build personalized projects and applications in every lesson. 

No matter how you do it, we encourage you to keep practicing your Python!

The post Python Tutorial for Kids: Random Dad Joke App appeared first on CodeWizardsHQ.

]]>
Scratch Tutorial For Kids: Flying Space Cat https://www.codewizardshq.com/scratch-tutorial-for-kids-flying-space-cat/ Mon, 05 Dec 2022 14:00:00 +0000 https://www.codewizardshq.com/?p=53874 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Space Cat is on a mission to collect as many crystals as possible to fuel his spaceship! Using the Scratch platform, let’s build a fun collecting game to help Space Cat with its mission. Collecting is a popular mechanic in games and can be easily coded in Scratch with the same basic logic. From weapons […]

The post Scratch Tutorial For Kids: Flying Space Cat appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Space Cat is on a mission to collect as many crystals as possible to fuel his spaceship! Using the Scratch platform, let’s build a fun collecting game to help Space Cat with its mission.

Collecting is a popular mechanic in games and can be easily coded in Scratch with the same basic logic. From weapons to badges, collecting can keep players striving to achieve more in your game. 

In this game, the goal is to collect as many crystals as possible, but if you miss three crystals the game ends. This tutorial shows you how to code this game from start to finish and you can customize it with your own images and messages. 

📌 [Download] Printable Scratch Coding Tutorials Get 2 printable Scratch tutorials, Rocket Landing and Flying Space Cat, to code your own games step by step. Download Now

Code this game and see how many crystals you can collect!

Play Flying Space Cat game.

Scratch tutorial complete

What you need:

Scratch account: Create a free Scratch account 

Starter files: Download the star image we are using in our game. You can also use your own images to customize your application. Download starter file.

No coding experience is necessary for this tutorial. Beginner-friendly for kids ages 8 and up. Give it a try!

Step 1: Create a new Scratch project

Let’s start by creating a new project. 

Scratch tutorial create project

Now, we can code your Flying Space Cat game! 

Hint: You can also remix this project and others to see the code.

Step 2: Add a scrolling background

To give the effect of moving through space, we created a simple scrolling background.

  • Start by deleting the Scratch cat sprite that appears in every new project. Click on the cat sprite and the trash can icon.
  • Click the “Choose a Backdrop” icon and add the “Galaxy” backdrop.

The stars will move while the backdrop stays in place.

  • Click upload sprite and upload the stars.png file
  • Change the size of the Stars sprite to 50 and position it on the screen
  • Add the “When Green Flag Clicked” block from the “Events” category
  • Use a “Forever” block with the “Go to Back Layer” block to make sure the stars show behind other sprites.
  • Then, use a “show” block to make the stars visible
  • Position them with the “go to” block and use the “glide” block to move it left for 10 seconds. 
  • “Hide” the sprite when it reaches the edge of the screen and the forever block will start this animation over again.
Flying space cat scratch tutorial step 2

Hint: Add more images or use a different image than stars.png to customize your scrolling background.

Step 3: Add flying cat and move it

Let’s position our flying cat and add the logic to move it up and down with arrows.

  • Select “Choose a Sprite”, find the Cat flying sprite, and click to add it
  • Use the “Go to” block to position the sprite at x= -150 y=0
  • Add music with the “Forever” and “Play Sound Until Done” block. We’re using the Dance Magic sound which you can add in the Sounds tab.
Flying space cat scratch tutorial step 3A

Now, add logic to the arrow keys so our cat moves up and down when we click.

  • Under events choose the “when key pressed” block and select “up arrow”
  • Underneath use a “change y by” block and enter 5 to move up
  • Go back to events,  choose the “When key pressed” block and select “down arrow”
  • Underneath use a “change y by” block and enter -5 to move down
Flying space cat scratch tutorial step 3B

Hint: Change the music by adding more sound options in the “Sounds” tab. Then select them in the “play sound” block.

Step 4: Show random crystals and move them

We want random crystals to appear on the right side of the screen and move toward the left. 

  • Select “Choose a Sprite”, find the Crystal sprite, and click to add it
  • Add the “When Green Flag Clicked” and a “Forever” block underneath it to repeat the movement of the crystals
  • Go to the “variables” blocks and “Make a variable”, name it Y-Position, and uncheck it
Flying space cat scratch tutorial step 4A
Flying space cat scratch tutorial step 4A
  • Inside the “forever” block “show” the crystal and set it to a random position on the right side using “go to x” with x=240 and y=y-position
  • Then, glide 2 seconds to x=-240 and y=y-position
  • Use “set” y-position to a random number between 100 and -100, so it shows up in a different position next time
  • “Hide” the crystal then wait a random amount of time between 1 and 2 seconds to repeat the loop
Flying space cat scratch tutorial step 4B

Hint: Select a different sprite or draw your own sprite to customize your collection item.

Step 5: Add up losing crystals

When a crystal flies by us and we don’t catch it, we want to count it. When we reach 3 crystals, the game is over. Let’s add on to the code you started in Step 4.

  • Go to the “variables” blocks and “Make a variable”, name it Crystal, and uncheck it
  • Under “when green flag clicked” set the Crystal variable to 0
  • Create an “if” block with the condition “touching edge”.
  • Inside this “if” block, change the crystal variable by 1. Add it under the “hide” block. Now each time it touches the edge, we add one. 
Flying space cat scratch tutorial step 5A
  • Add another “if” block inside the first “if” block. Use the condition “crystal = 3”.
  • Then we will broadcast a new message named “Game Over”
  • Add a “stop all” block to stop the game once the number of crystals reaches 3.
Flying space cat scratch tutorial step 5B

Hint: You can give different names to your variables, just make sure you are using the right variable in your code.

Step 6: Increase score for gaining crystals

Every time our flying cat touches a crystal, we want to increase our score. In addition to increasing the score, we will also decrease the count of the crystal variable. We do this because even though we are hiding the crystal, it still touches the edge each time.

  • Go to the “variables” blocks and “Make a variable”, name it Score. Keep it checked so it shows on your game screen.
  • Add the “When Green Flag Clicked” and set the Score to 0
  • Next, add a “Forever” block underneath
Flying space cat scratch tutorial step 6A

Inside the forever block, we will add to the game score every time our cat touches a crystal.

  • Use an “if” block with the condition “touching cat flying” sprite
  • Add the “start sound” block and select “magic spell” for a sound effect
  • Then change the score variable by 1 and the crystal variable by -1
  • Hide the crystal once it’s collected 
Flying space cat scratch tutorial step 6B

Hint: Change the variable “score” to give yourself more points for each crystal. Make sure to also decrease “crystal” by the same amount.

Step 7: Show “Game Over” screen

Your game is almost complete! Let the players know when the game is over by showing a game over screen. This will trigger when you’ve missed three crystals.

  • Select “paint” under sprites and rename this sprite Game Over.
  • In the costumes tab, select the rectangle tool and click and drag to draw a rectangle
  • Then, use the type tool with font “marker” and add the message “Game Over”
  • Adjust the message on your game screen
Flying space cat scratch tutorial step 7A
  • Go back to the “Code” tab 
  • Add the “When Green Flag Clicked” and hide block. That means this message will not show when the game starts
  • Add the “receive broadcast” block and select game over. This is the message we sent from the crystal sprite when the crystal variable reached 3.
  • Then, add the “stop all” block to end the game.
Flying space cat scratch tutorial step 7B

Hint: You can change the font, colors, and text for your Game Over message in the “Costumes” tab. 

Your Flying Space Cat game is complete!

Click the green flag and give it a try. If you want to let other people see your project and remix it, click the “Share” button at the top. 

Flying space cat scratch tutorial complete

See the complete Flying Space Cat game.

Download Free Printable Scratch Coding Tutorials PDF

Get the Rocketship Landing game and Flying Space Cat Scratch tutorials in a printable format.

More Scratch Tutorials for Kids

How To Make a Game on Scratch

If you want to build more games in Scratch, check out our Elementary School Coding Program. It’s the most fun and effective way to learn Scratch coding and eventually real-world languages like JavaScript and Python. Classes are live, online with an experienced instructor that is there to support you every step of the way. 

Ready to level up your child’s learning experience? Try the best online coding classes for kids.

The post Scratch Coding for Kids: Halloween Candy Collector Game appeared first on CodeWizardsHQ.

]]>
JavaScript Tutorial for Kids: Disappearing Snowman https://www.codewizardshq.com/javascript-tutorial-for-kids-disappearing-snowman/ Mon, 05 Dec 2022 14:00:00 +0000 https://www.codewizardshq.com/?p=53334 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Guess the right word before your snowman melts!  We’ve created this tutorial just in time for the holidays. Code a fun word game that you can share with family and friends.  This Christmas-themed guessing game uses simple JavaScript code to power the game functions. Try coding this game following the tutorial and then customize it […]

The post JavaScript Tutorial for Kids: Disappearing Snowman appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Guess the right word before your snowman melts! 

We’ve created this tutorial just in time for the holidays. Code a fun word game that you can share with family and friends. 

📌 [Download] JavaScript Projects Source Code Get the full source code for seven JavaScript project examples. Download Now

This Christmas-themed guessing game uses simple JavaScript code to power the game functions. Try coding this game following the tutorial and then customize it to make it your own.

Complete this JavaScript tutorial to make your own Disappearing Snowman Game.

Play the completed Disappearing Snowman Game.

Disappearing snowman javascript game

Recommended: JavaScript for Kids

What you need:

1. Text editor

We’ll be using the CodeWizardsHQ editor to write and run our JavaScript code.

You can also use an online text editor like replit that allows you to author and run JavaScript programs in a web browser. Make sure you have all of the project base files in order for your program to work correctly.

2. Base Files

Download the base files and open the app.js file. This folder contains all the images and files you will need to complete your game.

  • The HTML file holds the page title, emojis, and Player/Computer choice text. 
  • The CSS file adds some styling to our page and helps lay out the HTML elements. 
  • The error-handler.js file will display a big red error box on the page if you make an error while typing out your JavaScript code. 
  • The app.js file is where we’ll write our application code.

If you’re a CodeWizardsHQ student, download the x_hour_of_code_2022 project for the completed code. The starter files are in the javascript-projects/disappearing-snowman/starter-files directory.

Note: The index.html file (which executes the JavaScript) expects the filename app.js so you must use the same file name if you’re using your own text editor! You’ll edit the app.js file but you’ll always run the index.html file.

This tutorial is for beginner JavaScript programmers ages 8+. It assumes you understand basic HTML/CSS and JavaScript. Let’s get started!

Step 1: Fade keyboard keys on click

When someone uses our app, they’ll try to guess the hidden word one letter at a time by clicking the keyboard on the page with their mouse. In this step, we’ll fade out each letter they click and ensure that no more logic runs on a faded-out letter. 

  • In the styles.css file there’s a CSS class to make a keyboard key look faded out called selected. We’ll attach this class to whatever keyboard key the user clicks using JavaScript. You don’t have to type anything in the CSS file, this is just provided as a reference so you know why attaching this class to an HTML element makes it look faded out.
/* Added by JavaScript */

.hidden {
    display: none;
}

.selected {
    opacity: 0.3;
}

Navigate back to your app.js file to add the selected class to any key the user clicks.

  • First, create a variable called keyboardContainer
  • Use the document.querySelector() function to reference the element with the ID of keyboard-container and store it in the keyboardContainer variable
  • Then, we need to run code whenever an element in the keyboardContainer is clicked. We can use the addEventListener() function to ensure a function called handleKeyboardClick() (which we’ll define in just a minute) will run whenever a user clicks inside the keyboardContainer. The click event is triggered by clicking your mouse anywhere inside the keyboardContainer HTML element.
var words = ["APPLE", "PANCAKES", "COMPUTER", "PARIS", "MICROPHONE", "PASTRY"];
var randomWord = getRandomWord(words);

var keyboardContainer = document.querySelector("#keyboard-container");
keyboardContainer.addEventListener("click", handleKeyboardClick);
  • Create the function handleKeyboardClick() and define a single parameter called event that will be passed to this function whenever the keyboardContainer is clicked.
  • Whenever our keyboardContainer is clicked, we’ll run the handleKeyboardClick() function. 
keyboardContainer.addEventListener("click", handleKeyboardClick);

generateHiddenWord(randomWord);

function handleKeyboardClick(event) {

}
  • Create a variable called clickedElement. We can get information about the element that was clicked by using the target property. We’ll store the element that was clicked in the variable.
  • Anytime a user clicks inside the keyboardContainer element our click event listener will fire. But, we only want to continue if they click on a letter. Check if the clickedElement does not (!) contain the letter class or if (||) contains the selected class (which we’ll add next). If either of those conditions is true, we’ll use the return keyword to immediately exit the function. 
  • Finally, we’ll add the selected class to our clickedElement to ensure the CSS styles are applied to make it fade out a bit. 
function handleKeyboardClick(event) {

    var clickedElement = event.target;

    if (!clickedElement.classList.contains("letter") || clickedElement.classList.contains("selected")) return;

    clickedElement.classList.add("selected");

}

Hint: Test this out by clicking a few of the keys on the HTML page. They should fade out as you click them!

Step 1 Output:

Javascript tutorial step 1

Step 2: Check for a match when clicking a keyboard key

In this step, we’ll check to see if the keyboard key a user clicks matches any of the letters in the hidden word. If so, we’ll show all of the matching letters in the hidden word.

  • First, let’s define a function called checkForMatch(). This function will take the clickedLetter as a parameter and will check to see if it matches any of the hidden letters.
  • Create a variable called hiddenLetterElements where we’ll store references to the hidden letters. We’ll need to know all of the hidden letters on the page in order to compare them with the clickedLetter parameter. To get them, use document.querySelectorAll() and select all elements with the class hidden. The querySelectorAll() method returns an array-like object that represents any HTML elements with the selector passed into the parentheses. 
generateHiddenWord(randomWord);

function checkForMatch(clickedLetter) {
  var hiddenLetterElements = document.querySelectorAll(".hidden");
}

function handleKeyboardClick(event) {
  ...
}
  • Once we have all of the hiddenLetterElements, we can use a for...of loop to loop through the hidden letters one at a time. We’ll compare them with the clickedLetter that was passed in as a parameter to the function.
  • In the for...of loop, create a variable called hiddenLetter and get the textContent of the hiddenLetterElement. 
  • Then, use a conditional statement to compare the hiddenLetter with our clickedLetter parameter and see if they are the same. The === operator ensures that both items it compares are equal.
  • The last thing we need to do in our checkForMatch() function is to remove the hidden class from any hiddenLetterElement whose letter matches the clickedLetter. The remove() method of the classList object allows us to remove a class from an HTML element.

function checkForMatch(clickedLetter) {
    var hiddenLetterElements = document.querySelectorAll(".hidden");

    for (var hiddenLetterElement of hiddenLetterElements) {
        var hiddenLetter = hiddenLetterElement.textContent;
        if (hiddenLetter === clickedLetter) {
            hiddenLetterElement.classList.remove("hidden");
        }
    }
}
  • Finally, back in our handleKeyboardClick() function, create a clickedLetter variable to store the textContent of the clickedElement.
  • Then we’ll pass this variable to our new checkForMatch() function. This ensures that whenever a user clicks a keyboard letter, handleKeyboardClick() will check for a match with that letter and all of the hidden letters. 
  • Run your program and try clicking a few of the keyboard letters. You should see the ones that match the hidden letters show up on the page!
function handleKeyboardClick(event) {
    var clickedElement = event.target;
   
    if (!clickedElement.classList.contains("letter") || clickedElement.classList.contains("selected")) return;

    clickedElement.classList.add("selected");

    var clickedLetter = clickedElement.textContent;
    checkForMatch(clickedLetter);

}

Step 2 Output:

Javascript tutorial step 2

Step 3: Remove a snowman part when there’s no match for a clicked keyboard key

Now that we can tell if a user found a match or not, we need to remove a snowman part whenever there isn’t a match. This makes it seem like the snowman is melting if you guess a letter incorrectly!

  • Our snowman is made up of a few parts that are distinguished by CSS classes. The main parts have the classes hat, face, scarf, hands, body-top, body-middle, and body-bottom. You can see these parts if you view the HTML in index.html

snowman html css

index.html (no changes here, just shown for context)

<section id="snowman-container">
    <img class="hat" src="images/hat.png" />
    <img class="face nose" src="images/nose.png" />
    <img class="face eyes" src="images/eyes.png" />
    <img class="face mouth" src="images/mouth.png" />
    <img class="scarf" src="images/scarf.png" />
    <img class="hands left-hand" src="images/left-hand.png" />
    <img class="hands right-hand" src="images/right-hand.png" />
    <img class="body-top" src="images/body-top.png" />
    <img class="body-middle" src="images/body-middle.png" />
    <img class="body-bottom" src="images/body-bottom.png" />
</section>
  • In app.js, create an array called snowmanParts and store each of the classnames. Order them from top (hat) to bottom (body-bottom). Note that each snowman part starts with a dot (.). This is a CSS notation that indicates each string represents a CSS class, and we’ll use the strings in the snowmanParts array to query the correct HTML element by its class name. 

app.js

var words = ["APPLE", "PANCAKES", "COMPUTER", "PARIS", "MICROPHONE", "PASTRY"];
var randomWord = getRandomWord(words);
var keyboardContainer = document.querySelector("#keyboard-container");
var snowmanParts = [".hat", ".face", ".scarf", ".hands", ".body-top", ".body-middle", ".body-bottom"];

keyboardContainer.addEventListener("click", handleKeyboardClick);
  • Create a function called removeSnowmanPart(). This function will remove a single snowman part associated with those main classes each time the user guesses a letter that isn’t one of the hidden letters.
  • To remove the snowman parts from top-to-bottom, we need to remove the first item from the array each time removeSnowmanPart() is called. To remove the first item from an array, you use the Array.shift() method. We’ll store the removed item (which represents a CSS class) in a variable called snowmanPart.
  • Next, create a variable called partsToRemove to store these parts. Get the HTML element that represents the snowmanPart using document.querySelectorAll(). Remember, snowmanPart is a CSS selector (it starts with a dot) and querySelectorAll() will give us an array-like object of all HTML elements matching the selector we give it. 
function removeSnowmanPart() {
    var snowmanPart = snowmanParts.shift();
    var partsToRemove = document.querySelectorAll(snowmanPart);
}
  • The final step of our function definition will be to loop through all of the partsToRemove and remove each part from the HTML document. To do this, we can create a for...of loop and then call the element.remove() function on each partToRemove. The element.remove() function removes an HTML element from the page.
function removeSnowmanPart() {
    var snowmanPart = snowmanParts.shift();
    var partsToRemove = document.querySelectorAll(snowmanPart);

    for (var partToRemove of partsToRemove) {
        partToRemove.remove();
    }
}
  • Before we can determine if the user guessed incorrectly, we’ll need to edit the checkForMatch() function to return a boolean value: true or false. We start hasMatch as false, and only change it to true if there is a match when we are comparing the clickedLetter to the hiddenLetter in the for...of loop.
  • The removeSnowmanPart() function should be called only when the user doesn’t guess the correct hidden letter in our handleKeyboardClick() function. The checkForMatch() function will return true if we found a match, and false otherwise. 
function checkForMatch(clickedLetter) {
    var hiddenLetterElements = document.querySelectorAll(".hidden");
    var hasMatch = false;
    for (var hiddenLetterElement of hiddenLetterElements) {
        var hiddenLetter = hiddenLetterElement.textContent;
        if (hiddenLetter === clickedLetter) {
            hiddenLetterElement.classList.remove("hidden");
            hasMatch = true;
        }
    }

    return hasMatch;
}
  • Finally, in our handleKeyboardClick() function, we can create a variable called hasMatch and store the returned value from the checkForMatch() function. Remember, this variable is either the boolean value true or false
  • We can then use that value in a conditional statement and call the removeSnowmanPart() function if there was no match. The ! operator means “not”, so we’re saying “If there’s no match, remove a snowman part” in this code sample.
function handleKeyboardClick(event) {
    var clickedElement = event.target;

    if (!clickedElement.classList.contains("letter") || clickedElement.classList.contains("selected")) return;

    clickedElement.classList.add("selected");

    var clickedLetter = clickedElement.textContent;
    var hasMatch = checkForMatch(clickedLetter);

    if (!hasMatch) {
        removeSnowmanPart();
    }
}

Step 3 Output

Javascript tutorial step 4

Recommended: JavaScript Classes for Kids

Step 4: Check if the player loses

A game is no fun without winners and losers! In this step, we’ll show a message if the user guesses incorrectly too many times and the snowman melts before they guess the hidden word. 

  • We’ll create a function called checkForLoser() to check if the snowman has melted and the user loses. You lose when the snowman has melted, and in our program we’re removing a part from the snowmanParts array every time a user guesses a letter that isn’t in the hidden word. The snowman will be “melted” when there are no parts left in the snowmanParts array. We can check if there are no parts left in the snowmanParts array using a conditional statement and by comparing the length property of the snowmanParts array to 0.
function checkForLoser() {
    if (snowmanParts.length === 0) {

    }
}
  • In our conditional statement, we’ll add two messages to the page. The first will replace all the HTML in the snowman-container element with the text “You lost, game over!”. The second will replace all of the HTML in the keyboardContainer with the text “The word was: [RANDOM WORD]”. The RANDOM WORD will be whatever value is stored in the randomWord variable. Note that we can query and adjust the snowman-container on a single line since we don’t already have a reference to that HTML element stored in a variable. 
function checkForLoser() {
    if (snowmanParts.length === 0) {
        document.querySelector("#snowman-container").innerHTML = "<h2>You lost, game over!</h2>";
        keyboardContainer.innerHTML = `<h2>The word was: ${randomWord}</h2>`; 

    }
}
  • Now that our checkForLoser() function is working, we need to call it whenever the user clicks a key on the keyboard and the letter doesn’t match a letter in the hidden word. We’ve already got a conditional statement in the handleKeyboardClick() function to check if the user didn’t guess a matching letter, so we can call our checkForLoser() function after the removeSnowmanPart() function. This will ensure that we only check if the snowman is melted after removing a snowman part.
function handleKeyboardClick(event) {
    var clickedElement = event.target;

    if (!clickedElement.classList.contains("letter") || clickedElement.classList.contains("selected")) return;

    clickedElement.classList.add("selected");

    var clickedLetter = clickedElement.textContent;
    var hasMatch = checkForMatch(clickedLetter);

    if (!hasMatch) {
        removeSnowmanPart();
        checkForLoser();
    }
}

Step 4 Output

Javascript tutorial step 4

Step 5: Check if the player wins

For our final step, we’ll show a message if the player guesses the hidden word without melting the snowman!

  • First, we’ll create a function called checkForWinner(). A user wins when there are no more hidden letters, so this function’s job will be to show a winning message when there are no more hidden letters on the page.
  • Create a variable called hiddenLetterElements. To check for hidden letters, we first need a reference to all of the elements on the page with the class hidden. We can use document.querySelectorAll() to get an array of all the HTML elements with the class hidden and store them in hiddenLetterElements.
function checkForWinner() {
    var hiddenLetterElements = document.querySelectorAll(".hidden");
}
  • We can check the length property of the hiddenLetterElements array to see if there are any more HTML elements with the hidden class on the page. If the length property is 0, there are no more hidden letters on the page.
  • When there are no more hidden elements, the user wins! We can use the innerHTML property of the keyboardContainer to put a winning message on the page in place of the keyboard.
function checkForWinner() {
    var hiddenLetterElements = document.querySelectorAll(".hidden");
    if (hiddenLetterElements.length === 0) {
        keyboardContainer.innerHTML = "<h2>You win!</h2>";
    }
}
  • Finally, we need to call our checkForWinner() function every time the user guesses a letter correctly. We’re checking if the user guessed correctly in handleKeyboardClick(). We can add an else clause to our conditional statement at the end of that function and call our checkForWinner() function in the body of the else clause. This guarantees that every time the user has a match, we check if they won.
function handleKeyboardClick(event) {
    var clickedElement = event.target;

    if (!clickedElement.classList.contains("letter") || clickedElement.classList.contains("selected")) return;

    clickedElement.classList.add("selected");

    var clickedLetter = clickedElement.textContent;
    var hasMatch = checkForMatch(clickedLetter);

    if (!hasMatch) {
        removeSnowmanPart();
        checkForLoser();
    } else {
        checkForWinner();
    }
}

Step 5 Output

Javascript tutorial step 5

Your program is complete!

Check out the finished Disappearing Snowman Game.

Javascript tutorial completed game

Download the project files and open app.js to view the completed project.

This is just an example of what you can build when you learn JavaScript. There are plenty of exciting projects you can try and continue to build your skills.

Download JavaScript Projects Source Code

If you want to get the code behind 7 different JavaScript projects, download the full source code for free. You can use this code as an example to add to or inspire new projects. Enter your email below:

If you want to code more websites and games in JavaScript, join CodeWizardsHQ’s live coding classes for kids. It’s the most fun and effective way for kids to learn JavaScript and other real-world languages.. 

Students in all of our core tracks study JavaScript because of its importance in web development and beyond. They work with a live, expert instructor who supports them every step of the way. Classes are engaging and you’ll build a portfolio of websites, games, and apps as you learn. 

Have fun and happy holidays!

The post JavaScript Tutorial for Kids: Disappearing Snowman appeared first on CodeWizardsHQ.

]]>
Python Tutorial for Kids: “Pig” Dice Game https://www.codewizardshq.com/python-tutorial-for-kids-pig-dice-game/ Fri, 11 Nov 2022 07:26:24 +0000 https://www.codewizardshq.com/?p=53313 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

“Pig” is an easy and fun dice game that anyone in the family can play. You only need one die in hand and know basic arithmetic to play the game. It’s an entertaining way for kids to practice adding and learn about probability. If there’s no one around to play with, you can challenge the […]

The post Python Tutorial for Kids: “Pig” Dice Game appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

“Pig” is an easy and fun dice game that anyone in the family can play. You only need one die in hand and know basic arithmetic to play the game. It’s an entertaining way for kids to practice adding and learn about probability.

📌 [Download] Free Python Lesson Plans Get free 1-week Python lesson plans and slides for kids ages 11-13 to start learning about Python coding. Download Now

If there’s no one around to play with, you can challenge the computer! Build your own “Pig” game using Python that you can play anytime. This simple app will roll the dice for you and the computer and add up your points too. All you have to do is click.

Complete this Python coding tutorial to make your own “Pig” Dice Game.

Pig dice game

This is a beginner Python tutorial that will walk you through all of the code from start to finish.

Play the completed “Pig” Dice Game

What you need:

1. Text editor

We’ll be using the CodeWizardsHQ editor to write and run our Python code. If you’re a CodeWizardsHQ student, download the x_hour_of_code_2022 project for the completed code. 

You can also use an online text editor like replit that allows you to author and run Python programs in a web browser.

2. An empty Python file

Create a new empty Python file and add your code there. 

Our file is named main.py. If you’re using another platform to write and execute your code, you can choose whichever name you like.

This tutorial is for beginner Python programmers ages 11+. It assumes you understand basic Python code. Let’s get started!

Step 1: Create and display a welcome message with the game rules

We’ll begin by displaying a welcome message to the user that explains the rules of “Pig”, the dice game we’ll build in this project.

  • Create a multi-line string representing the game rules of “Pig” and store this string inside a variable called welcome_message.


welcome_message = """
          Welcome to 'Pig', a dice game!
   
    In this game, a user and a computer opponent
    roll a 6-sided die each round. If the value of
    the die is a 1, the player that rolled the 1 loses
    all of their points. Otherwise, the player gets the
    value of the die added to their points. The first
    player to reach 30 points wins!
"""
  • Use Python’s built-in print() function to display the welcome_message. Note, don’t type the … characters, those are used to hide unnecessary code from an example!
welcome_message = """
        ...
"""

print(welcome_message)

Step 1 Output:

Python tutorial step 1 output

Step 2: Get the user’s name and create the game loop

Prompt the user for their name, create a game loop, and allow the user to roll the dice.

  • Create a variable called username.
  • Use the input() function to prompt the user for their name and store it in the variable.
welcome_message = """
        ...
"""

print(welcome_message)

username = input("What is your name? ")
  • Create a while loop to represent the game loop.
  • Inside the while loop, use the input() function to prompt the user to press “Enter” to roll the die.
username = input("What is your name? ")

while True:
    input(f"Press 'Enter' to roll the die {username}!\n")
  • Add a break statement to ensure the loop only runs once. We do this while building a game to make it easy to test out our game logic once and then exit.
while True:
    input(f"Press 'Enter' to roll the die {username}!\n")

    break

Hint: Ask any question you like and get the input from the user. The \n notation adds an additional new line which makes our output look a little nicer.

Step 2 Output:

Python tutorial step 2 output

Step 3: Simulate rolling dice

Simulate rolling a six-sided die and display the player’s and computer’s roll.

  • Import the randint() function from Python’s built-in random module. This function allows us to generate random numbers, which we’ll use to “fake” rolling a six-sided die. Imports should always appear at the top of your file, before any other code.
from random import randint


welcome_message = """
    ...
"""
  • In the while loop, use the randint() function to generate a random number between 1 and 6. Store this number in a player_die_value and use an f-string to display the username and player_die_value.
while True:
    input(f"Press 'Enter' to roll the die {username}!\n")

    player_die_value = randint(1, 6)
    print(f"{username} rolls a {player_die_value}")

    break
  • Use the randint() function to generate another random number between 1 and 6. Store this number in a computer_die_value and use an f-string to display the computer_die_value. Note that the break statement still needs to be the last thing in the while loop.
while True:
    input(f"Press 'Enter' to roll the die {username}!\n")

    player_die_value = randint(1, 6)
    print(f"{username} rolls a {player_die_value}")

    computer_die_value = randint(1, 6)
    print(f"Computer rolls a {computer_die_value}")

    break

Step 3 Output:

Python tutorial step 3 output

Step 4: Create a function to update the scores of each player

Now, let’s calculate and track the player’s and computer’s score after each roll. We’ll create a function to determine whether each player gets points added to their score or gets their score reset to 0.

  • Create two variables to hold the scores of our players: player_score and computer_score. Each variable should initially be set to 0 because our players start with no points.
player_score = 0
computer_score = 0

welcome_message = """
    ...
"""
  • Define a function at the top of your file called update_score(). It should take two parameters: score and die_value. We’ll use this function to return 0 if the die_value is 1 and the sum of the score and die_value for any other die_value. Function definitions always go at the top of your file, after any import statements.
from random import randint


def update_score(score, die_value):



player_score = 0
computer_score = 0
  • In the body of the update_score() function, add an if…else conditional statement. We’ll return 0 if the die_value is 1, and the sum of the score and die_value for any other case. The return statement lets us send a value out of a function that can be used by the function caller.
def update_score(score, die_value):

    if die_value == 1:
        return 0
    else:
        return score + die_value

  • In the while loop, use update_score with the player and computer’s score and die values. Store the return values in player_score and computer_score variables.
while True:
    ...

    computer_die_value = randint(1, 6)
    print(f"Computer rolls a {computer_die_value}")

    player_score = update_score(player_score, player_die_value)
    computer_score = update_score(computer_score, computer_die_value)

    break
  • Use the f-string syntax f”{variable_name=}” syntax to test that the player_score and computer_score take on the value you’d expect based on the die value of each player. That special syntax prints the variable name along with its value, and is a handy debugging tool when you’re developing a program and want to confirm a variable’s value! Note that the break statement still needs to be the last line of the while loop.
while True:
    ...

    player_score = update_score(player_score, player_die_value)
    computer_score = update_score(computer_score, computer_die_value)

    print(f"{player_score=}")
    print(f"{computer_score=}")

    break

Step 4 Output:

Python tutorial step 4 output

Step 5: Display a formatted scoreboard

In this step, we’ll make our game feel a bit more realistic by creating and displaying a scoreboard each round that holds the current score.

  • At the top of your file, create a function called display_scoreboard() that takes two parameters: player_score and computer_score. 
def update_score(score, die_value):
    ...


def display_scoreboard(player_score, computer_score):
  • In the body of the display_scoreboard() function, use print() statements to display a formatted scoreboard. Empty print() statements give us some newline padding between calls to display_scoreboard().
def display_scoreboard(player_score, computer_score):

    print()
    print("#" * 20)
    print(f"Player Score: {player_score}")
    print(f"Computer Score: {computer_score}")
    print("#" * 20)
    print()
  • In the while loop, remove the print() statements that displayed the player_score and computer_score.
while True:
    ...

    player_score = update_score(player_score, player_die_value)
    computer_score = update_score(computer_score, computer_die_value)

    print(f"{player_score=}")    # Remove this!
    print(f"{computer_score=}")  # Remove this!

    break
  • Use the display_scoreboard() function to display your formatted scoreboard. The break statement still needs to be the final statement in your while loop.
while True:
    ...

    player_score = update_score(player_score, player_die_value)
    computer_score = update_score(computer_score, computer_die_value)

    display_scoreboard(player_score, computer_score)

    break

Hint: You can create multiple copies of a string in Python using the star (*) operator, which is a handy tool for building our scoreboard banner.

Step 5 Output:

Python tutorial step 5 output

Step 6: Determine the game winner

In the final step, we’ll check the scores of each player at the end of our game loop and determine who wins! The first player to reach 30 points is the winner.

  • At the end of the while loop, remove the break statement.
while True:
    ...

    player_score = update_score(player_score, player_die_value)
    computer_score = update_score(computer_score, computer_die_value)

    display_scoreboard(player_score, computer_score)

    break  # Remove this!
  • Add an if…elif conditional statement to determine the winner. Each conditional body should display the respective winner and exit the while loop with a break statement.
while True:
    ...

    display_scoreboard(player_score, computer_score)

    if player_score >= 30:
        print(f"{username} wins!")
        break
    elif computer_score >= 30:
        print("Computer wins!")
        break

Step 6 Output:

Python tutorial step 6 output

Hint: We didn’t handle ties in this version, but challenge yourself to do that with another “if” statement.

Your game is complete!

Check out the finished project.

Complete python tutorial for kids

Download the project files and open main.py to view the completed project.

We’ve built a simple version together, but there’s plenty more you can do to customize and upgrade your version of “Pig”. 

Download 1-Week Python Lesson Plans

Kds ages 11-13 can start learning Python in a structured way. Download a FREE 1-week lesson plan with activities and slides. Enter your name and email to receive the free lesson plans in your inbox today.

If you want to build more games and apps in Python, join CodeWizardsHQ’s live coding classes for kids. It’s the most fun and effective way for kids to learn Python and advance to a real-world coding internship. 

Students in our middle school and high school core track start by learning fundamental coding concepts in Python. They work with a live, expert instructor who supports them every step of the way. Classes are engaging and you’ll build personalized projects and applications in every lesson. 

Enjoy this project!

The post Python Tutorial for Kids: “Pig” Dice Game appeared first on CodeWizardsHQ.

]]>
JavaScript Tutorial for Kids: Rock, Paper, Scissors https://www.codewizardshq.com/javascript-tutorial-for-kids-rock-paper-scissors/ Fri, 11 Nov 2022 07:11:01 +0000 https://www.codewizardshq.com/?p=53373 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Is rock, paper, scissors more about skill or luck? Everyone has their own theory, but it’s one of those games that we all love to play when we’re bored. The logic is relatively simple, so it’s an easy game for beginners to turn into code too. You can replicate this game in any coding language, […]

The post JavaScript Tutorial for Kids: Rock, Paper, Scissors appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Is rock, paper, scissors more about skill or luck? Everyone has their own theory, but it’s one of those games that we all love to play when we’re bored.

The logic is relatively simple, so it’s an easy game for beginners to turn into code too. You can replicate this game in any coding language, but JavaScript is a great way to play.

📌 [Download] JavaScript Projects Source Code Get the full source code for seven JavaScript project examples. Download Now

In this tutorial, we’ll automate a game of Rock, Paper, Scissors versus the computer. Use computational thinking to setup the game and handle the possible game outcomes. Follow this tutorial to build your own rock, paper, scissors game and try out your luck (or skills!).

Complete this JavaScript tutorial to make your own Rock, Paper, Scissors game.

Play the completed Rock, Paper, Scissors.

Rock paper scissors javascript game

Recommended: JavaScript for Kids

What you need:

1. Text editor

We’ll be using the CodeWizardsHQ editor to write and run our JavaScript code.

You can also use an online text editor like replit that allows you to author and run JavaScript programs in a web browser. Make sure you have all of the project base files in order for your program to work correctly.

2. Base Files

Download the base files and open the app.js file. This folder contains all the images and files you will need to complete your game.

  • The HTML file holds the page title, emojis, and Player/Computer choice text. 
  • The CSS file adds some styling to our page and helps lay out the HTML elements. 
  • The error-handler.js file will display a big red error box on the page if you make an error while typing out your JavaScript code. 
  • The app.js file is where we’ll write our application code.

If you’re a CodeWizardsHQ student, download the x_hour_of_code_2022 project for the completed code. The starter files are in the javascript-projects/rock-paper-scissors/starter-files directory. 

Note: The index.html file (which executes the JavaScript) expects the filename app.js so you must use the same file name if you’re using your own text editor! You’ll edit the app.js file but you’ll always run the index.html file.

This tutorial is for beginner JavaScript programmers ages 8+. It assumes you understand basic HTML/CSS and JavaScript. Let’s get started!

Step 1: Add some setup code to handle the player’s choice.

We’ll begin by adding code to set up when the player clicks the emoji to make their choice.

  • Open the app.js file, all of the code in this tutorial will go into this file.
  • Create a playerChoice variable representing the player’s choice and set it to an empty string (the "" characters denote a string). We’ll declare this variable at the top of our file because we want to use it in a few places

Note: We’ll define all of our functions at the bottom of the file, and leave the variable declarations, event listener registration, and function calls at the top of our file.

var playerChoice = "";
  • Use document.querySelector() to select the #player-choice-container HTML element (the # means this is the ID of the element) and store it in a variable called playerChoiceContainer. This is the section that holds the player’s emojis. 
var playerChoice = "";

var playerChoiceContainer = document.querySelector("#player-choice-container");
  • Attach an event listener to the playerChoiceContainer that will run the handlePlayerChoice() function (which we’ll create next) whenever this container with the player’s emojis is clicked. 
var playerChoiceContainer = document.querySelector("#player-choice-container");

playerChoiceContainer.addEventListener("click", handlePlayerChoice);
  • Create a function called handlePlayerChoice() that records the players emoji selection. Since this is an event-handler function attached to a click event, use an event parameter representing the click event in the parenthesis. Note that there is no change in the output for this step!
playerChoiceContainer.addEventListener("click", handlePlayerChoice);

function handlePlayerChoice(event) {

}
rock paper scissors step 1

Step 2: Add logic to handle the player’s choice

Once the player clicks on their emoji choice, we need to add logic that will save their choice and display it on the screen.

  • In the handlePlayerChoice() function, add an if statement. If the element that was clicked (the event.target) does not (!) contain the class emoji, we will exit the function. This means that if a player clicks next to an emoji, none of the other function code runs. If they click on an emoji, it will run. The return statement exits a function immediately and can optionally return a value to the function caller.
function handlePlayerChoice(event) {
    if (!event.target.classList.contains("emoji")) return;

}
  • Get the text content of the clicked element (the emoji) and save it in the playerChoice variable. We’ll then change the innerHTML of the playerChoiceContainer to only display the emoji that was clicked. 
function handlePlayerChoice(event) {
    if (!event.target.classList.contains("emoji")) return;

    playerChoice = event.target.textContent;
    playerChoiceContainer.innerHTML = `<p class="emoji">${playerChoice}</p>`;

}

Step 2 Output

rock paper scissors step 2

Step 3: Show an emoji on the page for the computer’s choice

We’ll create a function that will eventually shuffle the emojis on the page and display the computer’s choice. In this step, we’ll create the function and display a single emoji choice on the page.

  • Create a variable called computerChoice that will hold the computer’s choice. We want to be able to access the variable in a few places so we’ll create it at the top of our file to ensure that it is global.
var playerChoice = "";
var computerChoice = "";
  • Create an array, a type of data that holds several items in a single variable, called emojis that holds the Rock, Paper, and Scissors emoji characters. Note that the scissors emoji needs to have an additional space after the emoji, as the quote characters overlap the emoji if you don’t add a space on the right-hand side in most text editors. 


You can find each emoji here:

  • https://emojipedia.org/rock/
    • 🪨
  • https://emojipedia.org/page-facing-up/
    • 📄
  • https://emojipedia.org/scissors/
    • ✂
var playerChoice = "";
var computerChoice = "";
/*
 * Note that the scissors emoji has to have an extra space!
 */
var emojis = ["✂ ", "📄", "🪨"];
  • In a variable called emojiShuffleElement, use document.querySelector() to get a reference to the #emoji-shuffle element.
var emojis = ["✂ ", "📄", "🪨"];

var playerChoiceContainer = document.querySelector("#player-choice-container");
var emojiShuffleElement = document.querySelector("#emoji-shuffle");
  • Next, create a function called shuffleEmojis(). This will eventually shuffle through the computer’s three emojis on a timer, but right now, it’ll simply pick whatever emoji we ask for from the emojis array and display it on the page. (Don’t type the ... characters. Those are an indicator that we’re leaving out code you don’t need to worry about right now.)
function handlePlayerChoice(event) {
    ...
}

function shuffleEmojis() {

}
  • Get an item from the emojis array and store it in the computerChoice variable. We use the [] brackets to access array items at an index number. Array indices start at 0, so the first element is at index 0, the second at index 1, etc. Here, we select the second item, the Paper emoji.
function shuffleEmojis() {
    computerChoice = emojis[1];
}
  • Get the text inside of your emojiShuffleElement variable by setting the textContent of the emojiShuffleElement to the computerChoice (which represents the emoji text). If you don’t need to change the HTML of an element, the textContent property is an easy way to display text on the screen. 
function shuffleEmojis() {
    computerChoice = emojis[1];
    emojiShuffleElement.textContent = computerChoice;
}
  • Next, call the shuffleEmojis() function. You should now see your chosen emoji appear under the “Computer’s Choice” text. Try changing the index number to a different emoji’s index in shuffleEmojis() to see if the emoji on the page changes! Note that you’ll need to refresh the page after each change in order to see the changes take effect.  
playerChoiceContainer.addEventListener("click", handlePlayerChoice);

shuffleEmojis();

function handlePlayerChoice(event) {
  ...
}

Step 3 Output

rock paper scissors step 3

Step 4: Shuffle the computer’s emoji choices

We’ll create a shuffle animation that shuffles through the Rock, Paper, and Scissors emojis quickly. This makes it seem like the computer is thinking about what choice it will randomly select.

  • Create a variable called currentEmojiNumber that will hold the index number of the emoji we’re currently displaying on the page during the shuffling process. We’ll start with the first index in the emojis array, index 0.
var emojis = ["✂ ", "📄", "🪨"];
var currentEmojiNumber = 0;
  • In the shuffleEmojis() function, use the currentEmojiNumber to pick an emoji out of the emojis array. 
function shuffleEmojis() {
    computerChoice = emojis[currentEmojiNumber];
    emojiShuffleElement.textContent = computerChoice;
}
  • We need to increase the currentEmojiNumber if we’re not on the last index of the emojis array and set it to 0 otherwise. We’ll use an if...else conditional statement to do this. Note that the emojis array has a length property that we can use to find out how big it is and that the last index number is 1 less than the length of the array. Also, note that we can increase the value stored in a variable using the ++ operator, as we do on the currentEmojiNumber here.
function shuffleEmojis() {
    computerChoice = emojis[currentEmojiNumber];
    emojiShuffleElement.textContent = computerChoice;

    if (currentEmojiNumber < emojis.length - 1) {
        currentEmojiNumber++;
    } else {
        currentEmojiNumber = 0;
    }

}
  • Remove the call to shuffleEmojis(). We’ll have JavaScript call this function in an interval timer instead.
playerChoiceContainer.addEventListener("click", handlePlayerChoice);

shuffleEmojis();  // REMOVE THIS!

function handlePlayerChoice(event) {
  ...
}
  • Use the setInterval() function to call the shuffleEmojis() function every 150 milliseconds. The setInterval() function is provided to us from the browser. It returns a reference to the ID of the running interval timer which we’ll store in a variable called shuffleIntervalID. This ID can be used to stop the interval timer, which we’ll do in the next step. 
var currentEmojiNumber = 0;

var shuffleIntervalID = setInterval(shuffleEmojis, 150);

var playerChoiceContainer = document.querySelector("#player-choice-container");

Step 4 Output

rock paper scissors step 4

Step 5: Pick a random emoji for the computer

Now that the computer’s possible choices are shuffling between Rock, Paper, and Scissors, we need to actually pick a random choice for the computer after the player makes their choice.

  • We’ll use the clearInterval() function to stop shuffleEmojis() inside our handlePlayerChoice() function. Since the shuffleIntervalID points to the interval timer that is running shuffleEmojis(), clearInterval() will stop that timer. 
function handlePlayerChoice(event) {
    if (!event.target.classList.contains("emoji")) return;
    playerChoice = event.target.textContent;
    playerChoiceContainer.innerHTML = `<p class="emoji">${playerChoice}</p>`;
    clearInterval(shuffleIntervalID);
}

Step 5 Output

rock paper scissors step 5

Step 6: Decide who won the game

For our last step, we’ll create a function to see who won the game.

  • Create a function called determineGameWinner(). This function will hold all the logic to determine who won the game.
function determineGameWinner() {

}
  • Create two variables: gameResultMessageElement and gameResultMessage. We can use document.querySelector() to get the HTML element with the ID of game-result-message and then the gameResultMessageElement. We’ll make the gameResultMessage an empty string for now because we won’t know the value of this variable until we determine who won.
playerChoiceContainer.addEventListener("click", handlePlayerChoice);

function determineGameWinner() {

    var gameResultMessageElement = document.querySelector("#game-result-message");
    var gameResultMessage = "";

}

function handlePlayerChoice(event) {
  ...
}
  • We can use a chain of conditional statements to determine if there is a tie, if the player won, or if the computer won. Set the gameResultMessage in the body of each conditional statement. Note that we only need to check for a tie and if the player won. If neither of those results occurs, then we can use the else clause to state that the computer won. Also, please make sure to add an extra space to the right of the scissors emoji to ensure your program works correctly (there’s an extra space in the HTML and in our emojis array).
function determineGameWinner() {
    var gameResultMessageElement = document.querySelector("#game-result-message");
    var gameResultMessage = "";

    if (playerChoice === computerChoice) {
        gameResultMessage = "It's a tie!";
        // Note the extra space in the scissors emoji!
    } else if (playerChoice === "🪨" && computerChoice === "✂ ") {
        gameResultMessage = "Player wins!";
    } else if (playerChoice === "📄" && computerChoice === "🪨") {
        gameResultMessage = "Player wins!";
    } else if (playerChoice === "✂ " && computerChoice === "📄") {
        gameResultMessage = "Player wins!";
    } else {
        gameResultMessage = "Computer wins!";
    }

}
  • The final thing our function needs to do is add our gameResultMessage to the page. We do this by making it the textContent of the gameResultMessageElement. We can also stick the string “Refresh to play again!” on the end of our gameResultMessage so users of our app know how to play another game.
function determineGameWinner() {
    ...

    if (playerChoice === computerChoice) {
        gameResultMessage = "It's a tie!";
        // Note the extra space in the scissors emoji!
    } else if (playerChoice === "🪨" && computerChoice === "✂ ") {
        gameResultMessage = "Player wins!";
    } else if (playerChoice === "📄" && computerChoice === "🪨") {
        gameResultMessage = "Player wins!";
    } else if (playerChoice === "✂ " && computerChoice === "📄") {
        gameResultMessage = "Player wins!";
    } else {
        gameResultMessage = "Computer wins!";
    }

    gameResultMessageElement.textContent = gameResultMessage + " Refresh to play again!";
}
  • As the final step, we’ll call our determineGameWinner() function in handlePlayerChoice() after all of the other function code has run:
function handlePlayerChoice(event) {
    if (!event.target.classList.contains("emoji")) return;
    playerChoice = event.target.textContent;
    playerChoiceContainer.innerHTML = `<p class="emoji">${playerChoice}</p>`;
    clearInterval(shuffleIntervalID);
    determineGameWinner();
}

Step 6 Output

rock paper scissors step 6

Your game is complete! 

Check out the finished project.

rock paper scissors complete game

Download the project files and open app.js to view the completed project code.

Add this fun game to your portfolio and show it off to family and friends. You can even customize the code to be your own version of Rock, Paper, Scissors with new rules and design.

Download JavaScript Projects Source Code

If you want to get the code behind 7 different JavaScript projects, download the full source code for free. You can use this code as an example to add to or inspire new projects. Enter your email below:

If you want to code more websites and games in JavaScript, join CodeWizardsHQ’s live coding classes for kids. It’s the most fun and effective way for kids to learn JavaScript and other real-world languages. 

Students in all of our core programming tracks study JavaScript because of its importance in web development and beyond. They work with a live, expert instructor who supports them every step of the way. Classes are engaging and you’ll build a portfolio of websites, games, and apps as you learn.

The post JavaScript Tutorial for Kids: Rock, Paper, Scissors appeared first on CodeWizardsHQ.

]]>
Simple Scratch Tutorial for Kids: Code a Rocket Landing Game https://www.codewizardshq.com/scratch-tutorial-for-kids/ Fri, 14 Oct 2022 23:29:00 +0000 https://www.codewizardshq.com/?p=52212 Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Scratch is one of the easiest and most fun ways to get started with learning to code. Kids can easily experiment in Scratch’s drag-and-drop platform or take a Scratch coding class to build their skills. Try this simple Scratch tutorial for kids for an introduction to coding in Scratch. Complete this Scratch tutorial for kids to […]

The post Simple Scratch Tutorial for Kids: Code a Rocket Landing Game appeared first on CodeWizardsHQ.

]]>
Online coding academy for kids and teens ages 8-18. Enroll to learn real-world programming languages like Python, Java, HTML/CSS, JavaScript, and more!

Scratch is one of the easiest and most fun ways to get started with learning to code. Kids can easily experiment in Scratch’s drag-and-drop platform or take a Scratch coding class to build their skills. Try this simple Scratch tutorial for kids for an introduction to coding in Scratch.

📌 [Download] Printable Scratch Coding Tutorials Get 2 printable Scratch tutorials, Rocket Landing and Flying Space Cat, to code your own games step by step. Download Now

Complete this Scratch tutorial for kids to build a Rocket Landing game.

Complete rocket landing scratch tutorial

Play and remix the Rocket Landing game now. Safely land your rocketship on the platform to win.

What you need:

  1. Scratch account: Create a free Scratch account

No coding experience is necessary for this Scratch tutorial. Beginner-friendly for kids ages 8 and up. Give it a try!

Scratch Tutorial: Rocket Landing Video Tutorial

Step 1: Create a new Scratch project

Let’s start by creating a new project. 

Visit https://scratch.mit.edu/, login to your account, and click on the “Create” button.

Scratch tutorial step 1

Now, we can code your Rocket Landing game! 

Hint: You can also remix this project and others to see the code.

X, Y positioning in Scratch

Before we move on, let’s talk about x and y coordinates. In Scratch, your images are called sprites.

Scratch uses x, y coordinates to position sprites on the screen. You might have seen these in math class. 

  • x coordinate – a number of pixels along the horizontal axis of a display starting from the pixel (pixel 0) in the center of the screen.  
  • y coordinate – a number of pixels along the vertical axis of a display starting from the pixel (pixel 0) in the center of the screen. 

We’ll use these (x, y) coordinates to position our sprites and change these coordinates to move them.

Scratch xy position coordinates

Step 2: Add a space backdrop

A new project will open up and you will see the Scratch interface. 

  • Start by deleting the Scratch cat sprite that appears in every new project. Click on the cat sprite and the trash can icon.
  • Click the “Choose a Backdrop” icon and add the “Space” backdrop.

Hint: Get creative! Choose any backdrop you want from the library or upload your own.

Scratch tutorial add a space backdrop

Step 3: Add a Rocketship sprite

Let’s create our player sprite by choosing the rocketship.

  • Select “Choose a Sprite”, find the Rocketship sprite, and click to add it
  • In the “Costumes” tab select costume 5
  • Decrease the size of your Rocketship to 50

In order to run our code in Scratch, use the “When Green Flag Clicked” block to get started.

  • Click on the “Code” tab
  • Add the “When Green Flag Clicked” block from the “Events” category
  • Position your rocketship at the top of the screen using a “Go to” block
  • Now, click on the green flag to position your sprite
Scratch tutorial add rocketship
Add a space backdrop gif

Hint: You can also upload your own Spaceship or use the “Paint” option to draw one.

Step 4: Move the Rocketship sprite 

To move our rocketship right and left using arrows, we will use “Events” blocks.

  • Add the “When space key pressed” block and change the dropdown to “left arrow”
  • Underneath that, add a “Change x by” block and use -5 to move left
  • Next, add the “When space key pressed” lock and change the dropdown to “right arrow”
  • Underneath that, add a “Change x by” block and use 5 to move right
Scratch tutorial move rocketship

We also want our rocketship to move down towards the platform. 

  • Add another “When Green Flag Clicked” block
  • Use a repeat block to repeat the downward motion of the rocketship 200 times
  • Move the rocketship down the y-axis (top to bottom) with a “Change by” block
Scratch tutorial move rocketship

Hint: Change the 5 and -5 values to move your rocketship more or less with each click

Scratch tutorial move rocketship

Step 5: Add the platform sprite and move it

Let’s create a moving platform to land our spaceship. 

  • Select “Choose a Sprite”, find the Paddle sprite, and click to add it
  • Right click on the sprite and rename it to Platform
  • Position the Platform so y = -175, at the bottom of the screen
Scratch tutorial add platform sprite

We want our platform to move randomly, so we need a variable to hold a random x value. To add code, go to the “Code” tab.

  • Go to Variable blocks and right click on the orange variable circle and rename it “New-X”
  • Add the “When Green Flag Clicked” block
  • Use a forever loop to keep the platform moving
  • Inside the forever loop, set the “New-X” variable to a random number between -240 and 240
  • Use a “Glide” block and use the “New-X” value for x and -175 for y
scratch tutorial pick random location
Scratch tutorial add platform sprite

Step 6: Add “Game Over” sprite

We need some text to tell us when the game is over.

  • Click on the cat icon, select “Paint” 
  • Select the rectangle option to draw a black rectangle
  • Then, select the text option and type “Game Over” in yellow on top of the rectangle
  • Right click on the sprite to rename it “Game Over”

We only want this sprite to show if our rocketship reaches the bottom. Go back to the code tab to add code to this block.

  • Add the “When Green Flag Clicked” block
  • Use “Hide” block to hide the block until we need to show it

Hint: Use the text option to write any message you want when the game is over.

Scratch tutorial add game over sprite
Add game over sprite gif

Step 7: Add “You Win!” sprite

We also need some text to tell us when we’ve successfully landed.

  • Right click on the “Game Over” sprite and duplicate
  • Click on the “Costumes” tab to edit the text
  • Double click the text and type “You Win!”
  • Right click to rename this sprite “You Win”

We only want this sprite to show if our rocketship touches the platform. Since we duplicated this sprite, it should already have the code to hide the block when the green flag is clicked.

Hint: Change the color of the box and the text to personalize your message.

Scratch tutorial add you win sprite
Add you win sprite gif

Step 8: Add game logic to rocketship

Depending on where the rocketship lands, we will display a different message. We need to broadcast the information to the other sprites get the right message. 

  • Click on the Rocketship sprite
  • Underneath the “Go to” block add a forever loop
  • Inside the forever loop, add two “If-then” controls
  • If the rocketship touches the edge, use the broadcast block and create a new message called “Lose”
  • If the rocketship touches the platform block, use the broadcast block and create a new message called “Win”
Scratch tutorial add game logic
Add game logic gif

Step 9: Add game logic to “You Win!” and “Game Over”

Depending on where the rocketship lands, we will display a different message. We need to broadcast the information to the other sprites get the right message. 

  • Click on the “Game Over” sprite
  • Use a “When I receive” block and select the “Lose” message
  • When this message is received, show the message and stop all scripts
Scratch tutorial add game logic lose

Do the same thing for the “You Win!” sprite

  • Click on the “You Win!” sprite
  • Use a “When I receive” block and select the “Win” message
  • When this message is received, show the message and stop all scripts
Scratch tutorial add game logic win
Add game logic gif

Your Rocket Landing game is complete! Play Rocketship Landing game.

Click the green flag and give it a try. If you want to let other people see your project and remix it, click the “Share” button at the top. 

Complete rocket landing scratch tutorial

You can “see inside” our completed Rocketship Landing game to get a peek at the full Scratch code.

Download Free Printable Scratch Coding Tutorials PDF

Get the Rocketship Landing game and Flying Space Cat Scratch tutorials in a printable format.

More Scratch Tutorials for Kids

Get inspired and practice coding with a fun Scratch tutorial for kids.

Is Scratch programming easy?

Scratch coding is a block programming language that is really easy to learn. What makes Scratch so easy is its drag-and-drop platform. It allows kids to start learning without advanced typing skills. Even though it’s easy to use, it can teach kids important programming concepts like variables, loops, if-else statements, conditions, and more. Not only that, there is no setup that needs to be done. Kids can login and start coding Scratch games and apps right away!

How do you learn Scratch programming for kids?

There are many online resources for kids to learn how to code in Scratch. The Scratch site has a directory of Scratch tutorials or you can check out our list of fun Scratch tutorials to help you get started. There are also plenty of YouTube videos from teachers and other kids learning to code in Scratch.

If your child wants to dive deeper into Scratch, consider taking a Scratch class for kids. Students in our elementary school coding program, for ages 8-11, start learning to code with Scratch and advance to other languages like HTML/CSS, JavaScript, and Python. They’ll learn fundamental coding concepts in the Scratch platform by building fun projects and applications that they can personalize and share. From there, the possibilities are endless!

The post Simple Scratch Tutorial for Kids: Code a Rocket Landing Game appeared first on CodeWizardsHQ.

]]>