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()
Related
I am creating a car game and have come across a problem. I've added a car image with a transparent background into my code but the car appears on the screen with the transparent background visible. I want to make the background to disappear. This is a link to the image: https://www.pngfind.com/mpng/bboJib_car-top-view-png-audi-transparent-png/
Here is the code:
import pygame
pygame.init()
import pygame
pygame.init()
black = (0, 0, 0)
#screen
screen_width = 600
screen_length = 800
screen = pygame.display.set_mode((screen_length, screen_width))
clock = pygame.time.Clock()
FPS = 60
#the car i am having trouble with
car2Img = pygame.image.load('car2.png')
car2_X = 0
car2_Y = 0
carX_change = 0
def car2(x, y):
screen.blit(car2Img, (x, y))
running = True
while running:
screen.fill((119, 118, 110))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
car2(car2_X, car2_Y)
clock.tick(FPS)
pygame.display.update()
pygame.quit()
In order to remove the background from a png image you must use the convert_alpha() function when loading it:
car2Img = pygame.image.load('car2.png').convert_alpha()
If your image doesn't contain alpha then you can use a color key to remove the background:
car2Img.set_colorkey(colorOfBackground)
When i hit play my cursor seems to be on the top left corner of the rect, i am very fresh to using thonny/pygames and can't figure out how to get my mouse cursor to be in the center of the rect.
Any help would be greatly appreciated, thanks! :)
import pygame # accesses pygame files
import sys # to communicate with windows
# game setup ################ only runs once
pygame.init() # starts the game engine
clock = pygame.time.Clock() # creates clock to limit frames per second
FPS = 60 # sets max speed of main loop
SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1000, 800 # sets size of screen/window
screen = pygame.display.set_mode(SCREENSIZE) # creates window and game screen
# set variables for colors RGB (0-255)
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
yellow = (255, 255, 0)
green = (0, 255, 0)
gameState = "running" # controls which state the games is in
# game loop #################### runs 60 times a second!
while gameState != "exit": # game loop - note: everything in the mainloop is indented one tab
for event in pygame.event.get(): # get user interaction events
print (event)
if event.type == pygame.QUIT: # tests if window's X (close) has been clicked
gameState = "exit" # causes exit of game loop
# your code starts here ##############################
screen.fill(black)
mouse_position = pygame.mouse.get_pos()
player1X = mouse_position[0]
player1Y = mouse_position[1]
player1 = pygame.draw.rect(screen, red, (player1X, player1Y, 50, 50))
pygame.display.flip() # transfers build screen to human visable screen
clock.tick(FPS) # limits game to frame per second, FPS value
# your code ends here ###############################
pygame.display.flip() # transfers build screen to human visable screen
clock.tick(FPS) # limits game to frame per second, FPS value
# out of game loop ###############
print("The game has closed") # notifies user the game has ended
pygame.quit() # stops the game engine
sys.exit() # close operating system window
Create a pygame.Rect object with the size of the player and set the center position of the rectangle by the mouse cursor position:
player1 = pygame.Rect(0, 0, 50, 50)
player1.center = mouse_position
pygame.draw.rect(screen, red, player1)
Note, a pygame.Rect has a bunch of virtual attributes, which can be used to get an set its size and position.
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()
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()
I'm learning pygame, and I just entered a few basic lines to try to move a ball across my window, but after displaying the image, the window will just freeze.
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
ball = pygame.image.load("ball.png").convert()
ball_rect = ball.get_rect()
white = (255,255,255)
frames = 100
for x in range(frames):
screen.blit(ball, ball_rect) # display player
ball_rect.move(2, 2) # move player
pygame.display.update()
pygame.time.delay(100)
screen.fill(white) # erase player
The window is not freezing, it's just refreshing the same image at the same place during the 10 seconds you have set.
This is mostly caused by the method used to move the image, you should use move_ip instead of move as a quick fix (doc).
Another change you can do is replace the for loop by a while, to let the player quit when he wants :
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((640, 480))
ball = pygame.image.load("ball.png").convert()
ball_rect = ball.get_rect()
white = (255,255,255)
looping = True
while looping:
for event in pygame.event.get():
if(event.type is pygame.QUIT):
looping = False
screen.fill(white) # erase player
screen.blit(ball, ball_rect) # display player
ball_rect.move_ip(2, 2) # move player
pygame.display.update()
clock.tick(10) # to keep the same FPS, better increase !
# Thanks skrx !