I'm working on a little game with some fellow students and I'm wanting some guidance on how to handle the problem...
With my code what it boils down to is I want to call into use the Boss_Shoot Class where the Boss class update() starts printing "should be shooting" .. the print statement statements seen through out are nothing more then a "placeholder of sorts...
As always Thanks so much!
class Boss(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("sprites/boss.png")
self.rect = self.image.get_rect()
self.dx = 1
self.dy = 1
self.shoot= True
def update(self):
if self.rect.centerx >= 600:
self.rect.centerx -= self.dx
elif self.rect.centerx <= 600:
print "should be shooting"
self.rect.centery -= self.dy
self.checkBounds()
def checkBounds(self):
if self.rect.top <= 0:
self.dy *= -1
print
if self.rect.bottom >= 500:
self.dy *= -1
class Boss_Shoot(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((20, 20))
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect()
self.rect.center = (320, 240)
self.dy =2
def update(self):
if self.shoot == True:
print "shooting"
for i in range(100):
print "wtf man"
self.rect.x = random.randrange(1000, 3000)
self.rect.y = random. randrange(10, 490)
self.rect.x -= 5
self.rect.y +=self.dy
You need a way your actors (or Sprites, or whatever you call your "entities") can communicate with the global state of your game.
You didn't show all your code, so I assume everything is in one file.
Somewhere in your code, you probably have a list of all actors (and if you don't, you should create one). Let's assume it's defined as:
actors = []
Maybe you use a single list, maybe you want to use pygame's Group class.
I further assume you call the update() method on all actors in your mainloop, like:
for a in actors:
a.update()
(or, if you use pygame's Group class, something like mygroup.update()).
Now, in the update() method of Boss, just create a new instance of Boss_Shoot, and add it to the list of actors, like:
def update(self):
if self.rect.centerx >= 600:
self.rect.centerx -= self.dx
elif self.rect.centerx <= 600:
actors.append(Boss_Shoot())
You probably want to pass the position of Boss to the Boss_Shoot constructor so the bullet (or whatever) doesn't randomly appear on the screen (if you want to).
I prefer encapsulating the gamestate into a seperate dict or class, and pass that down to each actor so each actor can register/unregister itself from the world, something like:
class State(object):
def __init__(self):
self._actors = []
def register(self, actor):
self._actors.append(actor)
def unregister(self, actor):
self._actors.remove(actor)
def update(self):
for a in self._actors:
a.update()
...
class Boss(pygame.sprite.Sprite):
def __init__(self, state):
self.state = state
self.state.register(self)
...
def update(self):
if self.rect.centerx >= 600:
self.rect.centerx -= self.dx
elif self.rect.centerx <= 600:
self.state.register(Boss_Shoot(self.state))
class Boss_Shoot(pygame.sprite.Sprite):
def __init__(self, state):
self.state = state
self.state.register(self)
...
while True:
state.update()
state.draw(screen)
...
You'll get the idea.
Related
import pygame, sys
pygame.init()
surf = pygame.display.set_mode((1280, 720))
black = (0, 0, 0)
surf.fill(black)
fps_clock = pygame.time.Clock()
pygame.display.flip()
class Player(pygame.sprite.Sprite):
def __init__(self, name, xx, yy):
self.name = name
self.image = pygame.Surface((22, 22))
self.image.fill((130, 100, 200))
self.rect = self.image.get_rect(x = xx, y = yy)
self.x_vel = 0
self.y_vel = 0
def speed(self, speed):
self.speed = speed
def update(self, keys):
if keys[pygame.K_DOWN]:
self.y_vel = 3
elif keys[pygame.K_UP]:
self.y_vel = -3
else:
self.y_vel = 0
if keys[pygame.K_LEFT]:
self.x_vel = -3
elif keys[pygame.K_RIGHT]:
self.x_vel = 3
else:
self.x_vel = 0
self.rect.x += self.x_vel
self.rect.y += self.y_vel
def update1(self, keys):
if keys[pygame.K_s]:
self.y_vel = 3
elif keys[pygame.K_w]:
self.y_vel = -3
else:
self.y_vel = 0
if keys[pygame.K_a]:
self.x_vel = -3
elif keys[pygame.K_d]:
self.x_vel = 3
else:
self.x_vel = 0
self.rect.x += self.x_vel
self.rect.y += self.y_vel
def draw(self, surface):
surf.fill(black)
surface.blit(self.image, self.rect)
player = Player('Tank', 100, 300)
player2 = Player('Tank2', 200, 500)
def main():
while True:
keys = pygame.key.get_pressed()
player.draw(surf)
player2.draw(surf)
player.update(keys)
player2.update1(keys)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fps_clock.tick(60)
main()
Trying to create 2 sprites, one which can be controlled using the arrow keys, the other using the WASD keyset. It only blits one sprite on the image, which can be controlled using WASD. The other can be controlled by arrow keys if player2.update1(keys) is commented. Please don't beat down on me that much, still kind of a novice.
The problem is that you fill the whole screen with black before you draw each player. That means that when player two is drawn player one gets drawn over with black. Remove line 52 surf.fill(black) from def draw() and add it to the main game loop so that it is only called once.
def main():
while True:
surf.fill(black)
I am currently working on a small RPG in Pygame to get used to object oriented coding.
When looking into how to auto-update a property I came across the following:
class P:
def __init__(self,x):
self.x = x
#property
def x(self):
return self.__x
#x.setter
def x(self, x):
if x < 0:
self.__x = 0
elif x > 1000:
self.__x = 1000
else:
self.__x = x
I tried applying it to my code but I get the following error:
File "weapons.py", line 13, in __init__
self.name = '{} {}'.format(ammo, self.raw_name)
TypeError: name() takes exactly 3 arguments (2 given)
I understand what the error is but I don't get how to solve it since I need both the raw_name and the ammo attributes to auto-update my Arrow instance's name.
My class is as such:
class Projectile(Item):
def __init__(self, name, value, image, x, y, speed, dmg, dmg_modif, ammo):
super(Projectile, self).__init__(name, value, image, x, y)
self.dest = (self.rect[0],self.rect[1])
self.speed = speed
self.dmg_modif = dmg_modif
self.dmg = dmg
self.orientation = 0
self.ammo = ammo
#property
def name(self):
return self.___name
#name.setter
def name(self, raw_name, ammo):
if '{} {}'.format(raw_name,ammo) != self.___name:
self.___name = '{} {}'.format(raw_name,ammo)
The child class which returns the error is:
class Arrow(Projectile):
def __init__(self, ammo): #name, value, image, x, y, dmg
self.raw_name = 'Arrows'
self.name = '{} {}'.format(ammo, self.raw_name)
self.value = 5
self.image = variables.quiver_img
self.speed = 4
self.dmg = 2
self.dmg_modif = 1
super(Arrow, self).__init__(self.name, self.value, self.image, 200, 150, self.speed, self.dmg, self.dmg_modif, ammo)
And the parent classes are, Item and MySprite:
class Item(MySprite):
def __init__(self, name, value, image, x, y):
# Call the parent class (Sprite) constructor
super(Item, self).__init__(image, x, y)
self.name = name
self.value = value
self.inv_pos = -1
and
class MySprite(pygame.sprite.Sprite):
def __init__(self,image,x,y):
# Call the parent class (Sprite) constructor
super(MySprite, self).__init__()
self.image = image
self.rect = self.image.get_rect().move(x, y) #initial placement
self.top_cp = (self.rect[0]+self.rect[2]/2,self.rect[1])
self.bot_cp = (self.top_cp[0],self.rect[1]+self.rect[3])
self.left_cp = (self.rect[0],self.rect[1]+self.rect[3]/2)
self.right_cp = (self.left_cp[0]+self.rect[2],self.left_cp[1])
self.center = self.rect.center
self.pos = self.rect.topleft
self.blit_order = 1
self.level = variables.current_level #Level(1)#level to which sprite belongs
Any help would be welcome !
Please provide a minimal example next time.
Your code looks a little complicated. OK, the first problem is that you can't pass multiple arguments to a setter. You can either pass a tuple or just use a traditional setter method def set_name(self, name, ammo):.
Another problem is that you use the ___name attribute before it has been set, for example in the second line of the Arrows __init__ method.
Private attributes should have one underscore not three (that's just a convention to warn other programmers). If you have two or more underscores than the name gets mangled.
Also, it looks to me like you change the name in the setter only if the new name is equal to the old name (kinda pointless ;)). What do you actually want to do there? Maybe you don't need properties at all.
Here's a fixed (minimal) version of your code:
import pygame
class MySprite(pygame.sprite.Sprite):
def __init__(self):
super(MySprite, self).__init__()
class Item(MySprite):
def __init__(self, name):
super(Item, self).__init__()
self.name = name
class Projectile(Item):
def __init__(self, name):
super(Projectile, self).__init__(name)
#property
def name(self):
return self._name
#name.setter
def name(self, name):
self._name = name + ' foo'
class Arrow(Projectile):
def __init__(self):
super(Arrow, self).__init__(name='Arrows')
arrow = Arrow()
print(arrow.name)
arrow.name = 'New name'
print(arrow.name)
So I eventually managed to solve my problem:
class Projectile(object):
def __init__(self, raw_name, ammo):
self.raw_name = raw_name
self.name = self.raw_name
self.ammo = ammo
#property
def ammo(self):
return self._ammo
#ammo.setter
def ammo(self, ammo):
self.name = str(ammo) + self.raw_name
self._ammo = ammo
class Arrow(Projectile):
def __init__(self):
self.raw_name = ' Arrows'
self.name = self.raw_name
super(Arrow, self).__init__(self.raw_name, ammo
= 10)
arrow = Arrow()
print arrow.ammo
print arrow.name
arrow.ammo = 15
print arrow.ammo
print arrow.name
gives:
>>>10
>>>10 Arrows
>>>15
>>>15 Arrows
I'm trying to recreate a game, however all I need is to create a game-over feature that occurs when the player collides or fails to jump over the rock. I've tried to do the check collision yet the player is passing through. What should I do or change in order to display the game over screen when the player collides with the rock? Here is my sample code:
#--- Player Definition
class Player(pygame.sprite.Sprite):
#- Constructor
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.playing = False
self.image = pygame.image.load("bcquestchar.png")
self.rect = self.image.get_rect()
self.color = BLUE
self.rect.x = 50
self.rect.y = 210
self.goalY= 450
self.gameover = False
#- Allows Player to Jump
def jump(self):
self.goalY -= 25
#- Imports & Displays player_image
def draw(self, screen):
screen.blit(player_image, [self.rect.x, self.rect.y])
#--- Rock definition
class Rock(pygame.sprite.Sprite):
#- Constructor
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("bcrocks.png")
self.rect = self.image.get_rect()
self.rect.x = random.randrange (0, 200)
self.rect.y = 335
#- Moves Rock
def move(self):
self.rect.x -= 3
#- Imports & Displays rock_image
def draw(self, screen):
screen.blit(self.image, [self.rect.x + 700, self.rect.y])
# Loop until user closes pygame
done = False
# How fast the screen updates
clock = pygame.time.Clock()
# Creates player
rock = Rock()
player = Player()
obstacles = pygame.sprite.Group()
obstacles.add(rock)
if pygame.sprite.spritecollide(player, obstacles, False):
player.gameover = True
#----- Main Program Loop -----#
while not done:
#movesound.play()
#- Calls in draw_background function
draw_background (screen, 0, 0)
#- Tracks Events
speed = 1
#--- Main Event Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = False
#- User is playing when M1 is clicked
elif event.type == pygame.MOUSEBUTTONDOWN:
player.playing = True
#- User jumps when playing and has not lost
if(player.gameover == False and player.playing == True):
player.jump()
#- Is the player playing?
if(player.playing == True):
# Jump up when the up arrow is pressed
if event.type == pygame.MOUSEBUTTONDOWN:
currently_jumping = True
going_up = True
#hopsound.play()
if currently_jumping == True:
if player.rect.y < 188:
going_up = False
elif going_up == False and player.rect.y > 215:
currently_jumping = False
if going_up:
player.rect.y -= 2
elif going_up == False:
player.rect.y += 2
elif currently_jumping == False:
if(player.rect.y > 600 or player.rect.y < 0):
player.gameover = True
if(player.rect.y < 210):#player.goalY):
player_moving_up = False
elif(player.rect.y > 210):#player.goalY):
player_moving_up = True
if player_moving_up == True or player_moving_up == True:
player.rect.y += 1
player.rect.y -= 1
player.goalY += 3
if(timer3 > 120):
timer3 = 0
if(player.playing == True and player.gameover == False):
score += 30
#--- Draw and Move Rocks
for rock in obstacles:
rock.draw(screen)
if(player.gameover == False):
rock.move()
rock.draw(screen)
#rock.checkCollision(player.x, player.y)
if pygame.sprite.spritecollide(player, obstacles, False):
obstacles.remove(rock)
#----- Gameover
if(player.gameover == True):
player.goalY = 600
font = pygame.font.SysFont('Ariel', 50, True, False)
text = font.render("Game Over", True, WHITE)
screen.blit(text, [150, 100])
Code edited
Make Rock() also a pygame.sprite.Sprite class and if possible, put in a pygame.sprite.Group(). In that case, you can use if pygame.sprite.spritecollide() to check for detection:
rock = Rock()
player = Player()
obstacles = pygame.sprite.Group()
obsatcles.add(rock)
if pygame.sprite.spritecollide(player, obstacles, False):
pass #Do something
The good thing about using pygame.sprite.Group() is that you can use that to help detect collisions with the player and any other obstacle. Let's assume you have three items in obstacles, in which they are all rock's:
for rock in obstacles:
if pygame.sprite.spritecollide(player, obstacles, False):
obstacles.remove(rock) #Removes the obstacle
Put the group outside the sprite classes and before the while loop.
For the rock, use this in your init function:
self.rect = self.image.get_rect()
So it would be:
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("filename.png")
self.rect = pygame.image.get_rect()
Then add this to your while loop:
for rock in obstacles:
rock.move()
rock.draw()
Your final class (excluding the last two functions) would be:
class Rock(pygames.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("bcrocks.png")
self.rect = self.image.get_rect()
self.rect.x = random.randrange (0, 200)
self.rect.y = 335
First off I am getting this error
File "E:\New folder (7)\maingame.py", line 64, in play print self.introduction AttributeError: 'game' object has no attribute 'introduction'
I am not to sure as to what it means because I am pulling the self.introduction from the previous class..
I am also getting an
File "E:\New folder (7)\maingame.py", line 96, in <module>
game.play()
TypeError: play() takes exactly 2 arguments (1 given)
error, but can't for the life of me find what argument it is looking for, I simply want it to work.
from random import random
class place(object):
def __init__(self, title, description, events):
self.title = title
self.description = description
self.events = events
class event(object):
def __init__(self, probability, message, healthChange):
self.probability = probability
self.message = message
self.healthChange = healthChange
def process(self):
if random() < self.probability:
print self.message
return self.healthChange
return 0
class textadventure():
def __init__(self):
super(textadventure, self).__init__()
self.introduction = """
Welcome player, you are a lone traveler in space whom has set out to find glories beyond measure.
Unfortunately for you the dread pirate Roberts has attacked. You must defeat him.
"""
commandDeck = place('Command Deck', "You are now in the command center, here you can drive the ship and fire its weapons.",(
event(0.7, "The pirate ship fires at you! You take damage to your engines!", -10),
event(0.2, "One of the pirates manages to beam onto your ship! He shoots you before beaming away!",0),
))
engineRoom = place('Engine Room', "You are now in the main engine room here you can repair damage to the ship",(
event(0.7, "The pirate ship fires at you! You take damage to your engines!", -10),
))
restQuarters = place('Resting Quarters', "Here you can take a rest and heal your self",(
event(1.0, 'You are able to patch up your wounds and get back to the battle',0),
event(0.5, "The pirate ship fires at you! You take damage to your engines!", -10),
))
commandDeck.transitions = (engineRoom, restQuarters),
engineRoom.transitions = (commandDeck, restQuarters),
restQuarters.transitions = (commandDeck, engineRoom),
self.location = commandDeck
pirateHp = 50
class game(object, textadventure):
def __init__(self):
super(game, self).__init__()
self.health = 100
def location(self):
if self.location == commandDeck:
choice = raw_input('would you like to fire on the enemy ship?')
if choice == 'yes':
print 'You have hit the pirates!'
pirateHp -= 10
else: choice == 'no'
elif self.location == engineRoom:
choice = raw_input('Would you like to repair the engines?')
if choice == "yes":
event(1, "You repair what you can of the engines.", 10)
def __init__(self):
self.health = 100
def play(self, textadventure):
print textadventure.introduction
while True:
print (self.location.description)
for event in self.location.events:
self.health += event.process()
if self.health <= 0:
print ("Your ship has been destroyed!")
pause
exit(1)
print ('Your ships health is at %d percent' % self.health)
self._transition()
def _transition(self):
transitions = self.location.transitions
print ('you can go to: ')
for (index, transition) in enumerate(transitions):
print (index + 1, transition.title)
choice = int(raw_input('Choose one '))
if choice == 0:
exit(0)
else:
self.location = transitions[choice - 1]
def pirateShip(Object):
if pirateHp == 0:
print "You have defeated the pirates! Congradualations!"
pause
exit(1)
game = game()
game.play(game)
'game' object has no attribute 'introduction'
You should call the init of your super class when initializing game. In your current code, textadventure.init is never called which is why introduction is never added to textadventure.
Game should also not inherit from object (it does that through textadventure).
class game(textadventure):
def __init__(self):
super(game, self).__init__()
self.health = 100
def play(self):
print self.introduction
Should do the trick.
TypeError: play() takes exactly 2 arguments (1 given)
You never use your textadventure argument in play. Removing this should get things working.
I need to make the balls in this code move around randomly. I am not sure what I am doing wrong. I am new to programming and this may be badly coded so any help would be appreciated. Right now the code makes a character in the middle of the screen that you can move up or down and it makes one ball in the top left corner of the screen that does not move. I want multiple balls on the screen and eventually I want the balls to be moving around randomly and if they collide with the character you lose this simple game.
from pygame import *
import random
class Ball(sprite.Sprite):
def __init__(self, numballs, balls = []):
sprite.Sprite.__init__(self)
self.image = image.load('ball.png')
self.rect = self.image.get_rect()
self.numballs = numballs
self.balls = balls
def multipleBalls(self):
for count in range(self.numballs):
self.balls.append(dict)
self.balls[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1,2), 'ymove':random.randint(1,2)}
def ballMove(self):
for count in range(self.numballs):
self.balls[count]['x'] = self.balls[count]['x'] + self.balls[count]['xmove']
self.balls[count]['y'] = self.balls[count]['y'] + self.balls[count]['ymove']
def ballsOnScreen(self):
for count in range(self.numballs):
self.screen.blit(self.image, (self.balls[count]['x'], self.balls[count]['y']))
def ballBarrier(self):
for count in range(self.numballs):
if self.balls[count]['x'] > 620:
self.balls[count]['xmove'] = random.randint(-2, 0)
if self.balls[count]['x'] < -10:
self.balls[count]['xmove'] = random.randint(0, 2)
if self.balls[count]['y'] > 470:
self.balls[count]['ymove'] = random.randint(-2, 0)
if self.balls[count]['y'] < -10:
self.balls[count]['ymove'] = random.randint(0, 2)
def manageBall(self):
self.multipleBalls()
self.ballsOnScreen()
self.ballMove()
self.ballBarrier()
class Character(sprite.Sprite):
def __init__(self, xy):
sprite.Sprite.__init__(self)
self.image = image.load('character.png')
self.rect = self.image.get_rect()
self.rect.centerx, self.rect.centery = xy
self.movementspeed = 1
self.velocity = 0
def down(self):
self.velocity += self.movementspeed
def up(self):
self.velocity -= self.movementspeed
def characterMove(self, dy):
if self.rect.bottom + dy > 480:
self.rect.bottom = 480
elif self.rect.top + dy < 0:
self.rect.top = 0
else:
self.rect.y += dy
def update(self):
self.characterMove(self.velocity)
class Game(object):
def __init__(self):
init()
key.set_repeat(1, 30)
self.screen = display.set_mode((640, 480))
self.clock = time.Clock()
display.set_caption('Game')
event.set_allowed([QUIT, KEYDOWN, KEYUP])
self.background = Surface((640, 480))
self.background.fill((0,0,0))
self.screen.blit(self.background, (0,0))
display.flip()
self.sprites = sprite.RenderUpdates()
self.character = Character((320, 240))
self.sprites.add(self.character)
self.ball = Ball(5)
self.sprites.add(self.ball)
def run(self):
running = True
while running == True:
self.clock.tick(60)
running = self.handleEvents()
display.set_caption('game %d fps' % self.clock.get_fps())
for sprite in self.sprites:
sprite.update()
self.sprites.clear(self.screen, self.background)
dirty = self.sprites.draw(self.screen)
display.update(dirty)
self.ball.manageBall()
def handleEvents(self):
for e in event.get():
if e.type == QUIT:
return False
elif e.type == KEYDOWN:
if e.key == K_ESCAPE:
return False
if e.key == K_UP:
self.character.up()
if e.key == K_DOWN:
self.character.down()
return True
def main():
game = Game()
game.run()
main()
I've never used the Sprite class before so this was a good exercise. :)
I fixed your code, just change the image paths back to your icon locations and you should be good to go. The print statements might need reformatting if you're running an older version of Python.
I take out the forced call to the Sprite init method in the Ball and Character classes, it won't let me add them to the game.sprites render group. Not sure why.
I'm running Python 3.2.2 and Pygame 1.9.2pre so YMMV. :)
Controls:
UP / DOWN = Move your dude.
R = add a new, random ball.
from pygame import *
import random
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
FPS = 60
class Ball(sprite.Sprite):
def __init__(self, xy = (0,0), xm = 0, ym = 0):
sprite.Sprite.__init__(self)
self.img_load('evil_balloon_32x32.png')
self.rect.centerx, self.rect.centery = xy
self.xmove = xm
self.ymove = ym
def update(self):
self.move()
self.ballBarrier()
def move(self):
self.rect.x += self.xmove
self.rect.y += self.ymove
def img_load(self, filename):
self.image = image.load(filename)
self.rect = self.image.get_rect()
def ballBarrier(self):
"""
Checks to make sure ball is within bounds, adjusts movement speed if it's not
"""
if self.rect.right > SCREEN_WIDTH:
self.xmove = random.randint(-2, 0)
if self.rect.left < 0:
self.xmove = random.randint(0, 2)
if self.rect.bottom > SCREEN_HEIGHT:
self.ymove = random.randint(-2, 0)
if self.rect.top < 0:
self.ymove = random.randint(0, 2)
class ball_manager():
def __init__(self, numballs = 5, balls = []):
self.blist = balls
if numballs > 0:
self.multipleBalls(numballs) # moved this here so balls get init'd only once
def update(self):
"""
Update position of all balls
"""
for ball in self.blist:
self.ballMove(ball)
def add_ball(self, xy = (0,0), xm = 0, ym = 0):
self.blist.append(Ball(xy, xm, ym)) # appends a random ball
def multipleBalls(self, numballs):
for i in range(numballs):
self.add_ball((random.randint(0, SCREEN_WIDTH),
random.randint(0, SCREEN_HEIGHT)),
random.randint(-2,2),
random.randint(-2,2))
class Character(sprite.Sprite):
def __init__(self, xy):
sprite.Sprite.__init__(self)
self.img_load()
self.rect.centerx, self.rect.centery = xy
self.movementspeed = 1
self.velocity = 0
def down(self):
self.velocity += self.movementspeed
def up(self):
self.velocity -= self.movementspeed
def characterMove(self, dy):
if self.rect.bottom + dy > SCREEN_HEIGHT:
self.rect.bottom = SCREEN_HEIGHT
self.velocity = 0
elif self.rect.top + dy < 0:
self.rect.top = 0
self.velocity = 0
else:
self.rect.y += dy
def update(self):
self.characterMove(self.velocity)
def img_load(self):
self.image = image.load("scary_clown_32x32.png")
self.rect = self.image.get_rect()
class Game(object):
def __init__(self):
init()
key.set_repeat(1, 30)
self.screen = display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
self.clock = time.Clock()
display.set_caption('Game')
event.set_allowed([QUIT, KEYDOWN, KEYUP])
self.background = Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
self.background.fill((0,0,0))
self.screen.blit(self.background, (0,0))
display.flip()
self.sprites = sprite.RenderUpdates()
self.character = Character((SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))
self.sprites.add(self.character)
self.balls = ball_manager(5)
for ball in self.balls.blist:
self.sprites.add(ball)
def run(self):
running = True
while running == True:
self.clock.tick(FPS)
running = self.handleEvents()
display.set_caption('game %d fps' % self.clock.get_fps())
self.sprites.clear(self.screen, self.background)
for sprite in self.sprites:
sprite.update()
dirty = self.sprites.draw(self.screen)
display.update(dirty)
def handleEvents(self):
for e in event.get():
if e.type == QUIT:
return False
elif e.type == KEYDOWN:
if e.key == K_ESCAPE:
return False
if e.key == K_UP:
self.character.up()
if e.key == K_DOWN:
self.character.down()
if e.key == K_r:
self.sprites.add(Ball((random.randint(0, SCREEN_WIDTH),
random.randint(0, SCREEN_HEIGHT)),
random.randint(-2,2),
random.randint(-2,2)))
return True
def main():
game = Game()
game.run()
quit()
main()
sys.exit()