Rectangle not being drawn [duplicate] - python

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.

Related

what is wrong with my code why don't I see the white rectangle when i run the code. draw.rect() command

when I try to run the code the white square that is supposed to be there does not pop up.
I've tried to replace the variables with the numbers corresponding to them but it does not work either.
this is the code:
import pygame
from pygame import *
pygame.init()
# vars for window Height,width, and resolution'
WIN_WIDTH = 1100
WIN_HEIGHT = 600
WIN_RES = (WIN_WIDTH, WIN_HEIGHT)
# Width & height for grid behind background + color of the grid
WIDTH = 100
HEIGHT = 100
WHITE = (255, 255, 255)
# Create window
GAME_WINDOW = display.set_mode(WIN_RES)
# To Do Add window caption/title here
display.set_caption("Attack of the vampire pizzas")
# background & vampire pizza image
pizza_img = image.load('vampire.png')
pizza_surf = Surface.convert_alpha(pizza_img)
VAMPIRE_PIZZA = transform.scale(pizza_surf, (WIDTH, HEIGHT))
background_img = image.load('restaurant.jpg')
background_surf = Surface.convert_alpha(background_img)
BACKGROUND = transform.scale(background_surf, WIN_RES)
GAME_WINDOW.blit(BACKGROUND, (0, 0))
GAME_WINDOW.blit(VAMPIRE_PIZZA, (900, 400))
# actual grid
tile_color = WHITE
draw.rect(BACKGROUND, tile_color, (0, 0, WIDTH, HEIGHT), 1)
# --------------------------------------------------------------------------------------
# Start main game loop
game_running = True
# game loop
while game_running:
# check for events
for event in pygame.event.get():
# Exit loop on quit
if event.type == QUIT:
game_running = False
display.update()
# End of main game loop
# Clean up game
pygame.quit()
It is a matter of Indentation. The event loop and display.update() must be run in the game loop. Additionally you need to draw the rectangle in the game window in the application loop:
# Start main game loop
game_running = True
# game loop
while game_running:
# INDENTATION
#-->|
# check for events
for event in pygame.event.get():
# Exit loop on quit
if event.type == QUIT:
game_running = False
GAME_WINDOW.blit(BACKGROUND, (0, 0))
GAME_WINDOW.blit(VAMPIRE_PIZZA, (900, 400))
draw.rect(GAME_WINDOW, tile_color, (0, 0, WIDTH, HEIGHT), 1)
# INDENTATION
#-->|
display.update()
# End of main game loop
# Clean up game
pygame.quit()
Note, you have to redraw the scene in every frame. 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()

Can't figure out how to get my mouse cursor on the center of the rect

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.

pygame.error: video system not initialize, using Repl.it

I get this error when I try to run my pygame code pygame.error: video system not initialized. I'm using Repl.it and am attempting to create an aiming game which can track accuracy and in which you only have 3 lives.
import pygame
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # Here we exit the Loop and execute what after
pygame.quit()
# Play Surface
width = 1080
height = 720
playSurface = pygame.display.set_mode((width, height))
pygame.display.set_caption('Aim Practice')
# Colors
red = pygame.Color(0, 0, 0)
blue = pygame.Color(255, 255, 255)
Image of most of the code
https://repl.it/join/dppwnpin-isa__paz (You can view the full code here!)
The issue is that you event loop is running before anything is initialised. As #zenofpython says in his answer, the calls to prepare the window must come before the main event loop.
Your main event loop is first, and nothing is setup to run.
Just moving the code around will fix it:
import pygame
# FIRST, HANDLE ALL THE INITIALISATION OF PYGAME, FONTS, MIXER etc.
# Play Surface
width = 1080
height = 720
playSurface = pygame.display.set_mode((width, height))
pygame.display.set_caption('Aim Practice')
# Colors
red = pygame.Color(0, 0, 0)
blue = pygame.Color(255, 255, 255)
# ... AND THE REST
# MAIN LOOP
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # Here we exit the Loop and execute what after
playSurface.fill( blue ) # fill the screen
pygame.display.flip() # flush all the drawing operations to the window
fpsController.tick_busy_loop(60) # clamp the max-FPS
pygame.quit()
You should use pygame.display.set_mode before running your event loop. pygame.event.get won't work if you haven't created a window.

Python + Pygame; screen.fill() crashing window

Whenever I try to include "screen.fill(insert value here)" to my pygame code, the window instantly crashes. I can comment it out and my code works just fine. I'm really not sure why.
I've tried moving the line around, using other people's code in part - no luck.
import pygame
pygame.init()
win = pygame.display.set_mode((1000, 800))
pygame.display.set_caption("Tetris")
img=pygame.image.load("C:\\Users\\Charlotte\\Desktop\\tetris_grid.png")
win.blit(img,(450, 150))
running = True
while running:
screen.fill(0, 0, 0)
pygame.display.update()
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
When I run the code with that line in it, the window opens and then it instantly closes.
If you are trying to fill the screen with black, the color must be passed as a tuple:
win.fill((0, 0, 0))
Also, you never assign screen, maybe you intended to use win?
The doc for Surface.fill.
The color parameter to fill() has to be either a single grayscale value or a tuple of 3 RGB or 4 RGBA components. So it has to be either:
win.fill(0)
or
win.fill((0, 0, 0))
Further you've to blit() the image in the main loop. To continuously draw the scene in the main application loop, you've to:
handle the events
clear the window
draw the scene (blit the image)
update the display
Furthermore I recommend to use tick() of pygame.time.Clock rather than pygame.time.delay() tpo control the frames per second.
import pygame
pygame.init()
win = pygame.display.set_mode((1000, 800))
pygame.display.set_caption("Tetris")
clock = pygame.time.Clock()
img=pygame.image.load("C:\\Users\\Charlotte\\Desktop\\tetris_grid.png")
running = True
while running:
clock.tick(60)
# handle the events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# clear the display
win.fill(0)
# draw the scene
win.blit(img,(450, 150))
# update the display
pygame.display.update()
pygame.quit()

Pygame Not Responding

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 !

Categories