I've recently implemented an enemy that shoots at regular intervals at a designated point on the screen. However, upon trying to make this point the player rect, it refused to work. As the enemy class is defined in the rooms module which is then defined in the main game module, I am not quite certain on how to call the player rect in the enemy module.
Working code as follows:
Game module
import pygame
from constants import *
from player import Player
from pygame.math import Vector2
from enemy import *
from Rooms import Room0
pygame.init()
screen_rect = pygame.display.set_mode([500, 500])
pygame.display.set_caption('Labyrinth')
all_sprites_list = pygame.sprite.Group()
projectiles = pygame.sprite.Group()
enemy_sprites = pygame.sprite.Group()
# Assign rooms
rooms = []
room = Room0()
rooms.append(room)
current_room_no = 0
current_room = rooms[current_room_no]
# Spawn player
player = Player(50, 50)
all_sprites_list.add(player)
clock = pygame.time.Clock()
done = False
# ----- Event Loop
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# ----- Game Logic
all_sprites_list.update()
current_room.projectiles.update()
current_room.enemy_sprites.update()
screen_rect.fill(GREEN)
all_sprites_list.draw(screen_rect)
current_room.projectiles.draw(screen_rect)
current_room.enemy_sprites.draw(screen_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Rooms module
import pygame
from enemy import Enemy
import Projectile
from pygame.math import Vector2
class Room(object):
enemy_sprites = None
projectiles = None
def __init__(self):
self.enemy_sprites = pygame.sprite.Group()
self.projectiles = pygame.sprite.Group()
class Room0(Room):
def __init__(self):
super().__init__()
enemy = Enemy(380, 280, self.projectiles)
self.enemy_sprites.add(enemy)
Player module
from constants import *
import pygame
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([15, 15])
self.image.fill(BLACK)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
Enemy module
from constants import *
import pygame
from Projectile import Bullet
from pygame.math import Vector2
target = Vector2(400, 400)
class Enemy(pygame.sprite.Sprite):
def __init__(self, x, y, projectiles):
super().__init__()
self.image = pygame.Surface([10, 10])
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.previous_time = pygame.time.get_ticks()
self.shoot_delay = 1000
self.speed = 12
self.projectiles = projectiles
def update(self):
now = pygame.time.get_ticks()
if now - self.previous_time > self.shoot_delay:
self.previous_time = now
bullet = Bullet(self.rect.x, self.rect.y, target)
self.projectiles.add(bullet)
Projectile module
import pygame
from constants import *
from pygame.math import Vector2
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, target):
super().__init__()
self.image = pygame.Surface((10, 10))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.position = Vector2(self.rect.x, self.rect.y)
direction = target - self.position
radius, angle = direction.as_polar()
self.image = pygame.transform.rotozoom(self.image, -angle, 1)
self.velocity = direction.normalize() * 11
def update(self):
self.position += self.velocity
self.rect.center = self.position
There's an answer you want, and an answer you need. Respectively:
SomeModule.py:
from game import player # imports the Player *instance* you've created in the main module
some_func(player) # as argument
player.another_func # method access
Now, that's the way you'd normally access that kind of stuff, and this would be perfectly fine. In this case though:
a) You'll spawn a whole new game loop, because you put the game setup at module scope rather than in some function or, at very least, directly under an if __name__ == '__main__'. Importing a module executes all the code in the module scope.
b) The very fact you have to import a non-singleton instance, directly, is a code smell - what the very existence of this problem should signal to you is that you likely have a place where your bits of code must be able talk to each other, but you have nothing unambiguously responsible for mediating that process.
So, to address the second part of my promised answer: you should not let this problem occur in the first place - build something dedicated to managing players and enemies, import just the class definitions, then instance and interface between them in the manager.
Related
This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Closed 8 months ago.
So I'm working on a simple game in pygame and I have a file named players.py that contains a Player class and a PlayerAttack class because I want to have the projectiles be their own object. Here is some code from my players.py
import pygame
import gametools
class PlayerAttack(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.bullet_img = gametools.smoothscale2x(pygame.image.load('sprites/player/player-bullet.png')).convert_alpha()
self.image = self.bullet_img
self.rect = self.image.get_rect(center = (400, 300))
class Player(pygame.sprite.Sprite):
'''The Main player class'''
def __init__(self):
super().__init__()
self.player_image_center = gametools.smoothscale2x(pygame.image.load('sprites/player/player.png')).convert_alpha()
self.player_image_left = gametools.smoothscale2x(pygame.image.load('sprites/player/player-left.png')).convert_alpha()
self.player_image_right = gametools.smoothscale2x(pygame.image.load('sprites/player/player-right.png')).convert_alpha()
self.player_image = [self.player_image_left, self.player_image_center, self.player_image_right]
self.player_index = 1
self.image = self.player_image[self.player_index]
self.rect = self.image.get_rect(center = (400, 500))
self.vector = pygame.math.Vector2()
self.velocity = 5
self.bullet = pygame.sprite.Group()
self.bullet.add(PlayerAttack())
def player_input(self):
keys = pygame.key.get_pressed()
# player movement
if keys[pygame.K_UP]:
self.vector.y = -1
elif keys[pygame.K_DOWN]:
self.vector.y = 1
else:
self.vector.y = 0
if keys[pygame.K_LEFT]:
self.vector.x = -1
elif keys[pygame.K_RIGHT]:
self.vector.x = 1
else:
self.vector.x = 0
# attacks
if keys[pygame.K_x]:
return self.bullet.draw(screen)
def move(self, velocity):
if self.vector.magnitude() != 0:
self.vector = self.vector.normalize()
self.rect.center += self.vector * velocity
def update(self):
self.player_input()
self.animation_state()
self.move(self.velocity)
If you look in the __init__() method in the Player class you will see that I define self.bullet as an object belonging to the PlayerAttack class. Now if you look inside the player_input() method in the Player class you see that it draws it to the screen surface defined in main.py
import pygame
import gametools
import players
from sys import exit
# initilaization
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Bullet hell')
clock = pygame.time.Clock()
# Player
player = pygame.sprite.GroupSingle()
player.add(players.Player())
x = pygame.sprite.GroupSingle()
# Background
back_surf = pygame.image.load('sprites/backgrounds/background.png').convert()
# main game loop
while True:
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# display background
screen.blit(back_surf, (0, 0))
player.draw(screen)
player.update()
pygame.display.update()
clock.tick(60)
This produces an error because screen is defined in main.py and not in the Player class. So my question is how can I draw an object to the screen when receiving input from within the class. Or is there a better way to go about this?
I'm making a basic dodger game where you play as a fish and need to avoid getting hit by obstacles. I want the obstacles to come from the right side of the screen at a random velocity (from a certain range, let's just say 4 to 6). I already have the fish/underwater gravity mechanics working. But I have no idea where to start with the obstacles.
This is my main python script:
import pygame
from assets.player import Bob
# Screen properties
pygame.init()
# Important Variables
run = True
game_speed = 0
SCREEN_WIDTH, SCREEN_HEIGHT = 900, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
FPS = 60
# Properties
bg_game_surface = pygame.image.load('images/game-background.png')
player = Bob(game_speed)
#############
# Functions #
#############
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.blit(bg_game_surface, (0, 0))
player.update(screen)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
And this is the class for my player:
import pygame
class Bob:
def __init__(self, game_speed):
self.img = pygame.image.load('images/player/bob.png').convert_alpha()
self.img_up = pygame.image.load('images/player/bob_up.png').convert_alpha()
self.rect = self.img.get_rect()
self.game_speed = game_speed
def update(self, screen):
key = pygame.key.get_pressed()
### Collision
if self.rect.top <= 0:
self.rect.centery = (screen.get_height() - self.img.get_height() * 2) + 10
elif self.rect.top >= screen.get_height() - self.img.get_height() * 2:
self.rect.centery = 20
### Movement
if key[pygame.K_w] or key[pygame.K_UP]:
self.rect.centery -= 6
self.img = pygame.image.load('images/player/bob_up.png').convert_alpha()
### Gravity
else:
self.img = pygame.image.load('images/player/bob.png').convert_alpha()
self.rect.centery += 4
screen.blit(self.img, self.rect)
My folders are sorted like this:
Right now, I'd like that the trash.py is also a class with a function called "update". When that function is executed, obstacles (preferably in the form of an image) come out of the right side of the display, doing what I said above.
Any help is appreciated. Thanks in advance :)
You should make a sprite class group, but first you need to import the random module:
import random
Now you can create the Obstacle Sprite class, this is just an example:
class Obstacle(pygame.sprite.Sprite):
def __init__(self, pos): #pos is the starting position
super().__init__()
self.image = pygame.Surface((10,10)) # You can change this with pygame.image.load('...')
self.rect = self.image.get_rect(topleft = pos)
self.vel = random.randint(4,6) #random speed of the obstacle
def collisions(self, player): #collisions function
if self.rect.colliderect(player.rect):
print('collision!') #write what you want to happen
def movement(self): #the blocks are moving left
if self.rect.x > -100: #just putting some limits
self.rect.x -= self.vel
def update(self, player): #try to put all the other functions in the update one
self.collisions(player)
self.movement()
Once you created the class, you only need to create some objects of that class (every obstacle).
First we create a sprite group before of the while loop:
obstacles = pygame.sprite.Group()
Then, inside your main loop, you need a condition that generates the obstacles.
I've done something like this, but you really should change it:
if x < 10: #I created x before the while (x=0)
posx = SCREEN_WIDTH + 50 #the starting x will be 50 pixels right of the screen
posy = random.randint(0, SCREEN_HEIGHT) #Im setting this to random
obs = Obstacle((posx, posy))
obstacles.add(obs)
x +=1
This basically creates 9 obstacles when we start the game, with different random x speed and y location, and draw them on the screen. If you collide with one of the blocks, the code just prints "collision!" (see the Obstacle class). Hope it was helpful and I didn't miss something.
I have created two simple sprites in PyGame and one of them is an Umbrella, the other one is a rain drop.
The Raindrops are added into a sprite group called all_sprites. The Umbrella sprite has its own group called Umbrella_sprite
The raindrops are "falling" from top of the screen and if one of them touches the umbrella / collides with it.. the raindrop is supposed to be deleted. BUT instead of that specific raindrops all other are affected by this.
main file (rain.py)
#!/usr/bin/python
VERSION = "0.1"
import os, sys, raindrop
from os import path
try:
import pygame
from pygame.locals import *
except ImportError, err:
print 'Could not load module %s' % (err)
sys.exit(2)
# main variables
WIDTH, HEIGHT, FPS = 300, 300, 30
# initialize game
pygame.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Rain and Rain")
# background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((40,44,52))
# blitting
screen.blit(background,(0,0))
pygame.display.flip()
# clock for FPS settings
clock = pygame.time.Clock()
def main():
all_sprites = pygame.sprite.Group()
umbrella_sprite = pygame.sprite.Group()
# a function to create new drops
def newDrop():
nd = raindrop.Raindrop()
all_sprites.add(nd)
# creating 10 rain drops
for x in range(0,9): newDrop()
# variable for main loop
running = True
# init umbrella
umb = raindrop.Umbrella()
# all_sprites.add(umb)
umbrella_sprite.add(umb)
# event loop
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for enemy in all_sprites:
gets_hit = pygame.sprite.spritecollideany(umb, all_sprites)
if gets_hit:
all_sprites.remove(enemy)
screen.blit(background,(100,100))
# clear
all_sprites.clear(screen,background)
umbrella_sprite.clear(screen,background)
# update
all_sprites.update()
umbrella_sprite.update()
# draw
all_sprites.draw(screen)
umbrella_sprite.draw(screen)
# flip the table
pygame.display.flip()
pygame.quit()
if __name__ == '__main__':
main()
raindrop.py ( Raindrop() & Umbrella() )
import pygame
from pygame.locals import *
from os import path
from random import randint
from rain import HEIGHT, WIDTH
img_dir = path.join(path.dirname(__file__), 'img')
class Raindrop(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.width = randint(32, 64)
self.height = self.width + 33
self.image = pygame.image.load(path.join(img_dir, "raindrop.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (self.width, self.height))
self.speedy = randint(1, 15)
self.rect = self.image.get_rect()
self.rect.x = randint(0, 290)
self.rect.y = -self.height
def reset(self):
self.rect.y = -self.height
def update(self):
self.rect.y += self.speedy
if self.rect.y >= HEIGHT:
self.rect.y = -self.height
self.rect.x = randint(0, 290)
class Umbrella(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.width = 50
self.height = 50
self.image = pygame.image.load(path.join(img_dir,"umbrella.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (self.width, self.height))
self.speedx = 10
self.rect = self.image.get_rect()
self.rect.x = (WIDTH/2) - self.width
self.rect.y = (0.7 * HEIGHT)
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and self.rect.x > 0:
self.rect.x -= self.speedx
elif keys[pygame.K_RIGHT] and self.rect.x < (WIDTH - self.width):
self.rect.x += self.speedx
This is your problem:
for enemy in all_sprites:
gets_hit = pygame.sprite.spritecollideany(umb, all_sprites)
if gets_hit:
all_sprites.remove(enemy)
You're looping through the group, and if any sprite collides, deleting all of them.
You don't need to loop through the group - the collision functions take care of that. You just need to use the spritecollide function, which compares a sprite versus a group. That function will return a list of collisions, as well as using the DOKILL flag to delete them automatically:
gets_hit = pygame.sprite.spritecollide(umb, all_sprites, True)
spritecollideany checks if the sprite collides with any sprite in the group and returns this sprite, so gets_hit is a trueish value as long as the collided sprite in the group is not removed and the if gets_hit: block gets executed. That means the code in the for loop simply keeps deleting every sprite in the group that appears before the collided sprite is reached and removed. A simple fix would be to check if the hit sprite is the enemy: if enemy == gets_hit:, but the code would still be inefficient, because spritecollideany has to loop over the all_sprites group again and again inside of the for loop.
I recommend to use spritecollide instead of spritecollideany as well, since it's more efficient and just one line of code.
I created a simple 2D game with python 2 and pygame where you have to avoid squares that are moving down. I created this class for the 'enemy':
class Enemy(pygame.sprite.Sprite):
def __init__(self, game):
self.groups = game.all_sprites
pygame.sprite.Sprite.__init__(self, self.groups)
self.game = game
self.image = pygame.Surface((TILESIZE + 10, TILESIZE + 10))
self.image.fill(ENEMY_COLOR)
self.rect = self.image.get_rect()
self.x = random.uniform(0, WIDTH - TILESIZE)
self.rect.x = self.x
self.y = 0
def update(self):
if self.rect.colliderect(self.game.player.rect):
self.game.deaths += 1
self.game.score = 0
self.game.run()
self.rect.y += (self.game.score + 500) / 50
Then, I have a thread that creates an instance of the enemy:
class Create_Enemy(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
while True:
while not game.game_paused:
time.sleep((game.score + 1) / game.speed)
Enemy(game)
Then in the draw method i just write self.all_sprites.draw()
The game is an infinite runner, and every frame the enemies move a few pixels down. The problem is that after a bit the game gets laggy since, when the blocks go offscreen, the sprites don't get deleted.
Is there a way to automatically delete the offscreen instances?
I tried the following but it just deletes all the enemies onscreen.
if self.rect.y >= WIDTH:
self.rect.kill()
I was thinking I could do something like game.all_sprites.pop(1) (the position 0 is the player) but I couldn't find a way to archive something similar ...
The enemies can remove themselfs from the game by calling self.kill() if their rect is no longer inside the screen, e.g.:
def update(self):
if self.rect.colliderect(self.game.player.rect):
self.game.restart() # reset score + count deaths
# we can simply use move_ip here to move the rect
self.rect.move_ip(0, (self.game.score + 500) / 100)
# check if we are outside the screen
if not self.game.screen.get_rect().contains(self.rect):
self.kill()
Also, instead of the thread, you can use pygame's event system to spawn your enemies. Here's a simple, incomplete but runnable example (note the comments):
import random
import pygame
TILESIZE = 32
WIDTH, HEIGHT = 800, 600
# a lot of colors a already defined in pygame
ENEMY_COLOR = pygame.color.THECOLORS['red']
PLAYER_COLOR = pygame.color.THECOLORS['yellow']
# this is the event we'll use for spawning new enemies
SPAWN = pygame.USEREVENT + 1
class Enemy(pygame.sprite.Sprite):
def __init__(self, game):
# we can use multiple groups at once.
# for now, we actually don't need to
# but we could do the collision handling with pygame.sprite.groupcollide()
# to check collisions between the enemies and the playerg group
pygame.sprite.Sprite.__init__(self, game.enemies, game.all)
self.game = game
self.image = pygame.Surface((TILESIZE + 10, TILESIZE + 10))
self.image.fill(ENEMY_COLOR)
# we can use named arguments to directly set some values of the rect
self.rect = self.image.get_rect(x=random.uniform(0, WIDTH - TILESIZE))
# we dont need self.x and self.y, since we have self.rect already
# which is used by pygame to get the position of a sprite
def update(self):
if self.rect.colliderect(self.game.player.rect):
self.game.restart() # reset score + count deaths
# we can simply use move_ip here to move the rect
self.rect.move_ip(0, (self.game.score + 500) / 100)
# check if we are outside the screen
if not self.game.screen.get_rect().contains(self.rect):
self.kill()
class Player(pygame.sprite.Sprite):
def __init__(self, game):
pygame.sprite.Sprite.__init__(self, game.all, game.playerg)
self.game = game
self.image = pygame.Surface((TILESIZE, TILESIZE))
self.image.fill(PLAYER_COLOR)
self.rect = self.image.get_rect(x=WIDTH/2 - TILESIZE/2, y=HEIGHT-TILESIZE*2)
def update(self):
# no nothing for now
pass
class Game(object):
def __init__(self):
# for now, we actually don't need mujtiple groups
# but we could do the collision handling with pygame.sprite.groupcollide()
# to check collisions between the enemies and the playerg group
self.enemies = pygame.sprite.Group()
self.all = pygame.sprite.Group()
self.playerg = pygame.sprite.GroupSingle()
self.running = True
self.score = 0
self.deaths = -1
self.clock = pygame.time.Clock()
def restart(self):
# here we set the timer to create the SPAWN event
# every 1000 - self.score * 2 milliseconds
pygame.time.set_timer(SPAWN, 1000 - self.score * 2)
self.score = 0
self.deaths += 1
def run(self):
self.restart()
self.player = Player(self)
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
while self.running:
for e in pygame.event.get():
if e.type == pygame.QUIT:
self.running = False
# when the SPAWN event is fired, we create a new enemy
if e.type == SPAWN:
Enemy(self)
# draw and update everything
self.screen.fill(pygame.color.THECOLORS['grey'])
self.all.draw(self.screen)
self.all.update()
pygame.display.flip()
self.clock.tick(40)
if __name__ == '__main__':
Game().run()
Check the values of self.rect.y, WIDTH, maybe the method kill. It looks like self.rect.y is always greater or equal WIDTH, that's why it kills them all.
I am trying to create a sprite class where the user can define and add any number of sprites on to the screen from a random location using this tutorial. However, when I try to run my current program it puts the error
AttributeError: type object 'Sprite' has no attribute 'sprite'
But I dont understand why, all the logic seems correct.
Any suggestions?
Heres my code:
import pygame, sys, random
pygame.init()
black = (0, 0, 0)
image = pygame.image.load("resources/images/img.png")
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 400
sprite_width = 5
sprite_height = 5
sprite_count = 5
# no changes here when using sprite groups
class Sprite(pygame.sprite.Sprite):
def __init__(self, Image, pos):
pygame.sprite.Sprite.__init__(self)
self.image =pygame.image.load("resources/images/img.png")
self.rect = self.image.get_rect()
self.rect.topleft = pos
self.pygame.display.set_caption('Sprite Group Example')
self.clock = pygame.time.Clock()
# this is a how sprite group is created
self.sprite = pygame.sprite.Group()
def update(self):
self.rect.x += 1
self.rect.y += 2
if self.rect.y > SCREEN_HEIGHT:
self.rect.y = -1 * sprtie_height
if self.rect.x > SCREEN_WIDTH:
self.rect.x = -1 * sprite_width
#classmethod
def sprites(self):
for i in range(actor_count):
tmp_x = random.randrange(0, SCREEN_WIDTH)
tmp_y = random.randrange(0, SCREEN_HEIGHT)
# all you have to do is add new sprites to the sprite group
self.sprite.add(Sprite(image, [tmp_x, tmp_y]))
#classmethod
def game_loop(self):
screen = pygame.display.set_mode([640, 400])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(black)
# to update or blitting just call the groups update or draw
# notice there is no for loop
# this will automatically call the individual sprites update method
self.sprite.update()
self.sprite.draw(screen)
self.pygame.display.update()
self.clock.tick(20)
Sprite.sprites()
Sprite.game_loop()
You define class method (#classmethod) but self.sprite exists only in object/instance not in class - it is created in __init__ when you crate new object/instance.
Remove #classmethod to have object/instance method and have no problem with self.sprite.
Or create sprite outside __init__ to get class attribute
class Sprite(pygame.sprite.Sprite):
sprite = pygame.sprite.Group()
def __init__(self, Image, pos)
# instance variable - value copied from class variable
print self.sprite
# class variable
print self.__class__.sprite
#classmethod
def sprites(self):
# instance variable not exists
# class variable
print self.sprite