Menu
CoddyTech

Whole and Half Numbers

Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 9 of 32.

Python has two kinds of number. An int is a whole number: 3, -40, 640. A float has a decimal point: 0.5, 2.0, 107.25.

One pixel a frame is 60 pixels a second. To move slower, add a float:

moon_x = moon_x + 0.5

Now moon_x goes 100, 100.5, 101.0, 101.5. pygame draws at whole pixels, so the moon moves one pixel every second frame: a slow drift, 30 pixels a second.

An int plus a float gives a float, and a float always shows its decimal point, such as 101.0. int() turns a float into an int by dropping what is after the point:

int(101.5)   # 101
challenge icon

Challenge

Medium

Make the moon drift slowly:

  1. In the change part, add 0.5 to moon_x on every frame.
  2. Show the label as a whole number: f"Moon x: {int(moon_x)}".

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()

# Set things up here, before the game loop.
moon_x = 100
moon_y = 200
font = pygame.font.Font(None, 36)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Change things here, once a frame.

    screen.fill((20, 24, 48))
    # Draw here, after the fill.
    pygame.draw.circle(screen, (240, 230, 160), (moon_x, moon_y), 50)
    text = font.render(f"Moon x: {moon_x}", True, (230, 230, 240))
    screen.blit(text, (20, 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python in a Game Window

Practice on your own: Pygame playground