Python Tamagotchi – Class 2: Micro:bit

Code comes alive, 
Micro:bit Tamagotchi, 
Joy on tiny screen.

To adapt the original Tamagotchi clone implemented in Python to the micro:bit , several changes are made to accommodate the hardware limitations and provide a simplified user experience. Here are the key changes:

  • Hardware Interaction: The original Python version used console input/output for user interaction, but in the micro:bit version, we utilized the micro:bit’s buttons (A and B) and accelerometer for user input, as well as the LED matrix for visual feedback.
  • Energy and Happiness Variables: In the Python version, energy and happiness were represented as numeric variables. In the micro:bit version, they were simplified to single integers representing the energy and happiness levels, which ranged from 0 to 10.
  • Visual Feedback: The LED matrix on the micro:bit was used to provide visual feedback on the pet’s state, such as displaying happy, sad, or sleeping faces based on the energy and happiness levels.
  • Shake to Wake: The micro:bit’s accelerometer was used to detect a shaking gesture to wake the pet up from sleep mode. This feature was not present in the original Python version.
  • Button Controls: The micro:bit’s buttons (A and B) were assigned specific functions. Button A was used for feeding the pet, and Button B was used for playing with the pet. These actions were not interactive in the original Python version.
  • Simplified Logic: The game logic was simplified in the micro:bit version. The pet’s energy and happiness levels decreased gradually over time, and there was no aging or complex health mechanics. The focus was on basic care and interaction with the pet.
  • Real-time Interactions: In the micro:bit version, the interactions with the pet were immediate, allowing the user to see the visual feedback and changes in energy and happiness levels instantly.

To summarise, the adaptation to the micro:bit hardware involved simplifying the variables, streamlining the game logic, and utilizing the micro:bit’s buttons, accelerometer, and LED matrix for user interaction and visual feedback. The goal was to provide a more concise and engaging experience tailored to the capabilities of the micro:bit platform.

User Guide

Here’s a user guide for a young person on how to load the code to the micro:bit and how to play the game:

Part 1: Loading the Code to the micro:bit

  1. Connect the micro:bit to your computer using a USB cable.
  2. Open a web browser and go to the micro:bit website: https://microbit.org/.
  3. Click on the “Let’s Code” button on the website.
  4. You will be taken to the micro:bit coding editor. Click on the “Create code” button.
  5. In the coding editor, you will see a blank canvas where you can write your code. Clear any existing code if present.
  6. Copy the Tamagotchi code provided into the coding editor. Make sure you copy the entire code correctly.
  7. Once you have pasted the code, click on the “Download” button to download the code onto your computer.
  8. Locate the downloaded file on your computer. It should have a “.hex” file extension.
  9. Drag and drop the downloaded “.hex” file onto the micro:bit drive that appears on your computer.
  10. The code will be transferred to the micro:bit. Wait for the transfer to complete.
  11. Safely disconnect the micro:bit from your computer.

Part 2: Playing the Game

  1. Turn on the micro:bit by pressing the power button.
  2. You will see different faces displayed on the LED matrix. These faces represent the state of your Tamagotchi pet.
  3. If you see a sleep face, it means your pet is asleep and needs to be woken up. Shake the micro:bit gently to wake up your pet.
  4. Once your pet is awake, you will see different faces depending on its happiness level.
  5. To feed your pet, press the button labeled “A”. This will increase the energy and happiness of your pet.
  6. To play with your pet, press the button labeled “B”. This will increase the happiness of your pet.
  7. Your pet will gradually lose energy and happiness over time, so make sure to keep an eye on their levels.
  8. If the energy level reaches 0, your pet will fall asleep again. Shake the micro:bit to wake them up.
  9. Take care of your pet by feeding and playing with them to keep them happy and energized.
  10. Enjoy playing with your Tamagotchi pet and see how well you can take care of them!

Remember to take breaks and have fun while playing with your micro:bit Tamagotchi.

The Code

# Tamagotchi Micro:bit Code
# Import necessary modules from the microbit library
from microbit import *
# Define constants for LED matrix icons
happy_face = Image("00000:"
                   "00000:"
                   "09090:"
                   "50005:"
                   "05550")
sad_face = Image("00000:"
                 "00000:"
                 "09090:"
                 "05550:"
                 "50005")
sleep_face = Image("00000:"
                   "00000:"
                   "05050:"
                   "00000:"
                   "55555")
# Initial state variables
energy = 10
happiness = 5
asleep = True
# Function to check if the micro:bit was shaken
def was_shaken():
    return accelerometer.was_gesture("shake")
# Main loop
while True:
    # Check if the micro:bit was shaken to wake up the pet
    if asleep and was_shaken():
        energy = min(10, energy + 2)
        asleep = False
    # Update LED matrix display based on pet state
    if asleep:
        display.show(sleep_face)
    elif happiness > 3:
        display.show(happy_face)
    else:
        display.show(sad_face)
    # Display energy level using the LED matrix (top row)
    energy_level = min(int(energy / 2), 5)
    for x in range(5):
        if x < energy_level:
            display.set_pixel(x, 0, 5)
        else:
            display.set_pixel(x, 0, 0)
    # Button A (Feed)
    if button_a.was_pressed():
        if not asleep:
            energy = min(10, energy + 2)
            happiness = min(5, happiness + 1)
    # Button B (Play)
    if button_b.was_pressed():
        if not asleep:
            happiness = min(5, happiness + 2)
    # Pet loses energy and happiness over time
    if not asleep:
        energy -= 0.1
        happiness -= 0.1
    # Check if the pet should fall asleep
    if energy <= 0:
        asleep = True
    # Pause for a short time to prevent rapid button presses
    sleep(100)

This code implements a simple Tamagotchi-like game on the micro:bit device.

Here’s a summary of the code’s functionality:

  • The code initializes the state variables for energy, happiness, and the asleep status of the pet.
  • The was_shaken() function checks if the micro:bit was shaken by using the accelerometer’s “shake” gesture.
  • Inside the main loop, it checks if the pet is asleep and if the micro:bit was shaken to wake it up. If so, it increases the energy level and sets the asleep status to False.
  • It updates the LED matrix display based on the pet’s state, showing the sleep face if asleep, happy face if happiness is high, and sad face if happiness is low.
  • The energy level is represented by a decreasing indicator on the top row of the LED matrix, where the brightness decreases from left to right based on the energy level.
  • Button A is used for feeding the pet, increasing energy and happiness if the pet is not asleep.
  • Button B is used for playing with the pet, increasing happiness if the pet is not asleep.
  • The pet gradually loses energy and happiness over time.
  • If the energy level reaches 0, the pet falls asleep.
  • A short delay is included to prevent rapid button presses.

Tips

Here are some tips to keep your micro:bit Tamagotchi pet alive and well:

  1. Feed Regularly: Make sure to press the “A” button to feed your pet regularly. This will increase their energy level and keep them active.
  2. Play Often: Press the “B” button to play with your pet frequently. Playing will boost their happiness and overall well-being.
  3. Monitor Energy Level: Keep an eye on the energy level displayed on the LED matrix. If it starts to decrease, it’s a sign that your pet needs to be fed or played with to replenish their energy.
  4. Avoid Neglect: If you neglect your pet for too long, their energy level will reach zero, and they will fall asleep. Shake the micro:bit gently to wake them up and make sure to attend to their needs promptly.
  5. Balance Feeding and Playing: Find a balance between feeding and playing with your pet. Providing them with both food and entertainment will contribute to their overall health and happiness.
  6. Check Happiness Level: The happiness level of your pet is crucial for their well-being. If you notice the happiness level dropping, spend some extra time playing with them to boost their spirits.
  7. Shake to Wake: If your pet falls asleep, gently shake the micro:bit to wake them up. Remember, they need your attention and care to stay active and happy.
  8. Take Breaks: While it’s essential to take care of your virtual pet, don’t forget to take breaks yourself. Set aside specific playtime intervals throughout the day to interact with your pet, and give yourself some time for other activities.
  9. Experiment and Explore: Don’t be afraid to try different actions and see how they affect your pet. Observe their responses and learn what makes them the happiest.
  10. Have Fun: The most important tip is to have fun and enjoy the experience of taking care of your micro:bit Tamagotchi pet. It’s a game meant to bring joy and entertainment, so make the most of it and create memorable moments with your virtual companion!

Remember, the key to keeping your micro:bit Tamagotchi alive is to provide them with love, attention, and regular care. Enjoy the journey of nurturing your virtual pet and see how well you can keep them happy and thriving.

So Sad:

Notes on re-coding for the micro:bit

If you have a micro:bit and want to port the code to it, you’ll need to consider the differences in hardware and programming environment. The micro:bit uses a different programming language and has a different set of capabilities compared to a mobile app. Here’s an overview of the steps you can follow to port the code:

  1. Understand the micro:bit Platform: Familiarize yourself with the micro:bit hardware and its features. The micro:bit has an LED matrix, buttons, sensors, and other built-in components that you can leverage to create the user experience.
  2. Choose a Programming Language: The micro:bit supports multiple programming languages. The most popular ones are Python, JavaScript (MakeCode), and MicroPython. Select the language you’re most comfortable with or interested in learning.
  3. Adapt the Code Logic: Review your existing code and identify the parts that are specific to the mobile app platform. Rewrite or modify those sections to work with the micro:bit’s hardware and programming language. Consider how you’ll represent the visual state, interact with the LED matrix, and handle user input using buttons or other sensors.
  4. Implement Micro:bit-specific Functionality: Utilize micro:bit libraries and APIs to access the hardware features. For example, you can use the LED matrix functions to display the state and status, use button events for user interactions, and leverage the sensors for various game mechanics.
  5. Test and Iterate: Test the ported code on the micro:bit to ensure it functions as expected. Make adjustments as necessary and iterate on the code until you achieve the desired behavior.
  6. Optimize Performance: The micro:bit has limited resources, so consider optimizing your code for memory usage and performance. Minimize unnecessary computations and reduce memory footprint where possible.
  7. Document and Share: Document your code, including any modifications made for the micro:bit platform. Share your work with others who may be interested in using or learning from it. Consider contributing to micro:bit community resources or forums to help others with similar projects.

Remember to refer to the micro:bit documentation and resources specific to your chosen programming language for detailed instructions and examples.

Additionally, you may find micro:bit project tutorials and code samples online that can provide insights into leveraging its hardware capabilities effectively.

micro:bit Architecture

From an architecture perspective, the micro:bit is a small, programmable computer designed to introduce and educate students and beginners to the world of electronics, coding, and physical computing. It provides a simplified platform for creating interactive projects and learning about computational thinking.

The architecture of the micro:bit consists of several key components that work together to enable its functionality:

  • Processor: At the heart of the micro:bit is a microcontroller unit (MCU) based on the ARM Cortex-M0 architecture. This low-power, 32-bit processor is responsible for executing the code and controlling the behavior of the micro:bit.
  • Input/Output (I/O) Pins: The micro:bit features a set of I/O pins, both digital and analog, which allow users to connect various external components such as sensors, LEDs, buttons, and motors. These pins provide the means for input and output interactions between the micro:bit and the physical world.
  • LED Matrix: One of the most distinctive features of the micro:bit is its 5×5 LED matrix. This matrix consists of 25 individually addressable LEDs, allowing users to display simple graphics, text, and animations. It serves as a visual output for the micro:bit’s programs.
  • Sensors: The micro:bit includes several built-in sensors that enable it to gather input from the environment. These sensors typically include an accelerometer, which detects motion and orientation changes, and a magnetometer, which can sense the presence of magnetic fields. Some variants of the micro:bit may also feature additional sensors like a temperature sensor or a light sensor.
  • Wireless Connectivity: The micro:bit is equipped with a radio module that supports Bluetooth Low Energy (BLE) communication. This wireless capability enables communication between multiple micro:bits or with other devices such as smartphones, tablets, or computers. It allows for the creation of interactive projects and the exchange of data between different devices.
  • Power and Programming: The micro:bit can be powered by a USB connection or an external battery pack. It can be programmed using various programming languages and development environments, including the block-based programming language MakeCode and the text-based programming language Python. The code is typically written on a computer and transferred to the micro:bit via USB or wirelessly.

Overall, the architecture of the micro:bit combines a compact form factor, a simple user interface, and a range of built-in components to provide an accessible and versatile platform for learning and experimentation in the fields of coding, electronics, and physical computing.

The micro:bit is a fantastic educational tool that provides an excellent platform for learning electronics, coding, and physical computing.

Here’s a review of the micro:bit:

Pros:

  • Educational Value: The micro:bit is specifically designed for educational purposes, making it an ideal tool for students and beginners. It introduces programming concepts in a visual and interactive manner, promoting computational thinking and problem-solving skills.
  • Ease of Use: The micro:bit is user-friendly, with a straightforward interface and programming environments like MakeCode and Python. Its block-based programming language allows users to easily create programs by dragging and dropping code blocks, while the text-based programming option caters to those looking for more advanced coding.
  • Versatility: Despite its small size, the micro:bit offers a surprising range of capabilities. It has built-in sensors like an accelerometer and magnetometer, allowing for projects involving motion detection, orientation sensing, and more. The LED matrix provides visual output, and the I/O pins enable connections with external components.
  • Connectivity: The micro:bit’s Bluetooth Low Energy (BLE) capability enables wireless communication with other devices, fostering collaboration and enabling interactions between multiple micro:bits or with smartphones, tablets, or computers. This feature enhances the learning experience and expands project possibilities.
  • Open Source: The micro:bit is an open-source platform, which means the hardware and software designs are available to the public. This openness promotes creativity, innovation, and community collaboration, allowing users to customize and extend the functionality of the micro:bit.

Cons:

  • Limited Resources: Due to its compact size and educational focus, the micro:bit has limited resources compared to more powerful development boards or microcontrollers. Its memory and processing power may restrict the complexity of projects that can be implemented. However, this limitation is necessary to maintain affordability and simplicity.
  • Lack of Advanced Features: While the micro:bit is an excellent tool for beginners, it may not be suitable for advanced users or those seeking to tackle more complex projects. Its simplicity and focus on education mean that it may not offer the same level of sophistication and features as other development platforms.
  • Fragility: The micro:bit, being a small and lightweight device, may be prone to physical damage if not handled with care. The exposed components, such as the LED matrix, can be vulnerable to impact or rough handling. However, using a protective case or cover can help mitigate this issue.

Overall, the micro:bit is an exceptional tool for introducing students and beginners to the world of electronics and coding.

Its educational focus, ease of use, versatility, and connectivity make it an excellent choice for learning and exploring the fundamentals of programming and physical computing.