How to find the position of a Rect in python? - python

I was trying to make a code that moves a rect object (gotten with the get_rect function) but I need its coordinates to make it move 1 pixel away (if there are any other ways to do this, let me know.)
Here is the code:
import sys, pygame
pygame.init()
size = width, height = 1920, 1080
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.png")
rectball = ball.get_rect()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
rectball.move()
screen.fill(black)
screen.blit(ball, rectball)
pygame.display.flip()
You will notice that on line 11 the parameters are unfilled. This is because I was going to make it coords + 1.

If I am correct I think it is rect.left or rect.top that gives it. Another method is to create another rectangle and check if the rectangle is in that.

Related

sprite image does not appear in pygame

i being following this pygame tutorial and I can't have my sprite show on the window. When I run the program I see the rectangle move on the screen but it just shows all black. I try changing the background color on my rectangle according to the window but i still get nothing. I do notice that the rectangle changes shape according to the different images i try to load. Here is the code. Thank you
import pygame
import random
import os
WIDTH = 800
HEIGHT = 600
FPS = 30
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
#SET ASSETS FOLDERS
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
class Player(pygame.sprite.Sprite):
# sprite for the Player
def __init__(self):
# this line is required to properly create the sprite
pygame.sprite.Sprite.__init__(self)
# create a plain rectangle for the sprite image
self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert()
# find the rectangle that encloses the image
self.rect = self.image.get_rect()
# center the sprite on the screen
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
# any code here will happen every time the game loop updates
self.rect.x += 5
if self.rect.left > WIDTH:
self.rect.right = 0
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Sprite Example")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(GREEN)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
enter code herepygame.display.flip()
pygame.quit()
I just changed one line near the end of the code in your question and it started working:
.
.
.
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(GREEN)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip() # <----- FIX THIS LINE
pygame.quit()

Pygame ValueError: invalid rectstyle object

I downloaded a pygame example from here called rabbitone, and followed the corresponding youtube video.
So I have studied the code and tried it:
import pygame
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
player = pygame.image.load("resources/images/dude.png")
while True:
screen.fill(0,0,0)
pygame.display.flip()
screen.blit(player, (100,100))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
In the video tutorial I'm following, the code works. Why do I get this error?
Traceback (most recent call last):
File "", line 2, in
ValueError: invalid rectstyle object
You're passing three separate integers to the pygame.Surface.fill method, but you have to pass a color tuple (or list or pygame.Color object) as the first argument : screen.fill((0, 0, 0)).
You also need to blit the player between the fill and the flip call, otherwise you'll only see a black screen.
Unrelated to the problem, but you should usually convert your surfaces to improve the performance and add a pygame.time.Clock to limit the frame rate.
import pygame
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
# Add a clock to limit the frame rate.
clock = pygame.time.Clock()
# Convert the image to improve the performance (convert or convert_alpha).
player = pygame.image.load("resources/images/dude.png").convert_alpha()
running = True
while running:
# Handle events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Insert the game logic here.
# Then draw everything, flip the display and call clock tick.
screen.fill((0, 0, 0))
screen.blit(player, (100, 100))
pygame.display.flip()
clock.tick(60) # Limit the frame rate to 60 FPS.
pygame.quit()
I had the same issue but it was in a different situation.
I put surface.fill(0,0,0)
To fix this, I put surface.fill((0,0,0))
With a pair of extra brackets aroud the colour

A Python Programming Road Block Type Error: 'pygame.Surface' object is not callable How to Fix

import pygame
pygame.init()
#colors
black = (0,0,0)
white = (255,255,255)
#Screen Display
Width = 1000
Height = 500
gameDisplay = pygame.display.set_mode((Width, Height))
pygame.display.set_caption('Trock')
clock = pygame.time.Clock()
S_1= pygame.image.load('S1.png')
def car(x,y):
gameDisplay.blit(S_1,(x,y))
x = (Width * 0)
y = (Height * 0.3)
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
gameDisplay.fill(white)
S_1(x,y)
pygame.display.update()
clock.tick (60)
pygame.quit()
quit()
I am Trying to load and image onto the display screen (image is called S1 and variable is S_1) but it wont show and says
Pygame.Surface object is not callable.
Any assistance will be greatly appreciated
S_1 is a Surface object. Use blit to draw an image. Actually blit draws one Surface onto another. Hence you need to blit the image onto the Surface associated to the display.
gameDisplay = pygame.display.set_mode((Width, Height))
# [...]
S_1 = pygame.image.load('S1.png')
# [...]
while not crashed:
# [...]
gameDisplay.fill(white)
gameDisplay.blit(S_1, (x, y))
pygame.display.update()
# [...]
See also How to Display Sprites in Pygame?

Pygame blit image with mouse event

I use Pygame in this code. This is like a game that when user hit mouse button, from the mouse position comes a laser image that will go up, and eventually go out of the screen. I am trying to blit an image when the user hit mouse button. This code I am using does not work and I do not know why. My problem starts at the main for loop
import pygame
# Initialize Pygame
pygame.init()
#___GLOBAL CONSTANTS___
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Set the height and width of the screen
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])
#Load Laser image of spaceship
laser_image = pygame.image.load('laserRed16.png').convert()
#Load sound music
sound = pygame.mixer.Sound('laser5.ogg')
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Get the current mouse position. This returns the position
# as a list of two numbers.
sound.play()
#Get the mouse position
mouse_position = pygame.mouse.get_pos()
mouse_x = mouse_position[0]
mouse_y = mouse_position[1]
# Set the laser image when the spaceship fires
for i in range(50):
screen.blit(laser_image,[mouse_x + laser_x_vector,mouse_y + laser_x_vector])
laser_x_vector += 2
laser_x_vector += 2
# Clear the screen
screen.fill(WHITE)
#Limit to 20 sec
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
You fill the screen after you blit the lazer, so the lazer will not appear. You should fill before you blit the lazer so the lazer appears.
The others have already explained why you don't see the laser. Here's a working solution for you. First I suggest to use pygame.Rects for the positions of the lasers and put them into a list (rects can also be used for collision detection). Then iterate over these positions/rects in the main while loop, update and blit them. I also show you how to remove rects that are off screen.
import pygame
pygame.init()
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])
laser_image = pygame.Surface((10, 50))
laser_image.fill(GREEN)
done = False
clock = pygame.time.Clock()
laser_rects = []
laser_velocity_y = -20
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Turn the mouse position into a rect with the dimensions
# of the laser_image. You can use the event.pos instead
# of pygame.mouse.get_pos() and pass it as the `center`
# or `topleft` argument.
laser_rect = laser_image.get_rect(center=event.pos)
laser_rects.append(laser_rect)
remaining_lasers = []
for laser_rect in laser_rects:
# Change the y-position of the laser.
laser_rect.y += laser_velocity_y
# Only keep the laser_rects that are on the screen.
if laser_rect.y > 0:
remaining_lasers.append(laser_rect)
# Assign the remaining lasers to the laser list.
laser_rects = remaining_lasers
screen.fill(WHITE)
# Now iterate over the lasers rect and blit them.
for laser_rect in laser_rects:
screen.blit(laser_image, laser_rect)
pygame.display.flip()
clock.tick(30) # 30 FPS is smoother.
pygame.quit()

How to make images move to random position on clicking in pygame?

I want to move the apple image to a random position whenever i click it.The first time i click it , it works well but next time i try to do it , it gives me no response.
Here is the code:
import pygame
pygame.init()
foodimg=pygame.image.load("food.png")
foodrect=foodimg.get_rect()
white = (255,255,255)
#Game Display
display_width = 1080
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Click It! ~ Snapnel Productions')
gameDisplay.fill((white))
running=True
while running:
gameDisplay.fill((white))
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
x, y = event.pos
if foodimg.get_rect().collidepoint(x, y):
foodrect.center=(random.randint(5,1060),random.randint(5,700))
print "Hi",
continue
gameDisplay.blit(foodimg,foodrect)
pygame.display.flip()
is the food image.
Change the line
if foodimg.get_rect().collidepoint(x, y):
to
if foodrect.collidepoint(x, y):
Your code didn't work because the rectangle of the picture never moves, it's always going to be <rect(0, 0, 30, 30)>. Foodrect actually represents where your rectangle is located and it's the rect whos values you change when you run foodrect.center =. You want to check if the mouse click is colliding with the real rect, not the rect of the image.

Categories