Reputation: 461
I recently came across something called PyGame Sprite's and would like to learn to create Pygame sprites as it will be very useful for my project.
Here is my code:
import pygame
import sys
from pygame.locals import *
white = (255,255,255)
black = (0,0,0)
objs = []
MAIN_BUTTON = 1
class Pane(pygame.sprite.Sprite):
def __init__(self):
pygame.init()
self.font = pygame.font.SysFont('Arial', 25)
pygame.display.set_caption('Box Test')
self.screen = pygame.display.set_mode((600,400), 0, 32)
self.screen.fill((white))
pygame.display.update()
def addRect(self):
self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
pygame.display.update()
def addText(self):
self.screen.blit(self.font.render('Hello', True, (black)), (250, 115))
pygame.display.update()
def delText(self):
self.screen = pygame.display.set_mode((600,400), 0, 32)
self.screen.fill((white))
pygame.display.update()
def mousePosition(self): #Ignore this.
global clickPos
global releasePos
for event in pygame.event.get():
if event.type == MAIN_BUTTON:
self.Pos = pygame.mouse.get_pos()
return MAIN_BUTTON
else:
return False
def groupSp(self):
pygame.sprite.Sprite.__init__(self, group)
if __name__ == '__main__':
Pan3 = Pane()
Pan3.addRect()
Pan3.addText()
Pan3.mousePosition()
group = pygame.sprite.Group(Pan3.addRect(), Pan3.addText())
Pan3.groupSp()
group.sprites()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit();
So I was wondering if you could group both addRect(self) and addText(self) as Sprite? If so is there a way of then being able to place it randomly on a screen? Or is there a better way of doing this?
In advance Thank-You for your time. :)
Upvotes: 0
Views: 133
Reputation: 7501
You only want to call pygame.display.update()
once per game loop. ( Right now, if you create two panes, and call addText() twice on each, that's 4 updates per loop. )
if you could group both addRect(self) and addText(self) as Sprite?
You can render them to the same surface, which later is drawn on screen.
If so is there a way of then being able to place it randomly on a screen?
To place randomly, use random.randint()
- https://stackoverflow.com/a/10667252/341744
pygame.sprite.Sprite.__init__(self, group)
This should be called in your constructor Pane.__init__
Upvotes: 1