Rapid spawning in Pigama

Ok, I just started using pygame a week ago, but I think I understand the basics. My game is very simple, move the balloon left and right to dodge the incoming screws. I have successfully made a balloon left and right, but I am very unfamiliar with classes and I don't know any other way to quickly create multiple screws on the screen. Any help would be greatly appreciated.

Here is my code:

import pygame
from pygame.locals import *
import sys
import time
pygame.init()

screen = pygame.display.set_mode((600,600))
pygame.display.set_caption('Baloon Pop')


baloon_size = (70,70)

white = (255,255,255)
cyan = (0,255,255)
red = (255,0,0)

screen.fill(cyan)

baloon = pygame.image.load('/users/Gaming/Desktop/rsz_baloon.png')
screw = pygame.image.load('/users/Gaming/Desktop/rsz_screw_png3029.png')



FPS = 30
fps_time = pygame.time.Clock()

baloonX = 280
baloonY = 500

import random
screwX = random.randint(0,600)
screwY = 20

LEFT = "left"
RIGHT = "right"
movement = "down"




while True:
    screwY = screwY+10
    screen.fill(cyan)
    screen.blit(screw, (screwX,screwY))
    screen.blit(baloon, (baloonX,baloonY))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                baloonX = baloonX+30
                if baloonX >= 580:
                    baloonX = baloonX -30
            elif event.key == K_LEFT:
                baloonX = baloonX -30
                if baloonX <=-30:
                    baloonX = baloonX+30






    pygame.display.update()
    fps_time.tick(FPS)

      

+3


source to share


2 answers


First of all, I would recommend using a class to control your player. This makes drawing and collision detection easier. A simple way to do it:

class Player:

    def __init__(self, x, speed):
        self.x = x
        self.speed = speed
        self.moveright = 0
        self.moveleft = 0

    def update(self, time_passed):
        if self.moveright:
            self.x += self.speed * time_passed
        if self.moveleft:
            self.x -= self.speed * time_passed

      

Then, a similar class for controlling your enemy.

class Enemy:

    def __init__(self, x, speed):
        self.x = x
        self.y = 0
        self.speed = speed

    def update(self, time_passed):
        self.y += self.speed*time_passed

      

Here time_passed is the value of your Clock () object. the screen is your pygame.display surface.

Now that your enemy is objectified, you can create a list to hold instances of the enemy class.

As I said, using this mechanism can smooth out your game a bit. Using an increment for each KEYDOWN event is not recommended.

Create a list to hold enemy instances and instantiate the player:

Enemylist = []
Player1 = Player(<SomeXValue>,0.1)

      

Moving on to creating random enemies. If you need to create, say, a screw (i.e. Enemy ()) every n loops, you can create a flag that is activated in that interval. You may have a "count" variable that handles this. The initial value can be 0, and then increment it every cycle by 1. (Example: if you want an enemy to multiply every 5 cycles, replace n with 5.)



if count % n == 0:    
    Enemylist.append(Enemy(random.randint(0,<YourScreenSize>),0.1))
if count > 1000:
    count = 0

      

That is, spawn the enemy in a random spot on the screen and let them move down. 0.1 is just the sampling rate.

Now, into the loop section ... Your event loop must have a KEYDOWN and KEYUP key to allow single keystrokes. Here Player1 is the name of an instance of the Player class.

for event in pygame.event.get():

    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    if event.type == KEYDOWN:
        if event.key == K_RIGHT:
            Player1.moveright = 1
        if event.key == K_LEFT:
            Player1.moveleft = 1
    if event.type == KEYUP:
        if event.key == K_RIGHT:
            Player1.moveright = 0
        if event.key == K_LEFT:
            Player1.moveleft = 0

      

Add checks to keep the player from leaving the screen.

Now the player's movement fully meets the requirements of this game.

Call the update () function of the player, enemies and flip the screen.

Player1.update(time_passed)
<blit background image or color here>
screen.blit(<image_name>, (Player1.x, <PlayerYPosition>))
for enemy in Enemylist:
    enemy.update(time_passed)
    screen.blit(<image_name>, (enemy.x, enemy.y))
count += 1
pygame.display.update()

      

Now add collision checks to complete the game. In addition, you can delete instances that have exited the screen to save memory.

+1


source


To make things less complicated for your program, you will need some classes for your ball and your screws. The first class for your player will look like this, assuming you only move from left to right:

class Player(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image_file)
        self.rect = pygame.image.get_rect()
        self.rect.top, self.rect.left = location

      

This code snippet will make your balloon a sprite ready for collision detection. The class of your screws will look similar, but with additional features move

and location

and speed

in terms of __init__

class:

class Screws(pygame.sprite.Sprite):
    def __init__(self, image_file, left, speed):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image_file)
        self.rect = pygame.image.get_rect()
        self.rect.top = 50
        self.rect.left = left
        self.speed = speed

    def move(self):
        self.rect = self.rect.move(self.speed)

      

This class makes the propellers sprites that are also detectable. This completes the classes section. Now to group these sprites, etc .:

balloon = Player('/users/Gaming/Desktop/rsz_baloon.png', [a, b])     
screw = Screws('/users/Gaming/Desktop/rsz_screw_png3029.png', random.randint(0, <ScreenSize>), c)
ScrewGroup = pygame.sprite.Group()

      

And again the variables change, but the higher c

, the faster the screws will fall. a

and b

will locate the balloon and random.randint()

will locate your propellers. self.rect.top

is a way to find a location using it as the location of the top rect

. In this case, it remains the same. Same for self.rect.left

, but this is the rect

"left" side position . Now let's move on to the moving part of the balloon, to avoid excessive UP and DOWN key presses (and fatigue), add this line of code right after:

delay = 100
interval = 50
pygame.key.set_repeat(delay, interval)
on = True
screwy = 0

      

delay

is the number of milliseconds between each activated KEYDOWN, and the interval is milliseconds to wait until a repeated KEYDOWN starts. This will help the user by forcing him to simply hold the Left key on the right and the balloon will continue moving in the desired direction. The variables on

and screwy

will be discussed in the next section. Further, there is almost no while loop:

while True:
    screen.blit(balloon.image, balloon.rect)
    while int(screwy - 1) > -1:
        screen.blit(screw.image, screw.rect)
    pygame.display.flip()

      

The second loop generates as many screws as possible, the value screwy

-1 is less than -1 (negative value 1). This also flips the screen to avoid any "tracks" appearing on the screen. Now to the moving part of the balloon:



for event in pygame.event.get():
    #Remember to do this : from pygame.locals import *#
    if event.type == QUIT:
        on = False
        #Remember to import sys!#
        sys.exit()
    elif event.type == pygame.KEYDOWN:
        if event.key = K_LEFT:
            balloon.rect.left -= 30
        elif event.key == K_RIGHT:
            #This can only work if (width_of_the_picture - a) is equal to 30#
            balloon.rect.left += int(width_of_the_picture - a)

      

This will allow you to move the balloon (you can hold the key until the kepp moves around the balloon like in a real video game). The next will be to continue spawning screws:

if screwy < 10:
    ScrewGroup.append(Screws('/users/Gaming/Desktop/rsz_screw_png3029.png', random.randint(0, b), [0, 15]))
    screwy += 1

      

This will cause screws to appear in random locations (same value self.rect.top

to make it look realistic). b

in this case will be equal to the screen width. Finally, sprite detection:

if pygame.sprite.spritecollide(balloon, ScrewGroup, True):     
    on = False
    sys.exit()
    pass

      

This determines if the ball has collided with the screws. If that's true, you can decide. You can just exit the while loop and exit the program, which is one way to do it. But if you plan on doing something like print 'Game Over!

add this line before doing on = False

/ sys.exit()

which will exit the loop / program immediately. You will need to re-split the images and allow screen output ( pygame.quit

):

    screen.fill([255, 255, 255])
    screen.blit(balloon.image, balloon.rect)
    while int(screwy - 1) > -1:
        screen.blit(screw) 
    pygame.display.flip()
pygame.quit()

      

Remember to put pygame.quit()

outside of the while loop, or the screen will disappear immediately. Of course, make a code to prevent the balloon from exiting the screen. Changing the KEYDOWN section to this should do this:

elif event.type == pygame.KEYDOWN:
    if event.key == K_LEFT:
        if int(balloon.rect.left) - 30 < 0:
            pass
        elif int(balloon.rect.left) - 30 >= 0:
            balloon.rect.left -= 30
    elif event.key == K_RIGHT:
        if int(balloon.rect.left) + (<Width_OF_Balloon> - a) > <Width_OF_Screen>:
            pass
        elif int(balloon.rect.left) + (<Width_OF_Balloon> - a) <= <Width_OF_Screen>:
            #This can only work if (<Width_OF_Balloon> - a) is equal to 30#
            baloon.rect.left + (<Width_OF_Balloon> - a)

      

If moving left / right causes the balloon to partially leave the screen, the program will not allow the balloon to go left / right without doing anything with pass

. This should greatly improve your program and answer your question. Hope this helps you!

0


source







All Articles