Cara menggunakan quiz game in python

There are many ways to keep the score in a game, we will show you how to write a score onto the canvas.

First make a score component:

Example

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
  myGamePiece = new component(30, 30, "red", 10, 160);
  myScore = new component("30px", "Consolas", "black", 280, 40, "text");
  myGameArea.start();
}


The syntax for writing text on a canvas element is different from drawing a rectangle. Therefore we must call the component constructor using an additional argument, telling the constructor that this component is of type "text".

In the component constructor we test if the component is of type "text", and use the fillText method instead of the fillRect method:

Example

function component(width, height, color, x, y, type) {
  this.type = type;
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    if (this.type == "text") {
      ctx.font = this.width + " " + this.height;
      ctx.fillStyle = color;
      ctx.fillText(this.text, this.x, this.y);
    } else {
      ctx.fillStyle = color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }
  }
...
}




At last we add some code in the updateGameArea function that writes the score onto the canvas. We use the frameNo property to count the score:

Our quiz game will be asking questions to the player to which player has to reply with the right answer. Each question will have 3 attempts. If the player fails to answer the question within 3 attempts then the game will move on to the next question and the player will receive zero points. But if the player gives the right answer to the question then, he will get 1 point. At the end of the game, the total points scored by the player are displayed.

Cara menggunakan quiz game in python

I hope the abstract working of the game is clear to everyone, now let's move on to the project setup.

Project Setup

Before we start coding this project, we need some questions and answers for our game.

In our case, we are going to use some easy superhero based questions.

Feel free to use your own questions or answers for the game. Our questions and answers will be stored in a separate python file in a form of a python dictionary.

Here how it looks:

quiz = {
    1 : {
        "question" : "What is the first name of Iron Man?",
        "answer" : "Tony"
    },
    2 : {
        "question" : "Who is called the god of lightning in Avengers?",
        "answer" : "Thor"
    },
    3 : {
        "question" : "Who carries a shield of American flag theme in Avengers?",
        "answer" : "Captain America"
    },
    4 : {
        "question" : "Which avenger is green in color?",
        "answer" : "Hulk"
    },
    5 : {
        "question" : "Which avenger can change it's size?",
        "answer" : "AntMan"
    },
    6 : {
        "question" : "Which Avenger is red in color and has mind stone?",
        "answer" : "Vision"
    }
}

Enter fullscreen mode Exit fullscreen mode

You can learn more about python dictionaries from here.

We won't be able to cover much about dictionaries in this tutorial but basically it is a data structure that can be used to store data as a single, organized & easy to access form.

You can think of the dictionary as the list. But there are some key differences between lists & dictionaries:

  • Lists are enclosed within
    from questions import quiz
    
    1 parenthesis while dictionaries are enclosed in
    from questions import quiz
    
    2 brackets.
  • Individual elements of lists are accessed using
    from questions import quiz
    
    3 of the element while individual elements of dictionaries are accessed through
    from questions import quiz
    
    4 pair where
    from questions import quiz
    
    5 is the identifier and
    from questions import quiz
    
    6 is its corresponding data or value.

You must make sure that your dictionary should be in the same format as above or else you may need to make necessary changes to the code to make it work for you. Feel free to ask questions on my social handles or post your question below in discussions/comments.

Now I assume that you have your questions & answers ready. Make sure that your Q&A python file is in the same folder as your main quiz game python file which we will start coding in just a second.

Now let's jump to coding.

Let's Code

The first thing we always do is import required modules into our code. Luckily for this project, we don't need any specific module. However, we still need to import the Q&A python file we created in the previous step.

We have named our Q&A python file as

from questions import quiz
7. Here's how we will import it:

from questions import quiz

Enter fullscreen mode Exit fullscreen mode

We are asking python to import the

from questions import quiz
8 dictionary which contains our question & answers from the file
from questions import quiz
7.

Now let's get to the structure of our game...

Pay close attention! As this might feel a bit complicated...

Now we are going to initialize a variable to keep track of the score.

score = 0

Enter fullscreen mode Exit fullscreen mode

Now it's time to ask the questions to our player.

For that, we need to create an

score = 0
0 loop which will iterate through all the questions.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    pass

Enter fullscreen mode Exit fullscreen mode

Now as previously mentioned, the player will have 3 attempts for each question to get the right answer.

Let's create a variable to keep track of the attempts.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3

Enter fullscreen mode Exit fullscreen mode

Now let's create an

score = 0
1 loop within our
score = 0
0 loop, which will run only until player has attempts left.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        # this while loop will run until player has more than 0 attempts left
        while attempts > 0:
                pass

Enter fullscreen mode Exit fullscreen mode

Great! Now let's print the questions and take the response from our player. We'll use our good old

score = 0
3 &
score = 0
4 functions for that.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        while attempts > 0: 
                print(quiz[question]['question']) # this will print the current interation of for loop
        answer = input("Enter Answer: ")

Enter fullscreen mode Exit fullscreen mode

Awesome! The response of the player will be stored in the

score = 0
5 variable.

Now we will use a function which will check if the answer provided by the player is right or wrong. We will name that function as

score = 0
6. For now, let's focus on our
score = 0
0 loop and then we will see how this function works.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        while attempts > 0: 
                print(quiz[question]['question']) # this will print the current interation of for loop
        answer = input("Enter Answer: ")
                check = check_ans(question, answer, attempts, score)

Enter fullscreen mode Exit fullscreen mode

We will pass 4 parameters to our function, which are:

  • score = 0
    
    8 - the current iteration of
    score = 0
    
    0 loop
  • score = 0
    
    5 - the answer provided by player
  • # Here remember 'quiz' is our dictionary and 'question' is our temp variable
    for question in quiz:
        pass
    
    1 (optional) - an optional parameter of number of attempts left
  • # Here remember 'quiz' is our dictionary and 'question' is our temp variable
    for question in quiz:
        pass
    
    2 (optional) - an optional parameter of the current score of the player

We will store the output of our function in

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    pass
3 variable.

Now we are going to use

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    pass
4 statements to increase score if the answer provided by the player is right.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        while attempts > 0: 
                print(quiz[question]['question']) # this will print the current interation of for loop
        answer = input("Enter Answer: ")
                check = check_ans(question, answer, attempts, score)
                if check:
            score += 1
            break
        attempts -= 1

Enter fullscreen mode Exit fullscreen mode

Here if the answer given by the player is right then the score will increase by 1 and the

score = 0
1 loop will break and the
score = 0
0 loop will move on to the next question.

But if the answer is wrong, then the player will lose one attempt, and the while loop will continue until either right answer is provided by the player or player runs out of attempts.

Here finally, our

score = 0
0 loop ends!

Are we forgetting something? 🤔

Oh we forgot the implementation of our

score = 0
6 function... Let's cover that quickly!

def check_ans(question, ans, attempts, score):
    if quiz[question]['answer'].lower() == ans.lower():
        return True
    else:
        return False

Enter fullscreen mode Exit fullscreen mode

Here is our function... Let's break it down!

Here an

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    pass
4 statement will compare the answer provided by the player with the correct answer from our dictionary.

If the answer is right then it will return

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
0 or else it will return
# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
1.

Let's add a few print statements to notify the player if his answer is right or wrong.

from questions import quiz
0

Enter fullscreen mode Exit fullscreen mode

Here looks good right!

You did it! Be proud of yourself 🤩

Some Ideas to try out

Here are some quick ideas you can try with this project.

  • Make it multiplayer - Try modifying this game so that more than one player can enjoy this game at once. You can do this by simply adding an additional
    score = 0
    
    0 loop which will contain the names of the players and score of each player is stored separately. The player with the highest score will win the game.
  • Use MCQ format - Not just quiz, you can also use it conduct MCQ tests. All you have to do is modify the print function to print the multiple answers and the player will have to guess the right answer.
  • Use an API - Make use of an interesting API to automatically fetch questions from the web so you don't have to get into the hassle of creating the questions and answers on your own. One of my favorite is the Superhero API.

Source Code

You can find the complete source code of this project here -

mindninjaX/Python-Projects-for-Beginners

Support

Thank you so much for reading! I hope you found this beginner project useful.

If you like my work please consider Buying me a Coffee so that I can bring more projects, more articles for you.

Cara menggunakan quiz game in python

Also if you have any questions or doubts feel free to contact me on Twitter, LinkedIn & GitHub. Or you can also post a comment/discussion & I will try my best to help you :D