A game from Pope
The following code is very funny. It make you understand how easy is to use Python for almost every use, even for games. To use pygame is not so easy, but pygame zero, makes it the easier that is possible today. So, if you ever wanted to get into pygame, but you were a little discouraged by the complication that it brings, here is the change to have some fun coding with Python to make interactive stuff and very funny games. Let’s get a little deeper into Pygame zero, thanks to the talk of Daniel Pope at EuroPython conference of 2016.
Pope has made a talk to the EuroPython conference, you can see his video in the last article, and I made some changes to it to make this game. Here is the code. In the next article I’ll show you a video with the explanations, even if pygame zero is very easy to read.
#! /usr/bin/python # eatgame # Giovanni Gatto # Based on a Pope code # you don't need it to run with pgzrun name.py, but with usual python name.py import pgzrun import random WIDTH = 800 HEIGHT = 600 alien_hurt = Actor('alien', midbottom=(WIDTH // 2, HEIGHT)) alien = Actor('alien_hurt') alien.topright = 100, 10 def draw(): screen.fill('blue') alien.draw() alien_hurt.draw() xpos = random.randint(0, 800) def update(): global xpos alien.y += 5 if keyboard.left: alien.x -= 5 if keyboard.right: alien.x += 5 if alien_hurt.colliderect(alien): print('you win') alien.y = 0 xpos = random.randint(0, 800) alien.x = xpos if alien.y > 600: print("you lose") alien. y = 0 xpos = random.randint(0, 800) alien.x = xpos """ def on_mouse_down(pos): global score if alien.collidepoint(pos): set_alien_hit() score += 1 print(score) else: score -= 1 print(score) def set_alien_hit(): alien.image = 'alien_hurt' sounds.eep.play() clock.schedule_unique(set_alien_normal, 0.5) def set_alien_normal(): alien.image = "alien" pgzrun.go()
Original music by Giovanni Gatto, author of the blog.