Order class objects are displayed on the screen - pygame

I am very new to Python and Pygame, if anyone can help point me in the right direction I would really appreciate it :)
From what I understand, the order these are displayed determines how they will appear.
I need the "ticker" to appear in front of the other class object, "tickerchart" but I can't seem to figure out why it isn't working.
self.ticker_movement() is first on the list.
Can anyone tell me why the ticker is not showing up on top of the "tickerchart" image when it moves to the same space on the screen?
class Ticker:
def __init__(self, main_ticker_screen):
self.main_ticker_screen = main_ticker_screen
TICKER_IMAGE = pygame.image.load(r'C:\Desktop\Coding\PYTHON\EXPERIMENT\assets\ticker.png').convert_alpha()
self.TICKER = pygame.transform.scale(TICKER_IMAGE, (6, 95))
self.TICKER_x = 1277.5
self.TICKER_y = 841
self.TICKER_direction = 'none'
def move_right(self):
self.TICKER_direction = 'right'
def move_left(self):
self.TICKER_direction = 'left'
def stopmoving(self):
self.TICKER_direction = 'none'
def drawticker(self):
self.main_ticker_screen.fill(BLACK)
self.main_ticker_screen.blit(self.TICKER, (self.TICKER_x, self.TICKER_y))
pygame.display.flip()
def movement(self):
if self.TICKER_direction == 'right':
self.TICKER_x += 22
if self.TICKER_direction == 'left':
self.TICKER_x -= 22
if self.TICKER_direction == 'none':
self.TICKER_x = self.TICKER_x
self.drawticker()
class TickerChart:
def __init__(self, ticker_screen):
self.ticker_screen = ticker_screen
FORTY_ONE_LEFT_IMAGE = pygame.image.load(r'C:\Desktop\Coding\PYTHON\EXPERIMENT\assets\41.png').convert_alpha()
self.FORTY_ONE = pygame.transform.scale(FORTY_ONE_IMAGE, (6, 120))
def draw_tickerchart(self):
#greytickers #left - 40s
self.ticker_screen.blit(self.FORTY_ONE, (1079.5, 816))
pygame.display.flip()
class Game:
def __init__(self):
pygame.init()
self.surface = pygame.display.set_mode((2555, 1005))
pygame.display.set_caption("PBF SCORE")
self.surface.fill(BLACK)
SCOREBOARD_IMAGE = pygame.image.load(r'C:\Desktop\Coding\PYTHON\EXPERIMENT\assets\score_board.png').convert_alpha()
self.SCOREBOARD = pygame.transform.scale(SCOREBOARD_IMAGE, (1236, 700))
self.surface.blit(self.SCOREBOARD, (650, 0))
self.ticker = Ticker(self.surface)
self.ticker.drawticker()
self.tickerchart = TickerChart(self.surface)
self.tickerchart.draw_tickerchart()
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_q:
self.ticker.move_right()
if event.key == K_o:
self.ticker.move_left()
if event.key == K_p:
self.ticker.stopmoving()
elif event.type == QUIT:
running = False
self.ticker.movement()
self.surface.blit(self.SCOREBOARD, (650, 0))
self.tickerchart.draw_tickerchart()
time.sleep(0.65)
if __name__ == "__main__":
game = Game()
game.run()

A possible problem might be that you arent calling for Ticket to be drawn every frame, only them the Game() class is initialized.
Put this in the run loop:
class Game:
def __init__(self):
pygame.init()
self.surface = pygame.display.set_mode((2555, 1005))
pygame.display.set_caption("PBF SCORE")
self.surface.fill(BLACK)
SCOREBOARD_IMAGE = pygame.image.load(r'C:\Desktop\Coding\PYTHON\EXPERIMENT\assets\score_board.png').convert_alpha()
self.SCOREBOARD = pygame.transform.scale(SCOREBOARD_IMAGE, (1236, 700))
self.surface.blit(self.SCOREBOARD, (650, 0))
self.ticker = Ticker(self.surface)
self.ticker.drawticker()
self.tickerchart = TickerChart(self.surface)
self.tickerchart.draw_tickerchart()
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_q:
self.ticker.move_right()
if event.key == pygame.K_o:
self.ticker.move_left()
if event.key == pygame.K_p:
self.ticker.stopmoving()
elif event.type == pygame.QUIT:
running = False
self.ticker.movement()
self.surface.blit(self.SCOREBOARD, (650, 0))
self.tickerchart.draw_tickerchart() # just add this line!!
time.sleep(0.65)
if __name__ == "__main__":
game = Game()
game.run()
I ran this and it seemed to work fine, the ticker (the moving object i presume) does apear and it does move around.
You just need to change ONE line of code in the Game class.

Related

my pygame bullet sprites only fire once each time through loop. would like to fire multiple times

i'm very new to coding, and i'm trying to get a ship to fire multiple bullets, but every time i push spacebar the bullet sort of re-triggers and doesn't make it to the end of the screen. it seems maybe only one instance of my Bullet class is called each time but i don't know how to fix it. here is the code i have going so far:
import sys
import pygame
from pygame.sprite import Sprite
class Sideship():
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((1200,800))
self.screen_rect = self.screen.get_rect()
pygame.display.set_caption("Side Ship")
self.bg_color = (50, 50, 255)
self.bullets = pygame.sprite.Group()
self.jet = Jet()
def run_game(self):
self.jet.rect.x = -20
self.jet.rect.y = 290
self.bullet = Bullet()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
self.jet.moving_down = True
if event.key == pygame.K_UP:
self.jet.moving_up = True
if event.key == pygame.K_SPACE:
self.new_bullet = Bullet()
self.bullets.add(self.new_bullet)
self.new_bullet.rect.x = self.jet.rect.x+200
self.new_bullet.rect.y = self.jet.rect.y+30
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
self.jet.moving_down = False
if event.key == pygame.K_UP:
self.jet.moving_up = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
sys.exit()
self.jet.update()
self.bullets.update()
self.screen.fill(self.bg_color)
self.bullets.update()
for bullet in self.bullets.sprites():
pygame.draw.rect(self.screen, self.new_bullet.bullet_color, self.new_bullet.rect)
self.screen.blit(self.jet.image, self.jet.rect)
pygame.display.flip()
class Jet():
def __init__(self):
self.image = pygame.image.load('jet.bmp')
self.rect = self.image.get_rect()
self.moving_down = False
self.moving_up = False
self.rect.y = float(self.rect.y)
self.rect.x = float(self.rect.x)
def update(self):
if self.moving_down and self.rect.bottom < 801:
self.rect.y += 1.9
if self.moving_up and self.rect.top > -14:
self.rect.y -= 1.4
class Bullet(Sprite):
def __init__(self,):
super().__init__()
self.bullet_width = 30
self.bullet_height = 5
self.bullet_color = (250,250,250)
self.rect = pygame.Rect(0,0, self.bullet_width, self.bullet_height)
def update(self):
self.rect.x += 4
side_ship = Sideship()
side_ship.run_game()
The issue is in the loop, which draws the bullets. When you iterate through the bullets, the current element is referenced by bullet. Hence, you have to draw bullet, rather than self.new_bullet:
pygame.draw.rect(self.screen, self.new_bullet.bullet_color, self.new_bullet.rect)
for bullet in self.bullets.sprites():
pygame.draw.rect(self.screen, bullet.bullet_color, bullet.rect)

How do i make the player look like in the back of the tree? [duplicate]

This question already has answers here:
Pygame image transparency confusion
(1 answer)
How can I make an Image with a transparent Backround in Pygame?
(2 answers)
Closed last year.
i have this python with pygame please don't mind the comment with ignore. every things work fine but i need to know how to make the player lower than the tree. I already tried to display character first and then the tree but the problem is when i import another TILED TMX it has a blackbackground i don't see the setting of being transparent.
brief information: LoadFileMap is where tmx opened and then it display the map here:
makemaps = LoadFileMap.make_map(scroll[0],scroll[1])
display.blit(makemaps,(0,0))
Example
my Main code:
import pygame, sys, os, random, math
clock = pygame.time.Clock()
from pygame.locals import *
import data.engine as e
import data.Mapload as Map
import data.Makemap as M
#Setting of the Windows
pygame.init()
pygame.display.set_caption("Pineapple")
WINDOWS_SIZE = (800, 608)
screen = pygame.display.set_mode(WINDOWS_SIZE,0,32)
display=pygame.Surface((304,256))
# pygame.mouse.set_visible(False)
#Loading the Animations & Particles
e.load_animations('data/images/Entities/')\
#Create random map
# LoadFileMap = Map.createfileworld("data/Map") Ignore
LoadFileMap = M.TilledMap('data/untitled.tmx')
tile_rects=[]
#Variables for the character
'''Player Status'''
for tile_object in LoadFileMap.tmxdata.objects:
if tile_object.name == 'Player':
player = e.entity(tile_object.x,tile_object.y,14,26,'player')
if tile_object.name == 'Tree':
tile_rects.append(pygame.Rect(tile_object.x,tile_object.y,tile_object.width,tile_object.height))
'''Camera'''
true_scroll = [player.x-304/2,player.y-256/2]
'''Character Movement'''
moving_right = False
moving_left = False
moving_up = False
moving_down =False
while True:
display.fill((146,244,255))
#Scroll Camera movement
true_scroll[0] += ((player.get_center()[0]-304/2)-true_scroll[0])/10
true_scroll[1] += ((player.get_center()[1]-256/2)-true_scroll[1])/10
if true_scroll[0] < 0:
true_scroll[0] = 0
if true_scroll[0] > 496:
true_scroll[0] = 496
if true_scroll[1] > 544:
true_scroll[1] = 544
if true_scroll[1] < 0:
true_scroll[1] = 0
scroll = true_scroll.copy()
scroll[0] = int(scroll[0])
scroll[1] = int(scroll[1])
#Rendering the map and rects
makemaps = LoadFileMap.make_map(scroll[0],scroll[1])
display.blit(makemaps,(0,0))
#Character Movement
player_movement = [0,0]
if moving_up == True:
player_movement[1] -= 2
if moving_down == True:
player_movement[1] += 2
if moving_right == True:
player_movement[0] += 2
if moving_left == True:
player_movement[0] -= 2
collision_types= player.move(player_movement,tile_rects)
player.display(display,scroll)
#Buttons
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_d:
moving_right = True
if event.key == K_a:
moving_left = True
if event.key == K_w:
moving_up = True
if event.key == K_s:
moving_down =True
if event.type == KEYUP:
if event.key == K_d:
moving_right = False
if event.key == K_a:
moving_left = False
if event.key == K_w:
moving_up = False
if event.key == K_s:
moving_down =False
screen.blit(pygame.transform.scale(display,WINDOWS_SIZE),(0,0))
pygame.display.update()
clock.tick(60)
this is the file where it renders the map (Makemaps.py)
import pygame, sys, os
from pygame.locals import *
import pytmx
class TilledMap:
def __init__(self, filename):
tm = pytmx.load_pygame(filename, pixelalpha=True)
self.width= tm.width*tm.tilewidth
self.height= tm.height*tm.tileheight
self.tmxdata = tm
def render(self,Surface,scrollx,scrolly):
ti = self.tmxdata.get_tile_image_by_gid
for layer in self.tmxdata.visible_layers:
test = str(layer)
if isinstance(layer,pytmx.TiledTileLayer):
for x, y, gid, in layer:
tile = ti(gid)
if tile:
Surface.blit(tile,(x*self.tmxdata.tilewidth-scrollx,y*self.tmxdata.tileheight-scrolly))
def make_map(self,scrollx,scrolly):
temp_surface = pygame.Surface((self.width,self.height))
self.render(temp_surface,scrollx,scrolly)
return temp_surface
class obstacle:
def __init__(game,x,y,w,h):
self.group = game.Tree
# pygame.sprite.Sprite.__init__(self.groups)
self.game = game
self.rect = pygame(x,y,w,h)
self.x = x
self.y = y
self.rect.x=x
self.rect.y=y

Automatically quits

I'm trying to write a snake game in python but my game automatically quites after inputing out of boundaries code.
I don't understand how the coordinates of my rect are >= than the width of my game, because in the screen they are not. I think that's what happens because the game automatically quits.
I'll post my code, below, to be even more clearer
import pygame
from random import randint
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
class Game():
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Second snake game.")
def __init__(self):
pass
game = Game()
class Player(pygame.sprite.Sprite):
lead_x = game.width/2
lead_y = game.height/2
lead_x_change = 0
lead_y_change = 0
velocity = 0.2
block_size = 10
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def draw_character(self):
self.cube = pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])
def change_x_right(self):
self.lead_x_change += -self.velocity
def change_x_left(self):
self.lead_x_change += self.velocity
def change_y_up(self):
self.lead_y_change += -self.velocity
def change_y_down(self):
self.lead_y_change += self.velocity
def move_x(self):
self.lead_x += self.lead_x_change
def move_y(self):
self.lead_y += self.lead_y_change
def stop_moving_x(self):
self.lead_x_change = 0
def stop_moving_y(self):
self.lead_y_change = 0
class Apple():
lead_x = randint(100, 700)
lead_y = randint(100, 500)
block_size = 10
def __init__(self):
pass
def spawn_apple_after_eaten(self):
self.lead_x = randint(100, 700)
self.lead_y = randint(100, 500)
self.apple = pygame.draw.rect(game.screen, red, [self.lead_x, self.lead_y, self.block_size, self.block_size])
def spawn_apple(self):
self.apple = pygame.draw.rect(game.screen, red, [self.lead_x, self.lead_y, self.block_size, self.block_size])
apple = Apple()
player = Player()
gameExit = False
while not gameExit:
game.screen.fill(white)
apple.spawn_apple()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
player.change_x_left()
player.stop_moving_y()
if event.key == pygame.K_a:
player.change_x_right()
player.stop_moving_y()
if event.key == pygame.K_w:
player.change_y_up()
player.stop_moving_x()
if event.key == pygame.K_s:
player.change_y_down()
player.stop_moving_x()
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
player.stop_moving_y()
if event.key == pygame.K_a or event.key == pygame.K_d:
player.stop_moving_x()
player.move_x()
player.move_y()
player.draw_character()
if player.cube.colliderect(apple.apple):
apple.spawn_apple_after_eaten()
if player.lead_x + player.block_size >= game.width or player.lead_x <= game.width:
gameExit = True
pygame.display.update()
pygame.quit()
quit()
You're setting gameExit to True if the x-coordinate is greater than or equal to game.width or if it's less than or equal to game.width, so it's always True. The second part of the conditional statement should be or player.lead_x <= 0.
if player.lead_x + player.block_size >= game.width or player.lead_x <= 0:
gameExit = True

My Button is not Defined even though I made the object?

I'm receving a button_01 is not defined error. I have a button class which defines how my button is made, and some of the specific functions of it, like defMouseButtonDown. I also a scenes class which organizes my events.
I called mouseButtonDown(button_01) in the processInput of my titleScreen and I had already created the object in the render of my titleScreen. How can I fix this?
import pygame
import os
WHITE = (255, 255, 255)
GREY = (200, 200, 200)
BLACK = (0, 0, 0)
screen = pygame.display.set_mode((800, 400))
###############################
class Button():
def __init__(self, txt, location, action, bg=WHITE, fg=BLACK, size=(80, 30), font_name="Segoe Print", font_size=16):
self.color = bg # the static (normal) color
self.bg = bg # actual background color, can change on mouseover
self.fg = fg # text color
self.size = size
self.font = pygame.font.SysFont(font_name, font_size)
self.txt = txt
self.txt_surf = self.font.render(self.txt, 1, self.fg)
self.txt_rect = self.txt_surf.get_rect(center=[s//2 for s in self.size])
self.surface = pygame.surface.Surface(size)
self.rect = self.surface.get_rect(center=location)
self.call_back_ = action
def draw(self):
self.mouseover()
self.surface.fill(self.bg)
self.surface.blit(self.txt_surf, self.txt_rect)
screen.blit(self.surface, self.rect)
def mouseover(self):
self.bg = self.color
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
self.bg = GREY # mouseover color
def call_back(self):
self.call_back_()
def my_great_function():
print("Great! " * 5)
def my_fantastic_function():
print("Fantastic! " * 4)
def mousebuttondown(button):
pos = pygame.mouse.get_pos()
#for button in buttons:
#if button.rect.collidepoint(pos):
#button.call_back()
if button.rect.collidepoint(pos):
button.call_back()
#########################
class SceneBase:
def __init__(self):
self.next = self
def ProcessInput(self, events, pressed_keys):
print("uh-oh, you didn't override this in the child class")
def Update(self):
print("uh-oh, you didn't override this in the child class")
def Render(self, screen):
print("uh-oh, you didn't override this in the child class")
def SwitchToScene(self, next_scene):
self.next = next_scene
def Terminate(self):
self.SwitchToScene(None)
def run_game(width, height, fps, starting_scene):
pygame.init()
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
active_scene = starting_scene
while active_scene != None:
pressed_keys = pygame.key.get_pressed()
# Event filtering
filtered_events = []
for event in pygame.event.get():
quit_attempt = False
if event.type == pygame.QUIT:
quit_attempt = True
elif event.type == pygame.KEYDOWN:
alt_pressed = pressed_keys[pygame.K_LALT] or \
pressed_keys[pygame.K_RALT]
if event.key == pygame.K_ESCAPE:
quit_attempt = True
elif event.key == pygame.K_F4 and alt_pressed:
quit_attempt = True
if quit_attempt:
active_scene.Terminate()
else:
filtered_events.append(event)
active_scene.ProcessInput(filtered_events, pressed_keys)
active_scene.Update()
active_scene.Render(screen)
active_scene = active_scene.next
pygame.display.flip()
clock.tick(fps)
# The rest is code where you implement your game using the Scenes model
class TitleScene(SceneBase):
def __init__(self):
SceneBase.__init__(self)
def ProcessInput(self, events, pressed_keys):
for event in events:
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
# Move to the next scene when the user pressed Enter
self.SwitchToScene(GameScene())
if event.type == pygame.KEYUP:
print("You are hitting up!")
print(self.next)
if event.type == pygame.MOUSEBUTTONDOWN:
mousebuttondown(button_01)
def Update(self):
pass
def Render(self, screen):
# For the sake of brevity, the title scene is a blank red screen
screen.fill((255, 0, 0))
#Title Creation
myfont = pygame.font.SysFont(("Moyko"), 50)
textImage = myfont.render("Anime Pong", True, (0, 255, 0))
screen.blit(textImage, (100,100))
#Button Creation
button_01 = Button("Great!", (60, 30), my_great_function)
button_01.draw()
def my_great_function():
print("Great! " * 5)
def my_fantastic_function():
print("Fantastic! " * 4)
class GameScene(SceneBase):
def __init__(self):
SceneBase.__init__(self)
def ProcessInput(self, events, pressed_keys):
pass
def Update(self):
pass
def Render(self, screen):
# The game scene is just a blank blue screen
screen.fill((0, 0, 255))
run_game(800, 400, 60, TitleScene())
You're creating the button_01 instance in the Render method as a local variable and that means the ProcessInput method has no access to this variable. You should create the button instance in the __init__ method self.button_01 = Button("Great!", (60, 30), my_great_function), so that all other methods have access to this attribute.
class TitleScene(SceneBase):
def __init__(self):
SceneBase.__init__(self)
# Create the button and the font instance here.
self.button_01 = Button("Great!", (60, 30), my_great_function)
self.myfont = pygame.font.SysFont("Moyko", 50)
def ProcessInput(self, events, pressed_keys):
for event in events:
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
self.SwitchToScene(GameScene())
if event.type == pygame.KEYUP:
print("You are hitting up!")
print(self.next)
if event.type == pygame.MOUSEBUTTONDOWN:
mousebuttondown(self.button_01)
def Update(self):
pass
def Render(self, screen):
screen.fill((100, 0, 0))
textImage = self.myfont.render("Anime Pong", True, (0, 255, 0))
screen.blit(textImage, (100,100))
# Just draw the button here
self.button_01.draw()
I also had to move the pygame.init() call to the top of the program (below the imports), because something went wrong with the font initialization.

how can i check (easily) if two sprites are near each other

how can i check (easily) if two sprites are near each other like they have a 100 pixels difference between them and i need it to be something that doesn't require a lot of if's. the only thing i got to is doing a lot of if's and for my game (hexagon) i need it to be with not so many if's
def is_near(myPearl,bPearl):
if (abs(myPearl.rect.x - bPearl.rect.x) == 100 and abs(myPearl.rect.y - bPearl.rect.y) == 100) or abs(myPearl.rect.y - bPearl.rect.y) == 100 or myPearl.rect.x == bPearl.rect.x:
return 1 # 1 means that the pearl is near it and this pearl is next to the pushed pearl
if abs(myPearl.rect.x - bPearl.rect.x) == 200 or abs(myPearl.rect.y - bPearl.rect.y) == 200 or myPearl.rect.x == bPearl.rect.x:
return 2 # 2 means that the pearl is near it and this pearl is two slots near the pushed pearl
I'd check if the center of a sprite is within the radius of another sprite. You can use pg.math.Vectors and their distance_to method to get the distance and then look if it's less than the radius. In the following example I do this in the circle_collision function which is passed as a callback to pg.sprite.groupcollide. I needed the if left != right: test, so that sprites don't collide with themselves.
import sys
import pygame as pg
from pygame.math import Vector2
from pygame.color import THECOLORS
class Player(pg.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups)
self.image = pg.Surface((50, 30))
self.image.fill(THECOLORS['sienna1'])
self.rect = self.image.get_rect(center=pos)
self.radius = 100
def circle_collision(left, right):
if left != right:
distance = Vector2(left.rect.center).distance_to(right.rect.center)
return distance < left.radius
else:
return False
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
sprite_group = pg.sprite.Group()
player1 = Player((100, 300), sprite_group)
player2 = Player((400, 300), sprite_group)
player3 = Player((100, 100), sprite_group)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEMOTION:
player1.rect.center = event.pos
sprite_group.update()
collided_sprites = pg.sprite.groupcollide(
sprite_group, sprite_group, False, False,
collided=circle_collision)
# Draw everything.
screen.fill(THECOLORS['lemonchiffon4'])
sprite_group.draw(screen)
for collided_sprite in collided_sprites:
pg.draw.circle(screen, THECOLORS['lightcyan1'],
collided_sprite.rect.center,
collided_sprite.radius, 2)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
You could also give the sprites a second, larger rect and look if it collides with the rect of the other sprite. The code is pretty much the same, but pygame.rect.colliderect is used instead of the distance < radius check.
import sys
import pygame as pg
from pygame.color import THECOLORS
class Player(pg.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups)
self.image = pg.Surface((50, 30))
self.image.fill(THECOLORS['sienna1'])
self.rect = self.image.get_rect(center=pos)
self.vicinity_rect = self.rect.inflate(200, 200)
self.vicinity_rect.center = self.rect.center
def update(self):
self.vicinity_rect.center = self.rect.center
def vicinity_collision(left, right):
if left != right:
return left.vicinity_rect.colliderect(right.rect)
else:
return False
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
sprite_group = pg.sprite.Group()
player1 = Player((100, 300), sprite_group)
player2 = Player((400, 300), sprite_group)
player3 = Player((100, 100), sprite_group)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEMOTION:
player1.rect.center = event.pos
sprite_group.update()
collided_sprites = pg.sprite.groupcollide(
sprite_group, sprite_group, False, False,
collided=vicinity_collision)
# Draw everything.
screen.fill(THECOLORS['lemonchiffon4'])
sprite_group.draw(screen)
for collided_sprite in collided_sprites:
pg.draw.rect(screen, THECOLORS['lightcyan1'],
collided_sprite.vicinity_rect, 2)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()