python-pygame rectangle won't draw/render - python

im relatively new to coding and after understanding some basics in python i'm trying to apply oop in pygame
I have this code and I can't figure out why the rectangle won't appear
import pygame
import time
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("EXAMPLE")
clock = pygame.time.Clock()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
FPS = 30
class Puddles(pygame.sprite.Sprite):
puddle_width = 100
puddle_height = 20
def __init__(self,color,x,y):
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.color = color
self.image = pygame.Surface((Puddles.puddle_width,Puddles.puddle_height))
self.image.fill(self.color)
self.rect = self.image.get_rect()
self.rect.x = self.x # i think problem's here because if I type specific integers for x and y the tile will appear
self.rect.y = self.y
all_sprites = pygame.sprite.Group()
puddle1 = Puddles(red, 400, 600)
all_sprites.add(puddle1)
gameExit = False
while not gameExit:
clock.tick(FPS)
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
gameExit = True
all_sprites.update()
screen.fill(white)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
quit()
any ideas?
thanks in advance:)

puddle1 = Puddles(red, 400, 600)
The y position of the puddle is below the screen height, so it's outside of the screen. ;) Try to change it for example to puddle1 = Puddles(red, 400, 200).
Also, lines 43-46 should be indented, so that they're in the while loop.

Related

How do I make this pymunk code work? It shows a black screen

I am new to stackoverflow.
My code has a problem which the screen turns completely black.
The error.
I need the answer quickly so any help will be good.
Heres the code:
import pygame, sys
import pymunk
import pymunk.pygame_util
from pymunk.vec2d import Vec2d
size = (800, 800)
FPS = 120
space = pymunk.Space()
space.gravity = (0,250)
pygame.init()
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
class Ball:
global space
def __init__(self, pos):
self.body = pymunk.Body(1,1, body_type = pymunk.Body.DYNAMIC)
self.body.position = pos
self.radius = 60
self.shape = pymunk.Circle(self.body, self.radius)
space.add(self.body, self.shape)
def draw(self):
x = int(self.body.position.x)
y = int(self.body.position.y)
pygame.draw.circle(screen, (255,0,0), (x,y), self.radius)
balls = []
balls.append(Ball((400,0)))
balls.append(Ball((100,0)))
balls.append(Ball((600,100)))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screeen.fill(217,217,217)
for ball in balls:
ball.draw()
space.step(1/50)
pygame.display.update()
clock.tick(FPS)
Any help on what to do???
Thanks.
screeen.fill(217,217,217) should be screen.fill((217,217,217))
The Indentation is not correct. In particular, the scene must be pulled in the application loop and not in the bleed loop:
import pygame, sys
import pymunk
import pymunk.pygame_util
from pymunk.vec2d import Vec2d
size = (800, 800)
FPS = 120
space = pymunk.Space()
space.gravity = (0,250)
pygame.init()
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
class Ball:
global space
def __init__(self, pos):
self.body = pymunk.Body(1,1, body_type = pymunk.Body.DYNAMIC)
self.body.position = pos
self.radius = 60
self.shape = pymunk.Circle(self.body, self.radius)
space.add(self.body, self.shape)
# INDENTATION
#<--|
def draw(self):
x = int(self.body.position.x)
y = int(self.body.position.y)
pygame.draw.circle(screen, (255,0,0), (x,y), self.radius)
balls = []
balls.append(Ball((400,0)))
balls.append(Ball((100,0)))
balls.append(Ball((600,100)))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# INDENTATION
#<------|
screen.fill((217,217,217))
for ball in balls:
ball.draw()
space.step(1/50)
pygame.display.update()
clock.tick(FPS)

Pygame character movement

I'm practicing with pygame and don't know how to make my character move. If I put 'print' statement, it works, and prints whatever I want when I press 'a' for example, but character stays on his place. I know little about classes, so I think that's the problem
import pygame
pygame.init()
pygame.font.init()
width, height = 924, 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Priest Beast')
clock = pygame.time.Clock()
BG = pygame.transform.scale2x(pygame.image.load('art/background.png')).convert_alpha()
music = pygame.mixer.Sound('sound/music.mp3')
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.transform.scale2x(pygame.image.load('art/Player.png')).convert_alpha()
self.rect = self.image.get_rect(center = (800, 300))
self.x = x
self.y = y
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.rect.x += 5
def update(self):
self.move()
#Loop and exit
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# Sounds
music.play()
music.set_volume(0.1)
screen.blit(BG, (0, 0))
player = pygame.sprite.GroupSingle()
player.add(Player(800,200))
#Update everything
player.draw(screen)
player.update()
pygame.display.update()
clock.tick(60)
You continuously recreate the object in its initial position. You need to create the Sprite and Group before the application loop:
player = pygame.sprite.GroupSingle() # <-- INSERT
player.add(Player(800,200))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# [...]
screen.blit(BG, (0, 0))
# DELETE
# player = pygame.sprite.GroupSingle()
# player.add(Player(800,200))
# [...]

How do I fix movement in my pygame script?

I am trying to make a replica for pong in pygame for my first project but when I try to move my paddles they stretch instead. I believe the reason is it creates a new rect every time I try to move it but I can't seem to figure out why. Please review the code and help rectify my mistake.
Here is my code:
import pygame
W, H = 600, 500
screen = pygame.display.set_mode((W, H))
FPS = 30
class Paddle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super(Paddle, self).__init__()
self.x = x
self.y = y
self.width = width
self.height = height
self.surf = pygame.Surface((width, height))
self.surf.fill((255, 255, 255))
self.rect = self.surf.get_rect()
self.rect.center = (x, y)
def move(self, distance):
self.rect.move_ip(0, distance)
paddleA = Paddle(15, 250, 10, 50)
paddleB = Paddle(585, 250, 10, 50)
allSprites = pygame.sprite.Group()
allSprites.add(paddleA)
allSprites.add(paddleB)
run = True
clock = pygame.time.Clock()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
pressedKeys = pygame.key.get_pressed()
if pressedKeys[pygame.K_UP]:
paddleB.move(-5)
elif pressedKeys[pygame.K_DOWN]:
paddleB.move(5)
elif pressedKeys[pygame.K_w]:
paddleA.move(-5)
elif pressedKeys[pygame.K_s]:
paddleA.move(5)
for sprite in allSprites:
screen.blit(sprite.surf, sprite.rect)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
Before drawing the new rect you should fill the screen with the background color, to remove the old rect. Otherwise the old one is still drawn there and you are just drawing new over the old one. Its' like painting a new picture on an old one.
screen.fill(color, rect) should do the trick.

Pygame: Click event is affecting every sprite to the left of them

I have an array with all the sprites inside of them, and in the loop, if the sprite is clicked then the sprite is killed.
If I click the sprites from left to right, everything is fine. They are cleared one by one independent of each other. But, if I click the sprite most right of the screen, it kills everything to the left of it.
Full code because I've no idea where the important region might be.
import pygame
from pygame.locals import *
import random
pygame.init()
level = 1
cooldown = 1000
class test(pygame.sprite.Sprite):
def __init__(self, w):
super().__init__()
self.image = pygame.Surface([600,600])
self.rect = self.image.get_rect()
self.image = pygame.image.load("index.png")
self.image = pygame.transform.scale(self.image, (w,w))
self.last = pygame.time.get_ticks()
screen = pygame.display.set_mode([600,600])
clock = pygame.time.Clock()
background = pygame.Surface(screen.get_size())
background.fill([0,0,0])
rX = random.randint(0, 500)
rX2 = random.randint(0, 500)
screen.blit(background, (0,0))
sp = []
all_sprites_list = pygame.sprite.Group()
a_1 = test(random.randint(40,60))
a_1.rect.x = rX
a_1.rect.y = -400
sp.append(a_1)
all_sprites_list.add(a_1)
#The steps for a_1 is repeated to make variables a_2, a_3, a_4...
Running = True
while Running:
now = pygame.time.get_ticks()
for x in sp:
x.rect.y+=level
m_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == QUIT:
Running = False
if event.type == MOUSEBUTTONDOWN:
for s in sp:
if s.rect.collidepoint(m_pos):
s.kill()
pygame.display.flip()
all_sprites_list.clear(screen, background)
all_sprites_list.draw(screen)
all_sprites_list.update()
clock.tick(60)
Problem is because in class you create Surface with size (600, 600) and you assign this size to self.rect. After that you load image but you forgot to assign its size to self.rect so program always check mouse click with size (600, 600) and when you click most right item then all rect (600, 600) are in area of click.
But you don't have to create Surface if you load image.
My version with many changes.
I removed list sp because I can use all_sprites_list
When it sends MOUSEBUTTONDOWN event then mouse position is in event.pos so I don't need pygame.mouse.get_pos()
import pygame
import random
# --- classes --- (UpperCaseNames)
class Test(pygame.sprite.Sprite):
def __init__(self, w):
super().__init__()
self.image = pygame.image.load("index.png")
self.image = pygame.transform.scale(self.image, (w, w))
self.rect = self.image.get_rect()
self.last = pygame.time.get_ticks()
# --- main ----
level = 1
cooldown = 1000
# - init -
pygame.init()
screen = pygame.display.set_mode((600, 600))
# - items -
background = pygame.Surface(screen.get_size())
background.fill((0, 0, 0))
screen.blit(background, (0,0))
all_sprites_list = pygame.sprite.Group()
for x in range(10):
item = Test(random.randint(40, 60))
item.rect.x = 40 * random.randint(0, 10)
item.rect.y = 0
all_sprites_list.add(item)
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
now = pygame.time.get_ticks()
for item in all_sprites_list:
item.rect.y += level
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
for item in all_sprites_list:
if item.rect.collidepoint(event.pos):
item.kill()
pygame.display.flip()
all_sprites_list.clear(screen, background)
all_sprites_list.draw(screen)
all_sprites_list.update()
clock.tick(30)
pygame.quit()

Pygame - Background doesnt work

im having a hard time making my first steps in pygame. I just wanna move a Picture around in front of a jpg-background.
I googled several times for a solution and tried different things .. and this is the "nearest" i can come up with:
(but it still doenst work ..)
Any ideas?
Thanks in advance!
Nico
import pygame
pygame.init()
display_width = 1600
display_height = 900
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
Player_width = 73
screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
background = pygame.surface(screen.get_size())
PlayerImg = pygame.image.load("C:\python\warrior1.png")
background_image = pygame.image.load("depositphotos_159346790-stock-photo-
forest-and-stones-2d-game.jpg")
background.blit(background_image)
screen.blit(background (0,0))
def Player(x,y):
gameDisplay.blit(PlayerImg,(x,y))
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
y_change = 0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
[...]
x += x_change
y += y_change
Player(x,y)
if x > display_width - Player_width or x < 0:
gameExit = True
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Answer:
delete
background = pygame.surface(screen.get_size())
in player replace
gameDisplay
with
screen
replace
background.blit(background_image)
screen.blit(background (0,0))
with
screen.blit(background_image, (0,0))
add screen.blit(background_image, (0,0))
also in the while Loop
Helpful Tips for Pygame:
Look at error messages and post them too.
Use *.png files in pygame. They can be transparent. You see no edges when the pictures overlap.
Watch Sentdex's Pygame Tutorial again.

Categories