So basically what I know how to do is add a player sprite (make a player class that inherits from pygame.sprite, etc...) this works for me.
What I would like to know how to do is iterate the creation of sprites and add them to the sprite group.
This is because I have a 2 dimensional array and I have a function that reads this and places the "tiles" accordingly in the 2d space, this is to create levels easier.
So what I want this function to do is create these sprites (I guess with a for loop that reads the array ?) and add them to do the group but this doesn't work so I have some questions first:
1)Can you create sprites outside of the init function in a class?
2)What really are sprites, is it a surface coupled to a rect ?
3)And finally do you have an idea of simply how to get this done: If I give you a 2d array, how would you make the function that reads this array and calculates the position (this is okay, I think I have it figured out) and most importantly, make sprites out of the given positions that can then be added to the sprites group.
Thanks in advance
Can you create sprites outside of the init function in a class?
Sure.
What really are sprites, is it a surface coupled to a rect ?
If we talk about pygame's Sprite class: yes.
Such a sprite is basically a Surface (the image attribute) and a Rect (the rect
attribute). They work best together with pygame's Group classes.
And finally do you have an idea of simply how to get this done ....
Just create a nested loop to iterate over the array.
Here's a simple example:
import pygame
pygame.init()
TILESIZE = 64
class Actor(pygame.sprite.Sprite):
def __init__(self, color, pos):
super().__init__()
self.image = pygame.Surface((TILESIZE, TILESIZE))
self.image.fill(pygame.Color(color))
self.rect = self.image.get_rect(topleft = pos)
def main():
data = [
' YUB ',
' G ',
' B ',
' ',
' Y ',
' U ',
]
screen = pygame.display.set_mode((len(data[0]) * TILESIZE, len(data) * TILESIZE))
sprites = pygame.sprite.Group()
colors = {
'G': 'green',
'B': 'black',
'Y': 'yellow',
'U': 'dodgerblue'
}
x, y = 0, 0
for line in data:
for char in line:
if char in colors:
sprites.add(Actor(colors[char], (x * TILESIZE, y * TILESIZE)))
x += 1
x = 0
y += 1
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
return
sprites.update()
screen.fill((100, 100, 100))
sprites.draw(screen)
pygame.display.flip()
main()
You can find another example here.
Related
I'm building a pong game trying to get better at programming but Im having trouble moving the ball. When the move_right method is called the ellipse stretches to the right instead of moving to the right. I've tried putting the ball variable in the init method but that just makes it not move at all even though the variables should be changing on account of the move_right method. I have also tried setting the x and y positions as parameters in the Ball class,but that just stretches it also.
I don't understand why when I run the following code the ball I'm trying to move stretches to the right instead of moves to the right. Can someone explain why this is happening? I have tried everything I can think of but i can't get it to do what I want.
import pygame,sys
import random
class Ball:
def __init__(self):
self.size = 30
self.color = light_grey
self.x_pos = width/2 -15
self.y_pos = height/2 -15
self.speed = 1
#self.ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
def draw_ball(self):
ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
pygame.draw.ellipse(screen,self.color,ball)
def move_right(self):
self.x_pos += self.speed
class Player:
def __init__(self,x_pos,y_pos,width,height):
self.x_pos = x_pos
self.y_pos = y_pos
self.width = width
self.height = height
self.color = light_grey
def draw_player(self):
player = pygame.Rect(self.x_pos,self.y_pos,self.width,self.height)
pygame.draw.rect(screen,self.color,player)
class Main:
def __init__(self):
self.ball=Ball()
self.player=Player(width-20,height/2 -70,10,140)
self.opponent= Player(10,height/2-70,10,140)
def draw_elements(self):
self.ball.draw_ball()
self.player.draw_player()
self.opponent.draw_player()
def move_ball(self):
self.ball.move_right()
pygame.init()
size = 30
clock = pygame.time.Clock()
pygame.display.set_caption("Pong")
width = 1000
height = 600
screen = pygame.display.set_mode((width,height))
bg_color = pygame.Color('grey12')
light_grey = (200,200,200)
main = Main()
#ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
#player = pygame.Rect(width-20,height/2 -70,10,140)
#opponent = pygame.Rect(10,height/2-70,10,140)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
#pygame.draw.rect(screen,light_grey,player)
#pygame.draw.rect(screen,light_grey,opponent)
#pygame.draw.ellipse(screen,light_grey,ball)
main.draw_elements()
main.move_ball()
main.ball.x_pos += main.ball.speed
pygame.display.flip()
clock.tick(60)
You have to clear the display in every frame with pygame.Surface.fill:
while True:
# [...]
screen.fill(0) # <---
main.draw_elements()
main.move_ball()
main.ball.x_pos += main.ball.speed
pygame.display.flip()
# [...]
Everything that is drawn is drawn on the target surface. The entire scene is redraw in each frame. Therefore the display needs to be cleared at the begin of every frame in the application loop. The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
I created an object called "alien" in my game. Uploaded the image for "alien" and used "get_rect()" to set its rect attributes.
Now I want to change the x-coordinate value of "alien". Which of the following two ways is correct?
alien.x = ...... or alien.rect.x = ......
I saw in a textbook that the following codes are used:
alien.x = alien_width + 2 * alien_width * alien_number
alien.rect.x = alien.x
Why didn't the author directly use alien.rect.x to change the x-coordinate value of "alien"? Like:
alien.rect.x = alien_width + 2 * alien_width * alien_number
Why does there have to be alien.x?
Unfortunately the answer is "it depends". Some people's code maintains the position of the object at an internal x and y, using a rect to handle collisions. Other code just maintains the rect, using the rect.x and rect.y if a single position is (ever) needed.
It's up to you really, but my advice is to keep it all inside a PyGame Rect, as this has benefits of easy collision detection, should you wish to use that down the track.
class Alien:
def __init__( self, x, y, image ):
self.image = image
self.rect = image.get_rect() # copy the image dimensions
self.rect.x = x
self.rect.y = y # move to location
def draw( self, window ):
window.blit( self.image, self.rect ) # paint it
When it's time to move the Alien, you can just as easy adjust the rectangle as an x and y
class Alien:
...
def moveBy( self, by_x, by_y ):
self.rect.move_ip( by_x, by_y )
def moveTo( self, x, y ):
self.rect.x = x
self.rect.y = y
Perhaps the author thought that having a separate x and y made the code easier to understand. This is a paramount reason that effects programming style. Program code is read many times more often than it is written, so often extra variables are included to illustrate the program flow better.
For example, like checking a mouse-click-event:
for event in pygame.event.get( ):
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONUP:
handleGameClick( mouse2Board( event.pos ) ) # <-- HERE
Adding extra variables documents what's going on:
elif event.type == pygame.MOUSEBUTTONUP:
mouse_click_coord = event.pos
game_board_coord = mouse2Board( mouse_click_coord )
handleGameClick( game_board_coord )
Here it tells the reader that event.pos is a co-ordinate (so probably a pair of values), and is from the mouse. Then it reenforces that the co-ordinate is then converted into a game-board space before being passed out to handleGameClick() for processing.
The two pieces of code have exactly the same outcome (and probably execution speed), but the second is much easier to follow.
IMHO one should ideally write code such that someone unfamiliar with the language (but still a programmer) can understand it without too much trouble. This is why in my answers you wont see much "pythonic" loop-in-list creation like:
[[col +1 for col in row] for row in a] # Taken from 10 vote answer
Because unless your very familiar with python syntax, it's unreadable.
I am brand new to Pygame and am making a game for my A-level course. I am trying to have multiple bats that I can spawn and collide with. I am using Pygames mask function for 'pixel perfect collision' but I cannot get multiple bats to spawn at the same time with the collision system also working. I tried using groups but I haven't been able to get this to work. Does anyone know how to fix my code/ a better way around this problem? Thanks! The relevant code is below...
class Bat(pygame.sprite.Sprite):
def __init__(self, bat_x, bat_y):
pygame.sprite.Sprite.__init__(self)
self.bat1 = pygame.image.load("Sprites\Bat_enemy\Bat-1.png").convert_alpha() # For hit registration for bat
self.bat1 = pygame.transform.scale(self.bat1, (80, 70))
self.bat_mask = pygame.mask.from_surface(self.bat1)
self.bat_rect = self.bat1.get_rect()
self.bat_x = bat_x
self.bat_y = bat_y
bats = pygame.sprite.Group()
Then in main loop:
num_of_bats = [1]
#Bat#
for i in num_of_bats:
bat_x = (random.randint(0, 600))
bat_y = (random.randint(0, 600))
bat = Bat(bat_x, bat_y, i)
bats.add(bat)
for bat in bats:
offsetP2B = (int(x - batx), int(y - self.baty)) #Player to Bat
resultP2B = bat_mask.overlap(player_mask, offsetP2B)
First get rectangle based collision working, then worry about the bitmask accuracy!
There's a couple of problems with your Sprite. The big one is that PyGame uses sprite.image to draw the bitmap. Your sprite code is using bat1 instead. It also needs to position the sprite.rect to the co-ordinate of the Bat. Furthermore, the collision mask must be called mask, and the sprite's collision/position pygame.Rect must be called rect.
I'm not sure if it's just a paste-o, but the sprite group definition shouldn't be inside the Sprite class.
So ... with a few minor fixups:
class Bat(pygame.sprite.Sprite):
def __init__(self, bat_x, bat_y, bat_image):
pygame.sprite.Sprite.__init__(self)
self.image = bat_image
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface( self.image )
self.rect.centre = ( bat_x, bat_y )
def update( self ):
# TODO: code to make this bat move/flat whatever
pass
There's only minor differences here. It's better to load the image in once, outside the sprite class, than loading it in hundreds(?) of times - once for each bat.
Now it's pretty easy to make a colony of bats:
import os.path
START_BAT_COUNT = 30
BAT_IMAGE_PATH = os.path.join( 'Sprites', 'Bat_enemy', 'Bat-1.png' )
# group to hold all the bat sprites
all_bats = pygame.sprite.Group()
# Going Batty!
bat_image = pygame.image.load( BAT_IMAGE_PATH ).convert_alpha()
for i in range( START_BAT_COUNT ):
bat_x = (random.randint(0, 600))
bat_y = (random.randint(0, 600))
new_bat = Bat( bat_x, bat_y, bat_image )
all_bats.add( new_bat )
The in your main loop:
# move every bat
all_bats.update()
...
# paint every bat
all_bats.draw( screen )
I need to store a Circle in a variable but after I've done that it has turned into a rect
circle_1 = pygame.draw.circle(screen, (0, 0, 0), (300, 300), 30)
Print(circle_1)
the print returns
<rect(270, 270, 60, 60)>
but I can't work with that.
My circle is predefined but it won't show it on the canvas, here is an example of the problem
> import pygame, sys
>
>
> pygame.init() screen = pygame.display.set_mode((600, 600))
> predefined_circle = pygame.draw.circle(screen,(0, 0, 0),(300, 300), 30)
>
> def update():
> screen.fill((200, 0, 0))
> while 1:
> for event in pygame.event.get():
> if event.type == pygame.QUIT: sys.exit()
> # It shows my circle if I dirctly tip pygame.draw.circle(screen,(0, 0, 0),(300, 300), 30) into it
> predefined_circle
> pygame.display.update()
>
> update()
So that you can better relate to what I'm trying to achieve here is the code of what I'm doing but it is not necessary to read as I've already tried to explain it as best as I can above.
Please note the comments should explain everything that the block of code below it is doing.
# Creating the canvas which can paint any wanted Object from another class
class Canvas:
# Initialising the screen and setting all needed variables
def __init__(self, painting):
pygame.init()
self.screen_size = (600, 600)
self.background = (25, 255, 255)
self.screen = pygame.display.set_mode(self.screen_size)
self.paint = painting
# Let the user set the name of the canvas
def set_screen_name(self):
return self.screen
# Draw the everything you want to
def update(self):
# Paint the canvas
self.screen.fill(self.background)
# Make the game be quittable
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# Draw the defined Circle and then update the Canvas
# it only draws a circle if directly tip pygame.draw.circle(surface, color, position, radius)
self.paint
pygame.display.update()
# Draw any circle you like
class Cir:
# Get all the required Information's to Draw a circle
def __init__(self, canvas, what_color, position, radius, line=0):
self.can = canvas
self.color = what_color
self.pos = position
self.r = radius
self.line = line
self.cir = None
# Create the circle with the acquired Information's
def create(self):
self.cir = pygame.draw.circle(self.can, self.color, self.pos, self.r, self.line)
return self.cir
# So far there is no Surface for the Cir class
# And there is no Object that cloud be painted for the Canvas class
# I initialise a canvas instance without anything that needs to be painted
get_surface = Canvas(None)
# Now I can access set_screen_name from the Canvas class and give the surface a name
# Which the Cir class can now use as a surface
screen = get_surface.set_screen_name()
c1 = pygame.draw.circle(screen, (0,0,0), (300, 300), 30)
print(c1)
# I'm initialising a circle
init_circle = Cir(screen, (0, 255, 0), (300, 300), 30)
# Create the initialised circle
circle_1 = init_circle.create()
# Give the Canvas class the created circle
paint = Canvas(circle_1)
# Draw the circle
paint.update()
My circle turns to a rect.
Actually, no, it doesn't. As per the documentation for those drawing functions, the intent of the calls is to draw something immediately, not to give you an object you can draw later:
Draw several simple shapes to a Surface.
From analysis of your question, it sounds like you believe that you are storing the act of drawing the circle so that it can be done later. That is not the case. Instead, what you are doing is actually drawing the circle and saving the result of that drawing action - evaluating the result later on will not actually draw, or redraw, the circle.
So, if the draw function is not returning something for later drawing, what is it returning? That can also be found in the above-mentioned documentation:
The functions return a rectangle representing the bounding area of changed pixels.
In other words, it's telling you the smallest rectangle that was changed by the drawing action - this will be a square with sides the same length as the diameter and centered around the same point.
Obviously, the authors of PyGame thought this information may be handy for some purpose, just not the purpose of redrawing the circle :-)
One way to do what you're trying to achieve would be to simply have a function to draw the "predefined" circle and call that instead of trying to evaluate the rectangle returned from a previous call.
I have a pygame menu where i have drawn some buttons, which represent the level difficulty of my game. For user convenience, i have made a sprite which indicates which level-button is selected(think of it as a light green frame around the button). Now, if i have a solid color as my background, i can just fill the frame with the bg color. But i wanna have a custom image. However i am not sure how to do the deleting stuff with this image. I dont want to have to do a surface.blit(bgImage, surface.get_rect())
in every while-loop. Is there any way to tell pygame to blit just part of the image? So the end-result is still fine-looking. Here is my code when i have a color as the background
(please note that my question does not apply only to this scenario, its more of a general way as to blitting part of an image, without having to rely on cropping the image using 3rd party software like paint(net), photoshop etc.):
#class for the highlight sprite that appears when a level button is clicked
class HighLightImage(Sprite):
def __init__(self, spriteX, spriteY, width = 180, height = 60):
Sprite.__init__(self)
self.rect = pygame.Rect(spriteX, spriteY, width, height)
self.image = pygame.image.load("highlight.png")
#function to draw the highlight sprite, after deleting its older position.
def draw(self, newSpriteX, newSpriteY):
#due to technical issues the following method is using 4 dirty sprite deletions.
surface.fill(bgCol, (self.rect.x, self.rect.y, self.rect.width, 10))
surface.fill(bgCol, (self.rect.x, self.rect.y + self.rect.height-10, self.rect.width, 10))
surface.fill(bgCol, (self.rect.x, self.rect.y, 10, self.rect.height))
surface.fill(bgCol, ( self.rect.x + self.rect.width-10, self.rect.y, 10, self.rect.height))
self.rect.x = newSpriteX
self.rect.y = newSpriteY
surface.blit(self.image, self.rect)
And here is the main while-loop
def mainIntro():
#snake image
snakeImg = pygame.image.load("snakeB.png")
snakeImg = pygame.transform.scale(snakeImg, (150,200))
#highlight obj
hlObj = HighLightImage(0, 0)
#starting level = 1
levels = 1
#initial fill
surface.fill(bgCol)
intro = True
#start button
startButton = StartButton(WIDTH/2-330, HEIGHT - 150)
startButton.draw("Start")
#Exit button
exitButton = ExitButton(WIDTH/2+110, HEIGHT - 150)
exitButton.draw("Exit")
#level buttons
easyLvl = EasyLevelButton( 65, HEIGHT/2 )
easyLvl.draw("Easy")
midLvl = MediumLevelButton( 320, HEIGHT/2 )
midLvl.draw("Medium")
hardLvl = HardLevelButton( 570, HEIGHT/2 )
hardLvl.draw("Hard")
instructions()
surface.blit(snakeImg, (WIDTH/2-75, HEIGHT - 250))
while intro:
for ev in pygame.event.get():
# X exit event
if ev.type == QUIT:
pygame.quit()
sys.exit()
if ev.type == MOUSEMOTION:
startButton.hover()
exitButton.hover()
easyLvl.hover()
midLvl.hover()
hardLvl.hover()
if ev.type == MOUSEBUTTONDOWN:
if easyLvl.clicked():
levels = 1
if midLvl.clicked():
levels = 2
if hardLvl.clicked():
levels = 4
#button exit event
elif exitButton.clicked():
pygame.quit()
sys.exit()
elif startButton.clicked():
intro = False
#highlight frame, according to level-button chosen
if levels == 1:
hlObj.draw(easyLvl.x-10, easyLvl.y-10)
elif levels == 2:
hlObj.draw(midLvl.x-10, midLvl.y-10)
elif levels == 4:
hlObj.draw(hardLvl.x-10, hardLvl.y-10)
update()
return levels
Finally here is an image of the end result :
P.s In the above code snippets i have not included the button classes, and the global variables like colors, width, height etc., since i dont think they are relevant with what i want to accomplice. Feel free to correct my code, and/or suggest improvements.
As #cmd said above, the area param would be a good option, but for more information, try the pygame docs or have a look at this question or try pygame.transform.chop()
Try the code below:
pygame.init()
size = width, height = 1200, 800
screen = pygame.display.set_mode(size)
image = pygame.image.load("example.png")
rect = image.get_rect()
cropx,cropy = 100,10 #Change value to crop different rect areas
cropRect = (cropx, cropy, rect.w,rect.h)
while(True):
for event in pygame.event.get():
if(event.type == pygame.QUIT):
pygame.quit()
sys.exit()
screen.blit(image,cropRect,cropRect)
pygame.display.update()