Skip to main content

Welcome to our ‘Coin Flip Python’ tutorial! In this guide, we’ll walk you through the process of building a virtual coin tossing program using Python. With just a few lines of code, you’ll be able to simulate a coin flip and get a random ‘Heads’ or ‘Tails’ result. Let’s get started and add some randomness to your Python projects!

Loading and scaling the coin image:

# Load the coin image
coin_img = pygame.image.load('coin.png')
coin_img = pygame.transform.scale(coin_img, (100, 100))

We load the coin image from the file “coin.png” and then scale it to a size of 100×100 pixels using pygame.transform.scale() so that it fits nicely on the screen.

New variables for animation:

flip_animation = False
flip_frame = 0

We introduce two new variables: flip_animation (a boolean flag to control the animation state) and flip_frame (a counter to keep track of the animation frame).

Modifying the draw_coin function:

def draw_coin():
    screen.blit(coin_img, (coin_center[0] - coin_img.get_width() // 2, coin_center[1] - coin_img.get_height() // 2))
    font = pygame.font.SysFont(None, 30)
    text = font.render("Press 'F' to flip the coin", True, (0, 0, 0))
    screen.blit(text, (screen_width // 2 - 130, screen_height - 50))

We update the draw_coin function to draw the coin image on the screen using screen.blit(). The image is centered around the coin_center. We also display the “Press ‘F’ to flip the coin” message at the bottom of the screen.

Adding the animation to the main loop:

if flip_animation:
    flip_frame += 1
    if flip_frame >= 20:  # Change animation speed by adjusting the value here
        flip_animation = False

# Draw the coin or the flipped coin
if flip_animation:
    rotated_coin = pygame.transform.rotate(coin_img, flip_frame * 18)  # Adjust the rotation speed here
    screen.blit(rotated_coin, (coin_center[0] - rotated_coin.get_width() // 2, coin_center[1] - rotated_coin.get_height() // 2))
else:
    draw_coin()

In the main loop, we check if flip_animation is True. If it is, we start the animation by incrementing flip_frame. We limit the animation to 20 frames (you can adjust this value to control the animation speed).

The rotated coin is created using pygame.transform.rotate() with an angle based on flip_frame. We adjust the rotation speed by multiplying flip_frame with a value (18 in this case) to control the number of degrees rotated per frame.

If flip_animation is False (animation is not running), we draw the coin normally using the draw_coin() function.

With these changes, the coin will animate when you press the ‘F’ key, and the result will be displayed after the animation finishes. Feel free to tweak the animation speed, rotation angle, and other properties to get the desired effect!

The full source code for this project is available on Github.

Close Menu

Welcome to Coded Brainy

Coded Brainy Provides you with technical blogs

Coded Brainy