The world’s leading publication for data science, AI, and ML professionals.

Simple Fun Python Project For Halloween!

A fun trick or treat game to learn python programming in an enjoyable manner for Halloween

Photo by Łukasz Nieścioruk on Unsplash
Photo by Łukasz Nieścioruk on Unsplash

In today’s article, we will be understanding some basics of python programming with a simple but fun project. The complete code is also provided in subsequent sections of the article.

Since October 31st is celebrated as Halloween in many countries, I thought it would be a good idea to learn some python programming with a fun trick or treat game that I made up.

Before we discuss more on the problem statement and the simple fun game we will be building today, let us understand some of the basic objectives that we will be trying to achieve in this article and what you can expect.

The below gif represents one part of our project that will be a small race between two turtles that we will build in this project

Screenshot By Author
Screenshot By Author

The article aims to achieve a better understanding of functions and learning to program while enjoying building a simple project. We will be using some cool libraries like the turtle module and the Google text to speech module for the construction of this project and gain more knowledge regarding these libraries.

Don’t worry if you don’t know about these as I will be touching on all the basic requirements in a briefly detailed manner for the complete understanding of this project.


Problem Statement:

You give the user a chance to pick an option – Trick or Treat. If the choice is to treat, then you just show a single turtle hit the finish line, and you are awarded a cookie for winning. The image, as well as the voice recording, needs to suggest the reward for the victory. If the choice selected is a trick, then the user gets to place a bet on the two turtles available. So the user has a 50% chance to win a reward of a cake else he gets no reward.

If you want to make the problem statement a bit more complicated, then you can also add this extra line.

An Additional else case of rock, paper, scissor game can also be added to provide the user with a higher chance to win the game if they lose the first 50% chance.


Approach:

The approach to this problem will be quite simple. We will be using two functions, namely trick() and treat(). We will be providing the user an input choice to pick either the safe treat() and win a cookie or the option to win a bigger reward of a cake by going for the trick() option.

Upon choosing the treat() option, we will have one turtle that will run on the turtle graphics window and retrieve the reward for the user. This option will be a no-risk choice that the user can make and get a cookie as a reward. However, if the user wants a bigger reward and wants to take some risk, then we have the trick() choice available.

The trick() choice will allow the user to pick between two turtles, namely red or blue. Whichever turtle you place your bet on will be the choice you select. If the turtle you selected wins the race, then you are rewarded with a cake. But if the turtle you have selected does not win, then you are given no reward. (An alternate to this is the rock, paper, scissor game that I suggested earlier for giving the users another chance.)

Whenever you win, either a cookie or a cake, the image is displayed accordingly as well, and also you get a vocal response from the computer stating that you have successfully won the game. You can have an alternate response as well for a failure case.


Understanding the modules:

import turtle
from turtle import *
from random import randint
from gtts import gTTS
from playsound import playsound
from PIL import Image
view raw modules hosted with ❤ by GitHub

The turtle module is a fun graphics module mostly used for beginner-level programmers to introduce them to the world of Python programming. The turtle module in python allows the user to draw on a graphical window as well as add some tortoises to it for building an overall enjoyable project.

I will go over the turtle module briefly in this article. I will also cover the other modules in lesser detail. The gTTS module is already covered extensively in another article, which I would highly recommend if you are just getting started with it. Firstly, I will briefly go over the simple modules.

The pillow (PIL) library imports the image function that will be used to display the images of the victory. These are the images of cookies and cakes that will be displayed as a reward. You can also make use of the open-cv module for this purpose if you want.

The playsound module is used to play the voice recordings that will be saved by the gTTS module. You can also use the OS module in python to do the same task, and it is preferred if you are having difficulties installing the playsound module. However, I don’t like an additional VLC or default media player opening when I try to play the sound, which is why I use the playsound module.

The random module is used for generating numbers in a given range randomly. Only that much information about the random module will suffice for this project. However, I would highly recommend checking out the guide to proportional sampling for learning more details about this module.

Step By Step Guide: Proportional Sampling For Data Science With Python!

Since I have not covered the turtle module anywhere else, that is exactly what I will doing very briefly in this article. Don’t worry, it will only be a few things that you need to know. I will only go over the essentials required for this project. You are free to learn more from the official documentation.

Quick Guide to Commands Required for Turtle module for this project:

1. Move and draw commands:

  • forward() – Move the turtle forward by the specified distance, in the direction the turtle is headed.
  • backward() – Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle’s heading.
  • right() – Turn turtle right by angle units. (Units are by default degrees).
  • left() – Turn turtle left by angle units.

2. Drawing state:

  • penup() – Pull the pen up i.e. no drawing when moving.
  • pendown() – Pull the pen down i.e. draw while moving.
  • write() – Write text according to the string representation of ‘arg’ at the current turtle position according to align ("left", "center" or right") and with the given font.
  • exitonclick() – Bind bye() method to mouse clicks on the Screen.

3. Color:

  • color() – Give a specific color to your turtle .
  • pencolor() – Give a specific color to the pen that draws.

Finally, we will Move over to the final Google Text-to-Speech module required for this project.

The text-to-speech (TTS) is the process of converting words into an audio form. The program, tool, or software takes an input text from the user, and using methods of natural language processing, understands the linguistics of the language used, and performs logical inference on the data.

This processed text passes into the next block, where digital signal processing becomes performed on the processed text data. With the use of many algorithms and transformations, this processed text is finally converted into a speech format. This entire process involves the synthesizing of speech. Below is the link to the following article explaining the same.

How to get started with Google Text-to-Speech using Python

Python offers a wide range of library modules and frameworks, making it one of the most compatible languages for constructing machine learning models and working on data science projects. The article aims to provide some cool modules to utilize for your machine learning and data science projects apart from the standard libraries that are used. I would highly recommend all of you to check it out if you are interested in learning more about other modules.

5+ Unique Python Modules For Creating Machine Learning and Data Science Projects That Stand out!


Procedure:

My code will have two functions. I will utilize the first function for Coding all the ideas related to the treat() option. The second function will be coded completely for all the ideas related to the trick choice.

The treat function is fairly simple to create. We will just draw a simple race track where a single red turtle will run the race and fetch the reward of chocolate for the owner. This can be done from the code block below:

def treat():
speed(0)
penup()
goto(-140, 140)
for step in range(15):
write(step, align='center')
right(90)
for num in range(8):
penup()
forward(10)
pendown()
forward(10)
penup()
backward(160)
left(90)
forward(20)
turtle1 = Turtle()
turtle1.color('red')
turtle1.shape('turtle')
turtle1.penup()
turtle1.goto(-160, 50)
turtle1.pendown()
for turn in range(100):
x = randint(1,5)
turtle1.forward(x)
turtle.exitonclick()
tts = gTTS("Congratulations On Your Cookies!")
tts.save("1.mp3")
playsound("1.mp3")
img = Image.open("Cookies.jpg")
img.show()
view raw treat hosted with ❤ by GitHub

Observe the above code block and try to interpret what is exactly happening here. We are drawing a race track for our turtle and defining set parameters so that the race track built is in the center of the graphical window screen. The position placement of the red turtle is at the center of the race track.

Once the turtle finishes the race, you are prompted to click on the screen to end the running of the graphical window interface. As soon as you click the screen, you will receive an audio response congratulating you on your reward as well as display an image of a cookie that you won.

Below is the image of the cookie that will be displayed for this project. I have renamed this as "Cookies.jpg" in my code block. If you want to run the same program, then you should consider doing so as well.

Photo by Mae Mu on Unsplash
Photo by Mae Mu on Unsplash

Let us similarly program the next trick() function.

The trick() function will have one parameter, which is the option that the user picks. The default color is given as red, but the user is free to choose the red or blue turtle, as per the user’s convivence.

Below is the entire code block for the implementation of the trick function.

def trick(pick="red"):
speed(0)
penup()
goto(-140, 140)
for step in range(15):
write(step, align='center')
right(90)
for num in range(8):
penup()
forward(10)
pendown()
forward(10)
penup()
backward(160)
left(90)
forward(20)
turtle1 = Turtle()
turtle1.color('red')
turtle1.shape('turtle')
turtle1.penup()
turtle1.goto(-160, 100)
turtle1.pendown()
for turn in range(10):
turtle1.right(36)
turtle2 = Turtle()
turtle2.color('blue')
turtle2.shape('turtle')
turtle2.penup()
turtle2.goto(-160, 40)
turtle2.pendown()
total_x = 0
total_y = 0
for turn in range(100):
x = randint(1,5)
y = randint(1,5)
total_x += x
total_y += y
turtle1.forward(x)
turtle2.forward(y)
turtle.exitonclick()
print(total_x, total_y)
if pick == "red" and total_x > total_y:
tts = gTTS("Your Turtle Won! Congratulations On Your Cake!")
tts.save("2.mp3")
playsound("2.mp3")
img = Image.open("Cake.jpg")
img.show()
elif pick == "blue" and total_y>total_x:
tts = gTTS("Your Turtle Won! Congratulations On Your Cake!")
tts.save("2.mp3")
playsound("2.mp3")
img = Image.open("Cake.jpg")
img.show()
else:
pass
view raw trick hosted with ❤ by GitHub

The trick() function is similar to the treat() function. The main difference is the use of two turtles instead of a single one. We are drawing a race track for our turtles and defining set parameters so that the race track built is in the center of the graphical window screen. The position placement of the red and blue turtles has been placed nearby the center of the race track.

The race stops when one of the turtles crosses the finish line. The victorious turtle will be the first to cross the finish line. We will calculate the total distance traveled by each of the turtles, and whichever has traveled a longer distance will win the race.

I will perform a test run on the above code now. My pick for the turtle is "red."

Let the race begin!

Screenshot By Author
Screenshot By Author

The calculations show that red has clearly won the race, and hence since the option I selected was also red, then the reward of the cake is also presented to me!

The below image with a congratulation audio response message is given to the user for this victory case.

Photo by David Holifield on Unsplash
Photo by David Holifield on Unsplash

The final code block for the implantation of this project is the choice option that is to be given to the users.

The first choice is for the trick or treat option. If the trick option is chosen, then the user has two options. They can either pick the red or blue turtle accordingly.

Below is the code block for this implementation along with a sample output.

print('''
Make Your Numerical Choice:
1. Trick
2. Treat
''')
choice = int(input(" "))
if choice == 1:
str1 = input("Enter red or blue: ")
trick(str1)
if choice == 2:
treat()
view raw choice hosted with ❤ by GitHub
Make Your Numerical Choice: 
1. Trick
2. Treat

 1
Enter red or blue: red
307 298

The sample output shown above is one of the runs where the user chooses option 1. The first option is the trick() function, which then prompts you to select a turtle of your choice. The respective output is displayed for the winning turtle, as previously mentioned.

Let us understand some of the further improvements that can be made to this simple project.


Further Improvements:

The project shown in this article is a very basic and starter project. There are tons of improvements that can be made to this trick or treat project. To mention a few of the improvements that will help in making the project way more cool and innovative are as follows:

  1. As suggested earlier, you are free to experiment with the else case. You can add a variety of options like another game of your choice or just add an extra command, which states a rejection.
  2. I would highly recommend trying out variations of the projects with other modules like pygame or Tkinter to make it more graphically and visually appealing to the audience.
  3. Another suggestion for a more advanced approach would be to work on the construction of deep learning or reinforcement learning models for achieving better results.
  4. Renovating the project and adding your own ideas to make it more complex and interesting.
  5. Deployment of the project to make sure it reaches a wider range of audiences.

Photo by Riccardo Chiarini on Unsplash
Photo by Riccardo Chiarini on Unsplash

Conclusion:

The best way to learn to program is by enjoying and appreciating the beauty of it. We developed a simple trick or treat game by understanding some of the modules required for this task as well as understood a bit more about functions.

The approach and analysis that I have used for this project are quite straightforward and elementary. It is made in an intuitive manner to understand the basics of building this simple game.

One of the best methods to become more efficient in a Programming language is by adapting and building more games. You learn newer concepts while having fun at the same time. So that is a win-win!

Check out some of these other articles that might be useful for your programming journey!

Understanding Advanced Functions In Python With Codes And Examples!

10 Step Ultimate Guide For Machine Learning And Data Science Projects!

10 Most Popular Programming Languages For 2020 and Beyond

Thank you all for sticking on till the end. I hope you guys enjoyed reading this article. I wish you all have a wonderful day ahead!


Related Articles

Some areas of this page may shift around if you resize the browser window. Be sure to check heading and document order.