For some reason when i run the code in netbeans i only get a blank screen
import pygame
import random
WIDTH = 480
HEIGHT = 600
FPS = 60
# define colours
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((40, 50))
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.rect.x += self.speedx
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(BLACK)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
please help me. when i run the code in netbeans it works but the screen where the game should be is blank, when i close the screen there is a frame of it in colour before it closes the window. I'm using OSX sierra
The sprites update and rendering calls are not being made in your while loop.
As pointed out in the comments, you need to indent the seven lines below # Update. Try this:
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(BLACK)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
Related
This question already has answers here:
Pygame on Mac Mojave
(1 answer)
Problems getting pygame to show anything but a blank screen on Macos
(10 answers)
Closed 2 years ago.
My kid is learning python via pygame
he saw in online tutorial about sprites
and wrote this code, but we dont see anything
import pygame
import random
WIDTH = 360
HEIGHT = 480
FPS = 30
# colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("my game")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# game loop
running = True
while running:
# keep the loop running at the right speed
clock.tick(FPS)
# events
for event in pygame.event.get():
# check for closing the window
if event.type == pygame.QUIT:
running = False
# update
all_sprites.update()
# draw/render
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
I can't see what's wrong with the below code. All I want to do is make the frog move across the screen, but it is simply redrawing many, many frogs all one pixel apart. How do I move the frog rather than just draw it again?
import pygame
from pygame.constants import *
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
class Frog(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.transform.scale(pygame.image.load('frog.png'), (64, 64))
self.rect = self.image.get_rect()
self.dx = 1
def update(self, *args):
self.rect.x += self.dx
running = True
frog = Frog()
entities = pygame.sprite.Group()
entities.add(frog)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
entities.update()
entities.draw(screen)
That is how you do it in Pygame, you just redraw objects every iteration to give the illusion that they're moving but you must cover up the previous drawn objects by filling your window with a solid color e.g.
screen.fill((255, 255, 255))
This should be at the start of your game loop so you have a fresh canvas for drawing your objects each iteration.
while running:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == QUIT:
running = False
entities.update()
entities.draw(screen)
pygame.display.update()
You may have to use the pygame.display.update() function to update the whole screen rather than just your entities.
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()
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()
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()