antiloquax
Posts: 406
Joined: Sun Nov 20, 2011 11:37 am
Contact: Website

Re: Getting stuck in to Python

Wed Apr 18, 2012 6:39 pm

Here"s a little game to have a play with.

Press the right arrow key to shoot a laser!

You"ll need these images: Laser, ship, alien, background.

And heres the code. (I"ve had to give it a .doc extension because Wordpress doesn"t allow .py. You"ll need to rename it to run it!)




# A test game

# initialise pygame
import pygame
from pygame.locals import *
pygame.init()

# set the height and width of the screen
size = [500, 250]
screen = pygame.display.set_mode(size)
screenrect = screen.get_rect()
pygame.display.set_caption("Test Game")
back = pygame.image.load("back.png").convert()
shot = pygame.image.load("shot.png").convert()
ufo = pygame.image.load("contact.png").convert_alpha()
ship = pygame.image.load("ship.png").convert_alpha()
ufos = pygame.sprite.Group()
fps = 40
# loop flag
done=False

class Blast(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = shot
        self.rect = self.image.get_rect()
        self.rect.centerx = 115
        self.rect.centery = screenrect.centery
        self.speed = 0
    def update(self):
        self.rect.centerx += self.speed

class Ufo(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = ufo
        self.rect = self.image.get_rect()
        self.rect.top = screenrect.centery
        self.rect.centerx = screenrect.right – 100
        self.y_shift = 1
        self.count = 0

    def update(self):
        if self.count < – 100:
            self.y_shift = 1
        if self.count > 50:
            self.y_shift = -1
        self.count += self.y_shift
        self.rect.centery += self.y_shift

class Craft(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = ship
        self.rect = self.image.get_rect()
        self.rect.centery = screenrect.centery
        self.rect.centerx = screenrect.left + 100

saucer = Ufo()
rocket = Craft()
fire = Blast()
ufos.add(saucer)
allsprites = pygame.sprite.RenderPlain(saucer, rocket, fire)

# create a timer
clock = pygame.time.Clock()

while done==False:
    screen.blit(back, (0,0))

    # Event Handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True # this will cause the loop to finish.

    # shoots laser missile    
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_RIGHT:
            fire.speed = 5

    # Collision detection.        
    hit = pygame.sprite.spritecollide(fire, ufos, 1)
    if len(hit) > 0:
        fire.kill()
        fire = Blast()
        allsprites.add(fire)

    if fire.rect.centerx > screenrect.right:
        fire.kill()
        fire = Blast()
        allsprites.add(fire)

    allsprites.update()
    allsprites.draw(screen)
    # set the loop to "fps" cycles per second
    clock.tick(fps)
    #  update the display
    pygame.display.flip()

# close pygame
pygame.quit()



antiloquax
Posts: 406
Joined: Sun Nov 20, 2011 11:37 am
Contact: Website

Re: Getting stuck in to Python

Wed Apr 18, 2012 7:03 pm





Here's a really simple bat and ball game. Control the bat with the mouse. Have a look at the code – maybe you can make it into a version of breakout? (You'll need to save the bat and ball images into the same folder as the code).

# bat and ball

# import the pygame library
import pygame, random
# this saves us from typing in full paths to some pygame modules.
from pygame.locals import *

# initialise the game engine
pygame.init()

# define colours
black = [  0,   0,   0]
white = [255, 255, 255]
blue =  [  0,   0, 255]
green = [  0, 255,   0]
red =   [255,   0,   0]

# set the height and width of the screen
size = width, height = 250, 200
screen = pygame.display.set_mode(size)
screenrect = screen.get_rect()

# give the window a title
pygame.display.set_caption("Bat and Ball")

# This makes the normal mouse pointer invisible in graphics window
pygame.mouse.set_visible(False)

# load images
bat = pygame.image.load("bat.png").convert()
batrect = bat.get_rect()
ball = pygame.image.load("ball.png").convert_alpha()
ballrect = ball.get_rect()

# set speed of ball
speed = [1, 1]

# puts the bat center of screen, near the bottom
batrect.center = (screenrect.centerx, (screenrect.bottom – 50))

# loop until the user clicks the close button
done=False

# create a timer to control how often the screen updates
clock = pygame.time.Clock()

# main game loop
while done==False:

# fill the screen with a colour
screen.fill(white)

# event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
# moves bat in accordance with the mouse position
position = pygame.mouse.get_pos()
batrect.centerx = position[0]

# move the ball
ballrect = ballrect.move(speed)

# collision detection
if ballrect.bottom == batrect.top:
if ballrect.left < (batrect.right -3):
if ballrect.right > (batrect.left +3):
# ballrect.bottom = (screenrect.bottom – 55)
speed[1] = -speed[1]

#check if the pi is going off screen
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0:
speed[1] = -speed[1]

# blit the images to the screen
screen.blit(bat, batrect)
screen.blit(ball, ballrect)

# set the loop to 40 cycles per second
clock.tick(100)

#  update the display
pygame.display.flip()

# close pygame
pygame.quit()

antiloquax
Posts: 406
Joined: Sun Nov 20, 2011 11:37 am
Contact: Website

Re: Getting stuck in to Python

Fri Apr 20, 2012 9:57 am

Had a play with the Bat and Ball game with my Programming Club this week.

The kids were keen to convert it into a 2-player, add sound, add scores and make a breakout version …

Good fun!


BeeryChisels
Posts: 18
Joined: Sat Apr 13, 2013 7:00 pm

Re: Getting stuck in to Python

Thu Apr 25, 2013 5:06 pm

Hello antiloquax,
This looks like a really useful jumping-off point for Rocket Raid to me! Your post says that as well as the code, I need images: laser, ship, alien, background too. Where do I get these from, please? And how do I create my own images?
What I really need is a good book about Python 3, which hopefully won't go out-of-date too quickly. Something along the lines of the old BBC User Guide, with each command on a new page with details of how it works, what it does, and syntax. Can you recommend one? Sorry to refer back to the BBC, but a) lots of people do, and b) the User Guide was brilliant.
I have typed in Bat And Ball from issue one of MagPi, and would like to change the keys that move the bat to something other than the arrow keys. So far, I have failed to find key-detection info on the Forum, and the Raspberry Pi User Guide doesn't tell me.
Regards, BeeryChisels

gordon77
Posts: 5133
Joined: Sun Aug 05, 2012 3:12 pm

Re: Getting stuck in to Python

Thu Apr 25, 2013 5:21 pm

Is this what you need to read keys ?

http://www.pygame.org/docs/ref/key.html

Return to “Python”