Daniel Schroeder, Author at CodeWizardsHQ https://www.codewizardshq.com/author/danielj/ The leading online coding academy for kids and teens ages 8-18 Fri, 29 Aug 2025 09:34:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 https://www.codewizardshq.com/wp-content/uploads/2019/10/cropped-cropped-blueHorizontal-32x32.png Daniel Schroeder, Author at CodeWizardsHQ https://www.codewizardshq.com/author/danielj/ 32 32 Python IDE for Kids https://www.codewizardshq.com/python-ide-for-kids/ Fri, 14 Apr 2023 22:58:50 +0000 https://www.codewizardshq.com/?p=55845 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!

Programmers use a specialized text editor called an IDE (Integrated Development Environment) when writing code. At CodeWizardsHQ, our Python classes use a custom IDE that make it possible for instructors to view their students’ code. Choosing a Python IDE for kids is a mix of personal preference and performance. IDEs differ from rich text content […]

The post Python IDE for Kids 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!

Programmers use a specialized text editor called an IDE (Integrated Development Environment) when writing code. At CodeWizardsHQ, our Python classes use a custom IDE that make it possible for instructors to view their students’ code.

Choosing a Python IDE for kids is a mix of personal preference and performance. IDEs differ from rich text content authoring tools, like Microsoft Word or Google Docs. They focus solely on writing and running programs. The content’s margins, text formatting, and other presentational aspects are not the focus. 

📌 [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

IDEs instead focus on syntax highlighting, error detection, IntelliSense, and running/debugging programs, among many other features. For a new Python programmer, choosing the right IDE can be a daunting task because there are hundreds of options! In this article, we’ll cover five Python IDEs that are kid-friendly and powerful enough for professional Python programmers.

Why Learn Python? 

When learning to code, picking a programming language is often the first step in a new programmer’s journey. There are many great options, but Python is a great choice for many new programmers (especially kids). Its simple syntax, abundant learning resources, and impressive extensibility through built-in and 3rd-party libraries make it easy to learn. 

Python programs are also cross-platform (meaning they run on Windows, Mac, and Linux) by default. They are executed directly from an IDE without an intermediate compilation step (required in languages like Java, C++, or C#). Get more information on why Python is a good choice for new programmers in our Python for Kids article!

What is a Python IDE for kids?

An IDE (Integrated Development Environment) is a powerful tool that programmers use to write, edit, debug, and execute programs. There are hundreds of IDEs to choose from, varying in complexity, pricing, and language focus. 

Kids learning Python programming should focus on IDEs that are simple to use and install and allow writing and executing Python programs with ease. In addition to IDEs, there are also dedicated coding text editors for writing and editing programs. These usually have a limited feature set and often expect programmers to debug or execute their programs in another environment. 

A full-featured IDE can be better for beginning Python programmers than a text editor. That’s because all programming tasks can be performed in a single place. This article has a detailed comparison, although the conclusions differ from our opinion). Once you’ve settled on an IDE, consider practicing your skills by working through our Python Projects for Kids or Python Game Development articles!

5 Best Python IDE for Kids

Python IDE Mu

Mu

Mu is a Python IDE that makes Python programming easier for beginners. There are helpful tutorials and how-to guides which aim to answer common questions. They also help prevent common roadblocks that beginner programmers often face when learning to code with an IDE. 

The Mu team is constantly refining the IDE based on feedback from teachers and learners. So, it should be the first choice for kids looking for the easiest option to begin learning Python. 

Download Mu

Python IDE vsc

Visual Studio Code

Visual Studio Code (VS Code) is one of the most popular general-purpose IDEs for programmers from beginners to professionals. Microsoft backs the team that builds VS Code and it’s led by a core contributor to the Python programming language, so the Python experience in the IDE is top-notch. 

You can bootstrap the IDE with dedicated Python resources for an enjoyable Python programming experience. In addition to official resources, many new Python tutorials will focus on using and configuring VS Code because it’s so popular.

Download VS Code

Python IDE pycharm

PyCharm

PyCharm is a dedicated Python IDE and is an industry-standard for professional Python developers. While not as beginner-friendly as the other IDEs in this article, PyCharm can be a good choice for kids who wants to get their hands dirty with a professional development experience while learning to code. 

Get to know the IDE’s many features in the dedicated knowledge base. It’s packed with tutorials, user guides, and other content. There is a paid version, but the community edition is more than adequate for someone beginning their programming journey. 

Download PyCharm

Python IDE idle

IDLE

IDLE is an IDE packaged with the Python programming language. If you download Python on your machine (for your operating system here), you also have IDLE installed. While it is the official IDE released by Python’s maintainers, the user interface is basic, and the feature set is minimal. This lack of features means that using IDLE is easy and requires almost no additional learning beyond some basic instructions. 

Because it lacks most mainstream IDE features, IDLE probably won’t be suitable as a student progresses in their programming journey. However, it’s a fine choice for someone learning Python for the first time. The folks at Real Python have a fantastic getting-started guide for working with IDLE.

Download Python (IDLE is packaged with the language)

Python IDE replit

Replit

Replit is a free online IDE that makes authoring, editing, and collaborating on Python projects easy. Unlike the other IDEs in this article, Replit runs in your web browser, so there’s nothing to download! Since the IDE is hosted online, you can easily share and collaborate on projects with anyone worldwide. 

An account is required, but it is free to sign up (although there are upgrades for paying customers). There are helpful learning resources and documentation to explain the wealth of features Replit provides, and the team is constantly improving the IDE based on user feedback.

Features of an IDE

Most IDEs have standard features like IntelliSense, linters, formatters, code runners, and debuggers. This section will discuss these key features all IDEs share, but this is not an exhaustive list! Explore your chosen IDE’s documentation to learn about all the features they offer. 

IntelliSense

intellisense python ide

IntelliSense is like auto-complete on steroids. It will give you suggestions as you type based on the programming language and any external libraries you’re using. Most IntelliSense implementations will suggest possible functions, variables, etc. Then it will show you helpful documentation once you’ve picked the appropriate programming structure. It saves a lot of time since you don’t have to constantly jump to the documentation for a particular language or feature while writing code!

Linters

linter python ide

A linter in an IDE is akin to a spelling or grammar checker in a program like Microsoft Word or Google Docs. Linters will check that your code conforms to common standards for the language you’re working in and will point out errors or make suggestions for improvement. Some programmers prefer to leave linters on while writing code; others like to run linters periodically to check their work. No matter which method you choose, use a linter to ensure you catch bugs before running your program!

Formatters

formatters python ide

A formatter is an opinionated tool that deals with things like horizontal/vertical spacing, line length, brace/bracket placement, and other nitpicky details that affect the “look and feel” of the written code but not the program itself. Most languages have several options, and many large companies release their internal formatting standards (usually as a style guide), which programmers and programming teams adopt in their IDE’s formatter to ensure everyone follows similar patterns when writing code. If you’ve ever had to write a paper following a specific style guide (font size, font family, margins, etc.), think of formatters as performing the same role but for code.

Code Runners

code runner python ide

While writing your program, you’ll want to run it constantly. IDEs allow you to author and execute code in the same place, which is a great time-saver. It’s also possible to write your program in an IDE and run it from another source (the command line is the most common). This can sometimes be advantageous depending on the steps you want to happen as before the program is executed (for example, if you need to pass command line arguments). Depending on your IDE choice, you may need to install dedicated language packs to execute programs in various languages from the IDE’s code runner.

Debuggers

debugger python ide

A debugger allows you to set breakpoints at specific areas in your program and pause program execution to examine the state of variables or other entities in real time. Using a debugger can make bug-hunting much easier for a beginning programmer, but there is a bit of a learning curve. If you’re too intimidated to use a debugger when first learning, that’s OK! There’s always “print debugging,” where you print values in your program to ensure they hold what you expect.

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.

Python Classes for Kids

Choosing an IDE is essential to learning to program, but it’s only the first step! Once you’ve found the IDE that fits your needs, the next step is learning to program in a structured environment and practicing your skills daily. 

CodeWizardsHQ has a structured curriculum for kids ages 8-18 that exposes them to various programming languages and application development patterns. In addition to our industry-leading curriculum, we also have a feature-rich browser-based IDE which students can use to work through our curriculum and build their own projects. There are many Python courses to choose from if you’re interested in learning to program with us!

The post Python IDE for Kids 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.

]]>
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

Kids, 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.

]]>
10 Beginner Python Projects for Kids https://www.codewizardshq.com/python-projects-for-kids/ Sat, 01 Oct 2022 00:39:30 +0000 https://www.codewizardshq.com/?p=52062 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!

Building Python projects for kids is one of the best ways to solidify programming fundamentals and learn new techniques if you’re beginning your journey as a Python programmer.  In programming, as in many other disciplines, practice makes perfect. Programming is about doing and, for programmers, that means sitting at the keyboard writing code. View 10 […]

The post 10 Beginner Python Projects for Kids 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!

Building Python projects for kids is one of the best ways to solidify programming fundamentals and learn new techniques if you’re beginning your journey as a Python programmer. 

In programming, as in many other disciplines, practice makes perfect. Programming is about doing and, for programmers, that means sitting at the keyboard writing code.

View 10 Beginner Python Projects for Kids

Once you gain confidence following step-by-step tutorials to code projects, you can start to modify these projects to your liking or create projects from scratch without instructions. 

Don’t be afraid to work on projects; that’s how you’ll learn and grow as a programmer!

Fun Python Projects For Kids and Beginners

At CodeWizardsHQ, we focus on learning fundamental programming concepts through building simple projects. Our coding classes take a project-based approach (as opposed to an exercise-based one) that helps to keep kids engaged and see the practical use cases of each new programming concept as they learn them. Kids will have many projects to showcase and reference after completing each course. Using something you’ve programmed is much more satisfying than pointing to a bunch of stale exercises you finished!

If you’re hitting a roadblock on what to build, try one of these fun Python projects for kids and beginners. You’ll practice core Python skills while also creating something useful, or at least fun. These projects will get your creative juices flowing and inspire your own Python project ideas.

10 Beginner Python Projects for Kids

📌 [Download] Python Projects Source Code Get the full source code for all ten Python project examples. Download Now

1. Mad Libs

Mad Libs is a popular game where you fill in the blanks in a sentence with a type of word (verb, noun, adjective, etc.) and the sentence changes depending on which word you pick for each type. This app allows you to create the Mad Lib (or use the one we’ve provided) and prompt a user to fill in the blanks.

Mad Libs

Python project, mad libs game

Python Skills:

  • Multiline strings
  • Getting user input
  • f-strings
  • Printing data

2. Guess The Number

Working with randomness and loops is important when programming, and a “Guess The Number” app allows you to practice both concepts. In this app, you’ll ask a user to repetedly guess a number between 1 and 10 and tell them if they are too high or too low. The user can keep guessing the number until they get it right. At the end, the user is told how many turns it took them to guess the number.

Python Skills:

  • Random numbers
  • Boolean values
  • Counter-controlled repetition with for loops
  • Conditional logic
  • Incrementing a value in a variable
  • Converting user input to int

Guess The Number

Python projects, guess the number

3. Random Nickname Generator

In this project, you’ll prompt a user for their first and last names and then you’ll insert a random nickname between their first and last names. Although it sounds simple, you’ll be using many core programming concepts to get this app to work!

Python Skills:

  • Modules
  • Variables
  • Multiline strings
  • Getting user input
  • Using f-strings
  • Lists
  • Getting random values from a list

Random Nickname Generator

Python project, nickname generator

4. Quiz App

This project allows users to take a quiz to test their knowledge of different programming langauges. The number of correct/incorrect answers are tracked and the user recieves different messages depending on how well they did on the quiz.

Python Skills:

  • Dictionaries
  • Looping through dictionaries
  • Using len() to get the length of a sequence
  • Incrementing a numeric value
  • Conditional statements

Quiz App

Python projects, quiz app

5. Strong Password Generator

When browsing the internet, you’re often asked to create a user account with a strong password to protect your account from hackers. In this app, you’ll learn how to create strong, secure passwords using Python!

Python Skills:

  • The string module
  • Generating random integers
  • Creating named constants for options
  • for loops and counter-controlled repetition
  • Conditional statements
  • Building str with +=
  • Converting user input to int with int()

Strong Password Generator

Python projects, password generator

6. Python Chatbot

Chatbots are very common these days, and Python can be used to program a simple or sophisticated chatbot. The chatbot in this app will respond to a few standard commands and do things like give users a random fact and perform simple math operations.

Python Skills:

  • Conditional statements
  • Selecting random items from a list
  • Indefinite looping
  • Ending a loop with the break statement
  • str methods
  • Lists

Python Chatbot

Python project, chatbot

7. Atbash Cipher

Python is a popular language for cybersecurity professionals, and a cipher app is a good way to practice some basic cryptography skills. In this app, a user can encrypt or decrypt a phrase using the Atbash cipher, which is one of the oldest substitution ciphers in existence. 

Python Skills:

  • User-defined functions 
  • Function parameters, return values
  • Looping through a sequence with for loops
  • Complex conditional statements
  • Membership testing with the in operator
  • str methods
  • Indexing str
  • Method chaining

Atbash Cipher

python project, atabash cipher

8. Video Game Browser

Python excels at sifting through large datasets. In this app, a user can browse a large dataset of video game data and search through the data using a keyword to pull relevant results matching that keyword.

Python Skills:

  • Reading CSV files
  • Multiple assignment
  • Building a list by iterating through a sequence
  • Indefinite loops
  • Conditional statements
  • f-strings

Video Game Browser

Python project, video game browser

9. Random Dad Jokes

Everyone loves a good dad joke, right? In this app, you’ll see how Python is can be used to pull data from an external API (Application Programming Interface) and use that data to make something goofy like a random dad joke generator. 

Python Skills:

  • Requesting data from an API
  • Parsing JSON data
  • Dictionaries
  • User-defined functions
  • Indefinite loops
  • Conditional statements
  • User input

Random Dad Jokes

Python project, dad jokes

10. Current Weather App

Have you ever left the house without your umbrella, only to get covered in rain? In this app, you’ll see how Python can be used to pull weather data from an API based on a user’s current location. 

Python Skills:

  • Requesting data from an API that requires an API key
  • Parsing JSON data
  • Dictionaries
  • User-defined functions
  • Indefinite loops
  • Encoding query parameters

Current Weather App

Python project, weather app

Download Python Projects Source Code

If you want to see the source code behind these 10 Python projects, download the full code for free. These code examples are great for practicing skills you’ve learned and inspiring your own custom projects. 

What can a kid do with Python?

Python is a versatile, general-purpose programming language. You can build nearly any kind of app in Python, but the most common uses are web development, data science, AI/ML, cybersecurity, scientific computing, and automation. 

Here are some types of apps you’ll often see Python used to create:

  • Server-side logic of web applications
  • Visualizations based on large datasets
  • Using AI/ML to assist physicians as they diagnose diseases
  • Analyzing malware that hackers use to attack vulnerable users
  • Determining ancient weather patterns through analysis of climate patterns
  • Automating repetitive tasks to improve productivity

Free Python Project Resources

Due to its popularity, there are hundreds of free resources on the web for learning Python. Some are interactive and proceed in small chunks, while others are more academic-focused and go very deep into the language. Whatever your level of experience or interest, there’s something for you in the Python learning ecosystem! Here are some excellent resources for learning Python:

Kids Can Learn to Code in Python

You can learn to code Python apps like those shown above at CodeWizardsHQ. We teach Python (and HTML, CSS, JavaScript, and SQL) throughout our structured coding classes (in elementary, middle, and high school). We even have a three-course track devoted solely to learning Python if you only want to work in one programming language. 

Our online classes for Python meet weekly and are taught by a live instructor in a small group setting (typically 4 to 6 students per class). We believe everyone can be a programmer, and we’re excited to show you how much you can learn!

The post 10 Beginner Python Projects for Kids appeared first on CodeWizardsHQ.

]]>