import pygame, random
pygame.init()
screen = pygame.display.set_mode((700,500))
ball = pygame.image.load('C://python32/ball.jpg')
brick = pygame.image.load('C://python32/brick.jpg')
rect1 = ball.get_rect()
rect2 = brick.get_rect()
screen.fill((255,255,198))
screen.blit(ball,rect1)
screen.blit(brick,rect2)
pygame.display.flip()
if rect1.colliderect(rect2):
x=random.randrange(0,550)
y=random.randrange(0,350)
rect2.move(x,y) #<-------This part
pygame.display.flip()
I have 2 images ball and brick. When I load them on pygame the 2 images collide. So the if rect1.colliderect(rect2) should work. I tested that by putting is a print function. But the rect2.move dosen't work it doesn't show the change on the pygame. What is wrong?
pygame.Rect.move creates a new rect object with the new position which you have to assign to a variable if you want to use it later.
If you just want to modify the existing rect, you can call the move_ip method (ip stands for in-place), so that the rect is still the same object with a new position.
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()
When i was making background with screen.fill, my code was checking collision of hero with a lot of projectiles - and program still wasn't lagging. But when i decided to add drawn background (3600x1200 pix) as sprite, and fps fell down to about 20 fps. I removed all projectiles, but fps is still enormously low. Such big background was chosen for moving it, instead of moving main hero. Here is my code and the problematic line displaying the background (everything works fine without it).
#import modules
import pygame as pg
from hero import Hero
#self-made classes
from obstruction import Obstruction
from setting import Settings
import gf
from time import sleep
**from back_ground import Background**
from command_block import Command_Line
#main function
def run_game():
#pygame activation
pg.init()
#window settings
settings = Settings()
screen = pg.display.set_mode((settings.screen_width,settings.screen_height))
pg.display.set_caption(settings.caption)
hero = Hero(0, 0, "Right", 1/240, pg.image.load('images/hero/hero1.png'), 128, 16, 15, 0.08, 0.2, settings,27)
bg = Background('images/sky.png', [0,0])
cl = Command_Line(hero)
#class creating
projectiles = []
#here was some projectile creating
#variables initialization etc.
work=True
myfont = pg.font.SysFont('TimesNewRoman',int(settings.screen_width*0.025))
#main loop
while work:
sleep()
hero.is_running = False
hero.idle = True
gf.check_events(hero, projectiles, settings, cl)
gf.jump(hero, projectiles)
#updating hero rect due to coordinate changing and hero image due to direction changing
hero.update_rect()
hero.orientation()
#screen filling with backgroung color
screen.fill([255, 255, 255])
screen.blit(bg.image, bg.rect)
#displaying projectiles(walls,floor,etc.)
for projectile in projectiles:
projectile.display(screen)
#displaying hero image and all his atributes
hero.display(screen, myfont)
gf.command_block_draw(settings,myfont,screen,cl)
#test string for displaying problematic variables
gf.test_string_draw(settings,myfont,hero,screen)
#display updating
pg.display.flip()
#quit
pg.quit()
#running game
run_game()
Line:
screen.blit(bg.image, bg.rect)
BackGround class:
import pygame as pg
class Background(pg.sprite.Sprite):
def __init__(self, image_file, location):
pg.sprite.Sprite.__init__(self)
self.image = pg.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
Make sure to convert() the image.
Changing this one line of code should increase your performance substantially.
It processes the Surface into a format pygame likes up front, speeding up all the consequent blits.
self.image = pg.image.load(image_file).convert()
When I run this code it does not display the sprite on the screen . just a blank screen I have tried everything I can think of to get this to work .Some help would be much appreciated.
I have tried everything I can think of to get this to work. what I'm trying to do is create my sprites with a rect attribute.
import pygame
pygame.display.init()
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
x = 300
y = 500
x1 = 100
y1 = 200
image1 = pygame.sprite.Sprite()
image1.image = pygame.image.load("picy.png").convert_alpha()
image2 = pygame.sprite.Sprite()
image2.image = pygame.image.load("picy1.png").convert_alpha()
image1_rect = image1.image.get_rect(topleft=(x,y))
image2_rect = image2.image.get_rect(topleft=(x1,y1))
screen.blit(image2_rect,(x1,y1))
screen.blit(image1_rect,(x,y))
pygame.display.update()
I expect it to put my two sprites on the screen and when they touch for them to register a hit.
From the docs:
blit()
draw one image onto another
blit(source, dest, area=None, special_flags = 0) -> Rect
Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. Dest can either be pair of coordinates representing the upper left corner of the source. A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit.
The blit method takes as first argument a Surface, not a Rect. The Surface is your image.
Try with:
screen.blit(image2.image, dest=image2_rect)
screen.blit(image1.image, dest=image1_rect)
By the way, you may also wish to make the rectangles attributes of the Sprite instances, instead of separate instances:
image1.rect = image1.image.get_rect(topleft=(x,y))
image2.rect = image2.image.get_rect(topleft=(x1,y1))
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 am working on this project to move a sprite, but I can't seem to figure out how to move a sprite to the right as well as move it downwards. Any thoughts?
Here is my program:
import pygame
import time
import sys
pygame.init()
# Set up window
screen = pygame.display.set_mode((320, 240))
# Load an image
rocket = pygame.image.load("rocket.png")
rocketrect = rocket.get_rect()
x_coord = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
screen.fill((0,0,0))
screen.blit(rocket, rocketrect)
pygame.display.flip()
x_coord += 1
rocketrect.centerx = x_coord
In your method of mving the sprite, you change the coordinatses (x) and then assign it to the centerx of the images rectangle. If you want to keep this kind of method (changing and assigning), and also move the image down, you will need to give a y value. For example
# Define y variable
y_coord = 0
# Your code
…
y_coords += 1
rocketrect.centery = y_coord
This works similarly to how you moved your x_coords, but in total, the program is a bit basic and is not how programmers (or at least me) usually code. Another person might used a tuple for the location, along with making a rocket class. There are also some other ways to move the sprite, such as the .move() or .move_ip() that I would suggest. But it's up to you.