How to centre an image in pygame? [duplicate] - python

This question already has an answer here:
How to center an image in the middle of the window in pygame?
(1 answer)
Closed 6 months ago.
I am using python 2.7, I would like to know if there is a way to centre an image in pygame. I have set the screen to fullscreen, is this possible? If it helps i will attach the code, thanks.
import pygame
import os
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
_image_library[path] = image
return image
pygame.init()
screen = pygame.display.set_mode((0, 0))
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill((0, 0, 0))
screen.blit(get_image('sw.png'), (0, 0)
pygame.display.flip()
clock.tick(60)

Yeah, it's possible.
You have to create a rect object of the image:
image = "insert image"
rect = image.get_rect ()
And then:
rect.center = ("coordinates of center")

This StackOverflow question might be able to help you.
Pygame Image position
Basically though, you'd get the image rectangle. From there there are a lot of useful functions you can call to position it.

Related

I would like to describe a parabola when a battle ship shoot a bullet with pygame [duplicate]

This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 2 years ago.
I'm trying to animate a ball getting thrown, and I want it to rotate an follow a smooth, parabolic path at the same time. However, I just can't seem to get pygame.transform.rotate() to cooperate.
Here's what I've tried so far:
import pygame
screen = pygame.display.set_mode((500, 500))
timer = pygame.time.Clock()
ball = pygame.sprite.Sprite()
ball.image = pygame.image.load("throwball.png")
ball.image = pygame.transform.scale(ball.image, (48,48))
ball.rect = ball.image.get_rect(topleft = (50,50))
ball.orig_image = ball.image
rotaterect = ball.rect
for i in range(60):
#pygame.draw.rect(screen, Color(255,255,255), ball.rect)
ball.image = pygame.transform.rotate(ball.orig_image, i*20)
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
screen.blit(ball.image, ball.rect)
pygame.display.update()
timer.tick(60)
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
while 1:
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
Whenever I run the code, the ball moves in an irregular pattern. I made a second rect to try to keep the positioning under control, but the ball ends up forming a path like this:
Obviously there's something wrong with the positioning on each frame, but I'm not sure why any of the frames would be out of place, since their location is determined by their center point.
Here's the ball image:
It's 16x16 (square), so I'm dumbfounded as to why the image isn't following a clean path.
Note, a rotated image varies in size. See How do I rotate an image around its center using Pygame?.
Get the rectangle of the rotated image and set the center of the rectangle by the center of the helper rectangle rotaterect. This causes that the image is symmetrically aligned around the center.
You missed to update the ball.rect to the actual size of the rotated image:
ball.rect = ball.image.get_rect()
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
Example:
for i in range(60):
ball.image = pygame.transform.rotate(ball.orig_image, i*20)
ball.rect = ball.image.get_rect()
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
screen.blit(ball.image, ball.rect)
pygame.display.update()

pygame.transform.rotate() acting weird [duplicate]

This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 2 years ago.
I've seen fixes to this problem elsewhere on StackOverflow, but I'm too new to this language to apply them to mine.
I'm making a Surface, drawing stuff on it, and then rotating it. The result is the same as this guy's issue:
The rectangle moves erratically as it rotates. Is this fixable, or must I change my approach?
from pygame import *
import sys
def drawShip(pos,angle,width,height,surface):
canvas = Surface((width,height))#A canvas to draw the ship on
r = ((1),(1),width,height)#A placeholder rectangle
draw.rect(canvas,(255,0,0),r)#Draw r on the surface
canvas = transform.rotate(canvas,angle)#Rotate the canvas
surface.blit(canvas,((pos[0] - width/2),(pos[1] - height/2)))#Draw the canvas onto the main surface
s = display.set_mode((500,500))#Create the main surface
i = 0
while True:
for e in event.get():
if e.type == QUIT:
sys.exit()
if e.type == KEYDOWN:
i += 5
drawShip((250,250),i,100,100,s)#Draw a ship
display.flip()#Update the display
See How do I rotate an image around its center using Pygame?.
Get a rectangle with the size of the rotated Surface by get_rect() and set the center of the rectangle to the desired position by an key word argument. Use the rectangle to draw the Surface. The 2nd argument of blit can be a Rect object, which specifies the destination location:
rot_rect = canvas.get_rect(center = pos)
surface.blit(canvas, rot_rect)
Minimal example:
from pygame import *
import sys
def drawShip(pos, angle, image, surface):
rot_image = transform.rotate(image, angle)
rot_rect = rot_image.get_rect(center = pos)
surface.blit(rot_image, rot_rect)
init()
s = display.set_mode((500,500))
clock = time.Clock()
image = Surface((100, 100), SRCALPHA)
image.fill((255, 0, 0))
angle = 0
while True:
clock.tick(60)
for e in event.get():
if e.type == QUIT:
sys.exit()
if any(key.get_pressed()):
angle += 1
s.fill(0)
drawShip((250,250), angle, image, s)
display.flip()

Very simple PyGame very slow [duplicate]

This question already has answers here:
Lag when win.blit() background pygame
(2 answers)
Closed 2 years ago.
I want to make a (a bit bigger) game in PyGame, but even with this simple code I just get arround 10 fps instead of 60? Here's the code:
import pygame
res = 1280,720
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")
background = pygame.transform.smoothscale(pygame.image.load("Background.png"), res)
a = 0
while True:
pygame.time.Clock().tick(60)
display.fill((0,0,0))
a += 10
display.blit(background, (0,0)) #Without this line: arround 20 fps
pygame.draw.rect(display,(255,0,0), (a,8,339,205))
pygame.display.update()
pygame.quit()
What am I doing wrong?
Thank you!
Try the following optimizations:
Use the convert() method on your image pygame.image.load("Background.png").convert()). This makes the animation about 5 times faster.
Instead of re-blitting entire background every frame, only update the changed parts of the screen.
You don't need to clear the screen before drawing the background.
Use the same Clock instance every frame.
Here's the code:
import pygame
pygame.init()
res = (1280, 720)
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")
background = pygame.transform.smoothscale(pygame.image.load(r"E:\Slike\Bing\63.jpg").convert(), res)
a = 0
clock = pygame.time.Clock()
display.blit(background, (0, 0))
pygame.display.update()
while True:
clock.tick(60)
rect = (a,8,339,205)
display.blit(background, rect, rect) # draw the needed part of the background
pygame.display.update(rect) # update the changed area
a += 10
rect = (a,8,339,205)
pygame.draw.rect(display, (255,0,0), rect)
pygame.display.update(rect) # update the changed area

pygame not displaying my image

i started learning pygame and i followed some tutorials to make simple hello world project and it works but when i do it my self trying to display my image on the window nothing happen!
this is my code
__author__ = 'mohammed'
import sys
import pygame
import color
# -----------setup------------------------
pygame.init() # start pygame
screensize = (800, 600) # variable that we will use to declare screen size
screen = pygame.display.set_mode(screensize) # set the screen size
pad = pygame.image.load('2.png')
x = 100
y = 100
# -----------setup------------------------
# -------------------main loop------------
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(pad, (x, y))
screen.fill(red)
pygame.display.update()
i am importing my file that contain colors and their rgb :
red = (255, 0, 0)
It looks like you're filling the screen after the image is drawn, covering the image. Try switching the order of the rows:
screen.blit(pad, (x, y))
and
screen.fill(red)

Is it possible to stretch an image in pygames?

Is it possible to stretch an image in pygame using an event to trigger it?
Like say I have a person and I want his eyes to popout like this
when I press a button and I am using surface.blit(eyes=pygame.image.load('eyes')) for the eyes.
Can i stretch the eye image like the picture in this link?
There is a solution to this problem that allows you to stretch the eyes to the exact width you want, but it may make the eyes very deformed... (nevermind, the original image has pretty deformed eyes anyway.)
From the Pygame doc on pygame.transform.scale:
scale(Surface, (width, height), DestSurface = None) -> Surface
We also use image.get_height() so the user does not have to get the height themselves.
So you would do something like this (wrapped in a function):
def stretchEyes(image, newWidth):
return pygame.transform.scale(image, (image.get_height(), newWidth))
eyes = stretchEyes(eyes, image.get_width()*3) # Stretch to three times width
# Blitting takes in the top left position, so we don't need to do any maths here!
screen.blit(eyes, (x,y))
A better approach would be to have two images one for the actual image and one where the eyes are stretched. Draw the second image whenever you need instead of the first image.
import pygame
from pygame.locals import *
screen = pygame.display.set_mode((540, 480))
runner1 = pygame.image.load('./runner1.jpg').convert()
runner1_rect = runner1.get_rect(center=(270, 240))
runner2 = pygame.image.load('./runner2.jpg').convert()
runner2_rect = runner2.get_rect(center=(270, 240))
screen.fill((0, 0, 0))
change = True
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
if event.type == MOUSEBUTTONDOWN:
screen.blit(runner2, runner2_rect)
pygame.display.update()
if event.type == KEYDOWN:
screen.blit(runner1, runner1_rect)
pygame.display.update()
As shown in the above example, we get images(sprites) of different postures and play them as and when we need to get the motion.
To begin and understand the pygame start from PUMMEL THE CHIMP and there are good API to handle sprites and their behavior through pygame.

Categories