How can a object detect the mouse in pygame - python

import pygame
from pygame.constants import( QUIT, KEYDOWN, KEYUP, K_LEFT, K_RIGHT, K_ESCAPE, K_SPACE,
MOUSEBUTTONDOWN)
import os
from random import randint
class Settings:
w_width = 800
w_height = 600
w_border = 50
file_path = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(file_path, "pictures")
class Background(object):
def __init__(self, filename):
self.imageo = pygame.image.load(os.path.join(Settings.image_path, filename))
self.image = pygame.transform.scale(self.imageo, (Settings.w_width, Settings.w_height)).convert()
self.rect = self.image.get_rect()
def draw(self, screen):
screen.blit(self.image, self.rect)
I have here the bubbles class and i want to do it that when you click a bubble it despawns but i dont know how the bubbles detect the mouse cursor and how the bubbles despawn.
I already tried to add the mouse position function but I dont know hot to use it.
And I searched on the Internet but I found nothing about that.
class Bubble(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.width = 50
self.height = 300
self.image = pygame.image.load(os.path.join(Settings.image_path, "Blase.png ")).convert_alpha()
self.image = pygame.transform.scale(self.image, (25, 25))
self.rect_br = (Settings.w_width//2) + 100, (Settings.w_height//2) + 100
self.rect = self.image.get_rect()
self.mousex, self.mousey = pygame.mouse.get_pos()
self.cx = self.width - 25
self.cy = self.height - 25
self.rect.left = randint(Settings.w_border, Settings.w_width - Settings.w_border)
self.rect.top = randint(Settings.w_border, Settings.w_height - (Settings.w_border * 2))
def update(self):
pass
def scale_up(self):
self.scale["width"] += 2
self.scale["height"] += 2
def scale_down(self):
self.scale["width"] -= 2
self.scale["height"] -= 2
def events(self):
pass
def draw(self, screen):
screen.blit(self.image,self.rect )
Here is where everythings run from the code
class Game(object):
def __init__(self):
self.screen = pygame.display.set_mode((Settings.w_width, Settings.w_height))
self.clock = pygame.time.Clock()
self.runn = False
self.background = Background("Hintergrund.png")
self.bubble = pygame.sprite.Group()
def run(self):
self.runn = True
while self.runn:
self.clock.tick(60)
self.watch_for_events()
self.draw()
self.events()
def events(self):
if len(self.bubble)< 100:
self.bubble.add(Bubble())
time.sleep(0.2)
def draw(self):
self.background.draw(self.screen)
self.bubble.draw(self.screen)
pygame.display.flip()
def watch_for_events(self):
for event in pygame.event.get():
if event.type == QUIT:
self.runn = False
if __name__ == '__main__':
os.environ['SDL_VIDEO_WINDOWS_POS'] = "50, 1100"
pygame.init()
game = Game()
game.run()
pygame.quit()
Thanks for Helping

"Despawn" a bubble by calling pygame.sprite.Sprite.kill. kill remove the Sprite from all Groups. Use the MOUSEBUTTONDOWN event and pygame.Rect.collidepoint to determine if a bubble is clicked:
class Game(object):
# [...]
def watch_for_events(self):
for event in pygame.event.get():
if event.type == QUIT:
self.runn = False
if event.type == MOUSEBUTTONDOWN:
for bubble in self.bubble:
if bubble.rect.collidepoint(event.pos):
bubble.kill()

Related

TypeError: pygame.sprite.Sprite.add() argument after * must be an iterable, not int

I have a problem with my code, after running, it said that " pygame.sprite.Sprite.add() argument after * must be an iterable, not int" in the line charS1=CharS(100,100,50,50)
i was expecting a red rect in my window after, but i had those problem
here my code, and yes, almost copy from Youtube, but it went wrong
import pygame, os , sys , math
from os import listdir
from os.path import isfile, join
pygame.init()
pygame.display.set_caption("Group 5: Female house from Ẻuope")
icon = pygame.image.load(join("img","good-icon.png"))
pygame.display.set_icon(icon)
WIDTH, HEIGHT = 1000, 600
FPS = 40
PLAYER_VEL = 3
window=pygame.display.set_mode((WIDTH, HEIGHT))
def get_background(name):
background = pygame.image.load(join("img",name))
return background
class CharS(pygame.sprite.Sprite):
COLOR = (255,0,0)
def __init__(self,x,y, width, heigth):
self.rect=pygame.Rect(x,y,width,heigth)
self.x_vel=0
self.y_vel=0
self.mask= None
self.direction= "right"
self.animation_count = 0
def move (self, dx, dy):
self.rect.x += dx
self.rect.y += dy
def move_right(self, vel):
self.x_vel = vel
if self.direction != "left":
self.direction = "left"
self.animation_count= 0
def loop(self, fps):
self.move( self.x_vel, self.y_vel)
def draw(self, win):
pygame.draw.rect(win, self.COLOR, self.rect)
def draw(window, background,char):
window.blit(background, (0,0))
char.draw(window)
pygame.display.update()
def main(window):
clock = pygame.time.Clock()
background= get_background("backgrd.png")
charS1=CharS(100,100,50,50) #the problem went here
run= True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
draw(window, background, charS1)
pygame.quit()
quit()
if __name__ == '__main__' :
main(window)
how can i fix that?
You get this error, because the base class pygame.sprite.Sprite is not initialized. You didn't invoke the constructor of the base class of (super().__init__() ). Also see class super.
class CharS(pygame.sprite.Sprite):
COLOR = (255,0,0)
def __init__(self,x,y, width, heigth):
super().__init__() # <---
self.rect=pygame.Rect(x,y,width,heigth)
# [...]

Why doesn't my Pygame sprite move when I blit it to the screen?

I tried to blit a sprite to the screen in Pygame.
Here's my code:
import pygame
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT
)
WINDOW = pygame.display.set_mode((800,800))
class Player(pygame.sprite.Sprite):
def __init__(self):
self.x = 0
self.y = 0
super().__init__()
self.surf = pygame.Surface((50,50))
self.surf.fill((20, 115, 224))
self.rect = self.surf.get_rect()
def update(self):
print("Updated")
GRAVITY = 10
self.y += GRAVITY
self.rect = (self.x,self.y)
def game_loop():
run = True
while run:
WINDOW.fill((52, 183, 235))
Player().update()
WINDOW.blit(Player().surf,(Player().x,Player().y))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
run = False
pygame.quit()
if __name__ == "__main__":
game_loop()
The specific part I am having trouble with are:
def update(self):
print("Updated")
GRAVITY = 10
self.y += GRAVITY
self.rect = (self.x,self.y)
and
Player().update()
WINDOW.blit(Player().surf,(Player().x,Player().y))
When I run this code, the sprite doesn't move from the screen even though self.y is being added by gravity. How can I fix it?
As I understand your code, you are instantiating a new Player() with default settings everytime you refer to Player().
Try:
import pygame
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT
)
WINDOW = pygame.display.set_mode((800,800))
class Player(pygame.sprite.Sprite):
def __init__(self):
self.x = 0
self.y = 0
super().__init__()
self.surf = pygame.Surface((50, 50))
self.surf.fill((20, 115, 224))
self.rect = self.surf.get_rect()
def update(self):
print("Updated")
GRAVITY = 10
self.y += GRAVITY
self.rect = (self.x, self.y)
def game_loop():
run = True
player = Player()
while run:
WINDOW.fill((52, 183, 235))
player.update()
WINDOW.blit(player.surf, (player.x, player.y))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
run = False
pygame.quit()
if __name__ == "__main__":
game_loop()

i want to change the location of my sprite when i click.... who to do that?

from numpy import place
import pygame, sys ,random as ran
start = True
ref_x = ran.randint(18,387)
ref_y = ran.randint(18,387)
class Player(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
super().__init__()
self.attack_animation = False
self.sprites_1 = []
self.sprites_1.append(pygame.image.load('.\crossHair.png'))
self.sprites_1.append(pygame.image.load('.\crossHair_2.png'))
self.sprites_1.append(pygame.image.load('.\crossHair_3.png'))
self.sprites_1.append(pygame.image.load('.\crossHair_4.png'))
self.sprites_1.append(pygame.image.load('.\crossHair_5.png'))
self.sprites_1.append(pygame.image.load('.\FIRE.png'))
self.current_sprite = 0
self.image = self.sprites_1[self.current_sprite]
self.image.set_colorkey('white')
for items in self.sprites_1:
items.set_colorkey('white')
self.rect = self.image.get_rect()
self.rect.topleft = [pos_x,pos_y]
def attack(self):
self.attack_animation = True
self.image.set_colorkey('white')
if mouse[0]+24 >= ref_x and ref_x+4 >= mouse[0] and mouse[1]+24 >= ref_y and ref_y+13 >= mouse[1]:
get_shot()
else :
print(ref_x,'here')
def update(self,speed):
self.image.set_colorkey('white')
mouse = pygame.mouse.get_pos()
if self.attack_animation == True:
self.current_sprite += speed
if int(self.current_sprite) >= len(self.sprites_1):
self.current_sprite = 0
self.attack_animation = False
print(mouse)
print('shot')
self.image = self.sprites_1[int(self.current_sprite)]
# self.image = self.sprites_1[int(self.current_sprite)]
self.rect = mouse
class enemy(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
super().__init__()
self.image = pygame.image.load('sp_1.png')
self.rect = self.image.get_rect()
self.rect.center = [pos_x, pos_y]
self.image.set_colorkey((255,255,255))
# General setup
pygame.init()
pygame.mouse.set_visible(0)
clock = pygame.time.Clock()
# Game Screen
screen_width = 400
screen_height = 400
mouse = pygame.mouse.get_pos()
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Sprite Animation")
# Creating the sprites and groups
moving_sprites = pygame.sprite.Group()
crosshair = Player(mouse[0],mouse[1])
enemy_x = ref_x
enemy_y = ref_y
print(enemy_x,enemy_y)
enemy_ = enemy(enemy_x,enemy_y)
moving_sprites.add(enemy_,crosshair)
def get_shot():
moving_sprites.remove(enemy_)
moving_sprites.add(enemy_)
moving_sprites.remove(crosshair)
moving_sprites.add(crosshair)
pygame.display.flip()
while True:
# Player.set_pos(*pygame.mouse.get_pos())
globals()['mouse'] = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
crosshair.attack()
# enemy.checkCollision(enemy,crosshair,enemy_)
# enemy.attack()
# pygame.sprite.spritecollide(Player,enemy,True)
screen.fill((120,220,150))
#this is causing the problem
# get_hit = pygame.sprite.spritecollide(Player,enemy,True)
# Drawing
screen.set_colorkey('white')
moving_sprites.draw(screen)
moving_sprites.update(0.06)
pygame.display.flip()
clock.tick(120)
on function get_shot i want to create my sp_1 at a new place i already tried to change the rect but it didn't work so what can I do to make it work and tell me it get_shot is the best method or not or do i have to create another sprite to make it work also i am a beggener to pygame so tr y to make it easy as possible ...
kill the enemy and spawn a new enemy in a new random position:
enemy_ = enemy(ref_x, ref_y)
moving_sprites.add(enemy_, crosshair)
def get_shot():
global enemy_, ref_x, ref_y
enemy_.kill()
ref_x = ran.randint(18,387)
ref_y = ran.randint(18,387)
enemy_ = enemy(ref_x, ref_y)
moving_sprites.add(enemy_)

Python Pygame how to put the rectangle on the center of the screen

I am really newer to study the python and doing the exercrise
I want to create an rectange or any other graph such as i usepygame.Rect(x,y,w,h)
and set the screen_center by
self.screen_rect=setting.screen.get_rect()
self.screent_center=self.screen_rect.center
but the rectange's center is not in the screen's center
also i want use self.b=self.bullet.get_rect()but it show error
how can i fix it?
here's the code:
#! /usr/bin/python
import pygame as p
import sys
class Setting():
def __init__(self,width,height):
self.w=width
self.h=height
self.flag=p.RESIZABLE
self.color=(255,255,255)
self.speed=1
self.screen=p.display.set_mode((self.w,self.h),self.flag)
p.display.set_caption("Bullet")
self.bullet_s=1
self.bullet_w=100
self.bullet_h=300
self.bullet_c=(0,0,0)
class Bullet(p.sprite.Sprite):
def __init__(self,setting):
super().__init__()
self.screen_rect=setting.screen.get_rect()
self.screent_center=self.screen_rect.center
self.bullet=p.Rect((self.screen_center),(setting.bullet_w,setting.bullet_h)) **<-- not in the center**
self.b=self.bullet.get_rect() **<-- AttributeError: 'pygame.Rect' object has no attribute 'get_rect'**
self.color=setting.bullet_c
self.speed=setting.bullet_s
# self.centery=float(self.bullet.centery)
def bullet_move(self):
self.y -= self.speed
self.bullet.y=self.y
def draw_bullet(self,setting):
self.rect=p.draw.rect(setting.screen,self.color,self.bullet)
def game():
p.init()
setting=Setting(1200,800)
bullet=Bullet(setting)
while True:
for event in p.event.get():
if event.type == p.QUIT:
sys.exit()
setting.screen.fill((255,0,0))
bullet.draw_bullet(setting)
p.display.flip()
game()
This code center rectangle on screen using
self.screen_rect = setting.screen.get_rect()
self.rect.center = self.screen_rect.center
It also moves rectangle when you press UP or DOWN.
It uses KEYDOWN, KEYUP to change speed and it runs move() in every loop and this function uses speed to change position (without checking keys).
It also compare rect.top with screen.top and rect.bottom with screen.bottom to stop rectangle when it touchs border of the screen.
BTW: I also add spaces and empty lines in code to make it more readable.
See: PEP 8 -- Style Guide for Python Code
import pygame as p
class Setting():
def __init__(self, width, height):
self.w = width
self.h = height
self.flag = p.RESIZABLE
self.color = (255, 255, 255)
self.speed = 1
self.screen = p.display.set_mode((self.w, self.h), self.flag)
p.display.set_caption("Bullet")
self.bullet_s = 1
self.bullet_w = 100
self.bullet_h = 300
self.bullet_c = (0, 0, 0)
class Bullet(p.sprite.Sprite):
def __init__(self, setting):
super().__init__()
self.setting = setting
self.screen_rect = setting.screen.get_rect()
self.rect = p.Rect(0, 0, setting.bullet_w, setting.bullet_h)
self.rect.center = self.screen_rect.center
self.color = setting.bullet_c
self.speed = 0 #setting.bullet_s
def move(self):
self.rect.y -= self.speed
if self.rect.top < 0:
self.rect.top = 0
elif self.rect.bottom > self.screen_rect.bottom:
self.rect.bottom = self.screen_rect.bottom
def draw(self):
p.draw.rect(self.setting.screen, self.color, self.rect)
def handle_event(self, event):
if event.type == p.KEYDOWN:
if event.key == p.K_UP:
self.speed = self.setting.bullet_s
elif event.key == p.K_DOWN:
self.speed = -self.setting.bullet_s
elif event.type == p.KEYUP:
if event.key == p.K_UP:
self.speed = 0
elif event.key == p.K_DOWN:
self.speed = 0
def game():
p.init()
setting = Setting(1200,800)
bullet = Bullet(setting)
running = True
while running:
for event in p.event.get():
if event.type == p.QUIT:
running = False
bullet.handle_event(event)
bullet.move()
setting.screen.fill((255, 0, 0))
bullet.draw()
p.display.flip()
p.quit()
game()
This will calculate the position from the top-left corner of the sprite
screen = pygame.display.set_mode((1080, 720))
def getcenter(sprite):
screen_size = screen.get_size()
sprite_size = sprite.image.get_size()
center_x = screen_size[0]/2 + sprite_size[0]/2
center_y = screen_size[1]/2 + sprite_size[1]/2
return (center_x, center_y)
getcenter(spritehere)

Sprite collision test in PyGame (tried: rect and group)

I know there are near 5 or 6 questions similar to this one I'm making, but none of the answers helped me (they probably would if I weren't a complete noob), so I'll try to show my specific case.
I'm trying to make a sprite collision test in PyGame (Python lib) but I can't get it to work, all I get is "False" when colliding, it simply won't work and I can't figure out why, been searching for 2 days straight.
In my game I have the object Player (which I called "dude") and the object Enemy (which I called... "enemy"). The __init__ on both is very similar, and both have rects generated.
This is the __init__ for the player:
class dude(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = self.load_image(SPRITE_PLAYER)
self.X = randint(34,ALTURA-10)
self.Y = randint(34,LARGURA-10)
self.rect = pygame.Rect(self.X,self.Y,25,25) #currently testing this
#self.rect = self.image.get_rect() already tried this
self.speed = SPEED_PLAYER
self.clock = pygame.time.Clock()
For the enemy, I have this:
class enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = self.load_image(SPRITE_ENEMY)
self.X = randint(34,ALTURA-10)
self.Y = randint(34,LARGURA-10)
self.rect = pygame.Rect(self.X,self.Y,25,25)
self.speed = SPEED_ENEMY
self.clock = pygame.time.Clock()
self.xis=1
self.yps=1
When testing collision, these are two methods that return something (wich is already awesome for me, cause there were other tries that only returned errors) but they always return 0's even when I collide then ingame.
The collision should occur when player (controlled by key input) touches the enemy sprite ou image (moved randomly though the stage).
These are the testing methods I have:
print pygame.sprite.collide_rect(player, enemy),pygame.sprite.collide_rect(player, enemy2)
print pygame.sprite.collide_rect(player, enemy),player.rect.colliderect(enemy2)
print player.rect.colliderect(enemy),player.rect.colliderect(enemy2)
(EDIT)
I've been oriented to show more code so the problem can be found, so there it is
(I'm also going to load the sprites globally, passing them as parameters to the objects, tanks for the tip).
Player Object:
# -*- coding: cp1252 -*-
import pygame, os
from pygame.locals import *
from Configs import *
from random import randint
class dude(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = self.load_image(SPRITE_PLAYER)
self.X = randint(34,ALTURA-10)
self.Y = randint(34,LARGURA-10)
self.rectBox()
self.speed = SPEED_PLAYER
self.clock = pygame.time.Clock()
def load_image(self,image_loaded):
try:
image = pygame.image.load(image_loaded)
except pygame.error, message:
print "Impossivel carregar imagem: " + image_loaded
raise SystemExit, message
return image.convert_alpha()
def rectBox(self):
self.rect = self.image.get_rect()
self.image_w, self.image_h = self.image.get_size()
self.rect.move(self.X, self.Y)
self.rect.topleft = (self.X, self.Y)
self.rect.bottomright = (self.X + self.image_w, self.Y + self.image_h)
def update(self,xis,yps,screen):
time_passed = self.clock.tick()
time_passed_seconds = time_passed/1000.0
distance_moved = time_passed_seconds * (self.speed +100) #Distancia = tempo * velocidade
self.X +=xis*distance_moved
self.Y +=yps*distance_moved
screen.blit(self.image, (self.X,self.Y))
if self.X>ALTURA-52:
self.X-=2
elif self.X<30:
self.X+=2
if self.Y>LARGURA-52:
self.Y-=2
elif self.Y<30:
self.Y+=2
Enemy Object:
# -*- coding: cp1252 -*-
import pygame, os
from pygame.locals import *
from Configs import *
from random import randint
class enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = self.load_image(SPRITE_ENEMY)
self.X = randint(34,ALTURA-10)
self.Y = randint(34,LARGURA-10)
self.rectBox()
self.speed = SPEED_ENEMY
self.clock = pygame.time.Clock()
self.xis=1
self.yps=1
def load_image(self,image_loaded):
try:
image = pygame.image.load(image_loaded)
except pygame.error, message:
print "Impossivel carregar imagem: " + image_loaded
raise SystemExit, message
return image.convert_alpha()
def rectBox(self):
self.rect = self.image.get_rect()
self.image_w, self.image_h = self.image.get_size()
self.rect.move(self.X, self.Y)
self.rect.topleft = (self.X, self.Y)
self.rect.bottomright = (self.X + self.image_w, self.Y + self.image_h)
def update(self,screen):
time_passed = self.clock.tick()
time_passed_seconds = time_passed/1000.0
distance_moved = time_passed_seconds * (self.speed +100)
self.X +=self.xis*distance_moved
self.Y -=self.yps*distance_moved
screen.blit(self.image, (self.X,self.Y))
#Maquina de estados finitos para inteligência da movimentação
if self.X>ALTURA-50:
self.X-=2
self.xis=-1
elif self.X<30:
self.X+=2
self.xis=1
if self.Y>LARGURA-50:
self.Y-=2
self.yps=1
elif self.Y<30:
self.Y+=2
self.yps=-1
Main script:
# -*- coding: cp1252 -*-
import pygame, os
from pygame.locals import *
from Configs import *
from Enemy import enemy as e
from Player import dude
from sys import exit
pygame.init()
#Função para carregar imagens
def load_image(image_loaded):
try:
image = pygame.image.load(image_loaded)
except pygame.error, message:
print "Impossivel carregar imagem: " + image_loaded
raise SystemExit, message
return image.convert()
#Funções do Pause
def pause():
drawpause()
while 1:
p = pygame.event.wait()
if p.type in (pygame.QUIT, pygame.KEYDOWN):
return
def drawpause():
font = pygame.font.Font(None, 48)
text1 = font.render("PAUSE", 1, (10, 10, 10))
text1pos = text1.get_rect()
text1pos.centerx = screen.get_rect().centerx
text1pos.centery = screen.get_rect().centery
screen.blit(text1, text1pos)
font = pygame.font.Font(None, 36)
text2 = font.render("Pressione qualquer tecla para continuar", 1, (10, 10, 10))
text2pos = text2.get_rect()
text2pos.centerx = screen.get_rect().centerx
text2pos.centery = screen.get_rect().centery + 50
screen.blit(text2, text2pos)
pygame.display.flip()
#Inicializa tela principal
os.environ["SDL_VIDEO_CENTERED"] = "1"
screen = pygame.display.set_mode((ALTURA, LARGURA),0,32)
bg = load_image(BACKGROUND)
pygame.display.set_caption("Jogo teste para TCC - Top-Down")
#Inicialização do personagem
move_x, move_y = 0, 0
player = dude()
#Inicialização dos inimigos
enemy = e()
enemy2 = e()
#Atribuição de grupos de entidades
inimigos = pygame.sprite.Group()
inimigos.add(enemy)
inimigos.add(enemy2)
personagem = pygame.sprite.Group()
personagem.add(player)
#Objeto clock
clock = pygame.time.Clock()
#Loop principal sprite.get_height() sprite.get_width()
while True:
#Eventos do jogo
for event in pygame.event.get():
#SAIR DO JOGO
if event.type == QUIT:
pygame.quit()
exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
exit()
elif event.key == K_p:
pause()
#TECLAS DE MOVIMENTAÇÃO PERSONAGEM
if event.type == KEYDOWN:
if event.key == K_LEFT:
move_x = -1
elif event.key == K_RIGHT:
move_x = +1
elif event.key == K_UP:
move_y = -1
elif event.key == K_DOWN:
move_y = +1
elif event.type == KEYUP:
if event.key == K_LEFT:
move_x = 0
elif event.key == K_RIGHT:
move_x = 0
elif event.key == K_UP:
move_y = 0
elif event.key == K_DOWN:
move_y = 0
#Posicionamento do background
screen.blit(bg, (0,0))
#Movimentação do personagem
player.update(move_x,move_y,screen)
#Movimentação inimigos
enemy.update(screen)
enemy2.update(screen)
#Teste colisão
#print pygame.sprite.collide_rect(player, enemy),pygame.sprite.collide_rect(player, enemy2)
#print pygame.sprite.collide_rect(player, enemy),player.rect.colliderect(enemy2)
#print player.rect.colliderect(enemy),player.rect.colliderect(enemy2)
#Refresh (por FPS)
pygame.display.update()
Thats it, thanks for the feedback on my post!
If you have a problem with collision detection, it often helps to print the rects of the sprites, e.g. print(player.rect). It'll show you that the rects are never updated and they stay at the same position, and because they're used for the collision detection your sprites won't collide.
To fix your problem you have to set the self.rect.center (or self.rect.topleft) of the sprites to the current self.X and self.Y coordinates in the update methods.
self.rect.center = self.X, self.Y
I recommend to take a look at the pygame.sprite.spritecollide method. Put your enemies into a separate sprite group and then get the collided sprites in this way:
collided_enemies = pg.sprite.spritecollide(player, enemies, False)
for collided_enemy in collided_enemies:
# Do something with the collided_enemy.
Here's a minimal, complete example:
import sys
import pygame as pg
class Player(pg.sprite.Sprite):
def __init__(self, pos, color):
super().__init__()
self.image = pg.Surface((50, 30))
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
player = Player((100, 100), pg.Color('dodgerblue2'))
enemy = Player((300, 100), pg.Color('sienna2'))
enemy2 = Player((200, 300), pg.Color('sienna2'))
all_sprites = pg.sprite.Group(player, enemy, enemy2)
enemies = pg.sprite.Group(enemy, enemy2)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEMOTION:
player.rect.center = event.pos
all_sprites.update()
collided_enemies = pg.sprite.spritecollide(player, enemies, False)
for collided_enemy in collided_enemies:
print(collided_enemy.rect)
screen.fill((50, 50, 50))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()

Categories

Resources