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 !
Related
(i followed a yt tut so idk) my code: idk if i put code in wrong place
import pygame
white = (255,255,255)
black = (0,0,0)
orange = (255,165,0)
player_sprite = pygame.image.load("will smith.png") .convert_alpha
pygame.init()
display = pygame.display.set_mode((850,850))
pygame.display.set_caption('Conners Game')
exit = False
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
print(event)
display.fill(white)
pygame.display.update()
pygame.quit()
quit()
not really sure why it does this, im new to python so idk
There are multiple things that needs to fixed. First of all to you actually need to blit the image on the screen.
while not exit:
for event in pygame.event.get():
#...[block of code]
display.fill(white)
display.blit(player_sprite, (100,100)) # BLIT IMAGE TO SCREEN
.convert_alpha() is a method and you need to call it after you initialize pygame and set the video mode.
You can read more about convert_alpha() here
pygame.init()
display = pygame.display.set_mode((850,850))
pygame.display.set_caption('Conners Game')
#converting it after init and setting game mode
player_sprite = pygame.image.load("will smith.png").convert_alpha()
Here's the final working code
import pygame
white = (255,255,255)
black = (0,0,0)
orange = (255,165,0)
pygame.init()
display = pygame.display.set_mode((850,850))
pygame.display.set_caption('Conners Game')
player_sprite = pygame.image.load("will smith.png").convert_alpha()
exit = False
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
# print(event)
display.fill(white)
display.blit(player_sprite, (100,100))
pygame.display.update()
pygame.quit()
quit()
You have to blit the image in the application loop, after clearing the display and before updating the display:
display.blit(player_sprite, (100, 100))
convert_alpha is function. You missed the parentheses
player_sprite = pygame.image.load("will smith.png").convert_alpha
player_sprite = pygame.image.load("will smith.png").convert_alpha()
Also, you cannot call a pygame function before you initialize pygame. pygame.init() should be the very first pygame function called.
Complete example:
import pygame
white = (255,255,255)
black = (0,0,0)
orange = (255,165,0)
pygame.init()
display = pygame.display.set_mode((850,850))
pygame.display.set_caption('Conners Game')
player_sprite = pygame.image.load("will smith.png").convert_alpha()
exit = False
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
print(event)
display.fill(white)
display.blit(player_sprite, (100, 100))
pygame.display.update()
pygame.quit()
quit()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
When running this code:
import pygame,time
GREEN = (30, 156, 38)
WHITE = (255,255,255)
pygame.init()
screen = pygame.display.set_mode((640, 480))
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, (0,0,100,100))
time.sleep(3)
Pygame shows a black screen for 3 seconds, but doesn't draw a rectangle.
I am using Atom using script package to run code
You have to implement an application loop. The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
limit frames per second to limit CPU usage
import pygame
GREEN = (30, 156, 38)
WHITE = (255,255,255)
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
# applicaition loop
run = True
while run:
# limit frames per second
clock.tick(60)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# clear display
screen.fill(WHITE)
# draw objects
pygame.draw.rect(screen, GREEN, (0, 0, 100, 100))
# update display
pygame.display.flip()
pygame.quit()
exit()
Note, you must do the event handling. See pygame.event.get() respectively pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
Update the screen with:
pygame.display.update()
at the end of your code you have posted.
You have to update the screen like that:
pygame.display.flip()
to render what you just drew.
Your code should look like this:
import pygame
import time
pygame.init()
GREEN = (30, 156, 38)
WHITE = (255,255,255)
screen = pygame.display.set_mode((640, 480))
# draw on screen
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, (0,0,100,100))
# show that to the user
pygame.display.flip()
time.sleep(3)
Off-topic: You should also get the events to allow the user to close the window:
import pygame
from pygame.locals import QUIT
import time
pygame.init()
GREEN = (30, 156, 38)
WHITE = (255, 255, 255)
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock() # to slow down the code to a given FPS
# draw on screen
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, (0, 0, 100, 100))
# show that to the user
pygame.display.flip()
start_counter = time.time()
while time.time() - start_counter < 3: # wait for 3 seconds to elapse
for event in pygame.event.get(): # get the events
if event.type == QUIT: # if the user clicks "X"
exit() # quit pygame and exit the program
clock.tick(10) # limit to 10 FPS
# (no animation, you don't have to have a great framerate)
Note that you must put all of this into a game loop if you want to repeat it like a classic game.
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()
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()