I'm trying to run a very basic pygame application, however I cannot get it to draw content to, or even fill the screen. I do update the screen in the main loop after filling it, however the screen stays blank and does not color black.
Printing inside the run function prints 60 times every second as expected. I do run MacOS Catalina which may be the problem, although I did not find any other mention of this problem.
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
class Simulator:
running = True
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((800, 600), 0, 32)
self.clock = pygame.time.Clock()
pygame.display.set_caption('Traffic Simulator')
def run(self):
while (self.running):
for e in pygame.event.get():
if (e.type == pygame.QUIT):
self.running = False
self.screen.fill(BLACK)
pygame.display.flip()
pygame.display.update()
self.clock.tick(60)
if __name__ == "__main__":
sim = Simulator()
sim.run()
pygame.quit()
It shows a window with the title 'Traffic Simulator' with the default system color grey in the window, which I expect to be black.
#sloth Was right after all. After building pygame manually instead of pulling it from pip, it worked.
Here are the instructions I followed.
https://www.pygame.org/wiki/MacCompile
Related
import pygame
import time
# WINDOW SETUP
window = pygame.display.set_mode((900, 500))
pygame.display.set_caption("Pong")
time.sleep(5)
FPS = 60
# RGB VALUE VARIABLES
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
def background(window):
window.fill(WHITE)
pygame.display.update()
# FRAMERATE AND EVENT LOOP INITIALIZATION
def main():
run = True
clock = pygame.time.Clock()
while run:
clock.tick(FPS)
background(window)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if running == False:
pygame.quit()
Above, is my code. I'm trying to make a pong game with pygame. The text editor I am coding with is Visual Studios Code (VSCODE).
Firstly, you need to call the main. You should also make you're code nice and easy to read when possible. I imported pygame as pg which makes typing pygame functions a bit faster as you have less to type. Also, it's better to use global variables to hold variables that won't change through the program, like screen width, height, colours, etc. Then make sure you initialise the module.
As well as that, the only update you have is in background(). You should put the update at the bottom of the loop and remove it from background(). This way everything above will update each loop.
I apologise for not adding you're FPS counter in here as well but I think this should be enough to help you get you're window running with more readable code and a more efficient loop.
import pygame as pg
# Global Variables
screen_width = 900
screen_height = 500
screen = pg.display
window = screen.set_mode((screen_width, screen_height))
colour = 'red'
def main():
# Initialise module
pg.init()
pg.display.set_caption('PONG')
running = True
while running:
# This is a better way of writing your loop
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
# Call background function
background()
# Updates window
# place this inside the loop near the bottom
# so everything is updated at the end of each loop
screen.flip()
def background():
window.fill(colour)
# Remember to call your main function
# This if statement is good practise but not required
# You can just place main() here
if __name__ == '__main__':
main()
So i wrote this code:
# Pygame development 4
# Focus on making code object oriented
# Introduce classes and objects into our code
# Gain access to the pygame library
import pygame
# Size of the screen
SCREEN_TITLE = 'Crossy RPG'
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
# Colors according to RGB codes
WHITE_COLOR = (255, 255, 255)
BLACK_COLOR = (0, 0 , 0)
# Clock used to update game events and frames
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.SysFont('comicsans', 75)
class Game:
# Typical rate of 60, equivalent to fps
TICK_RATE = 60
# Initializer for the game class to set up the width, height, and title
def __init__(self, title, width, height):
self.title = title
self.width = width
self.height = height
# Create the window of specified size in white to display the game
self.game_screen = pygame.display.set_mode((width, height))
# Set the game window color to white
self.game_screen.fill(WHITE_COLOR)
pygame.display.set_caption(title)
def run_game_loop(self):
is_game_over = False
# Main game loop, used to update all gameplay suh as movement, check, and graphics
# Runs unit is_game_over = True
while not is_game_over:
# A loop to get a;l of the events occuring at any given time
# Events are most often mouse movement, mouse and button clicks, or eit events
for event in pygame.event.get():
# If we have a quite type event(exit out) then exit out of the game loop
if event.type == pygame.QUIT:
is_game_over = True
print(event)
# Update all game graphics
pygame.display.update()
# Tick the clock to update everything within the game
clock.tick(self.TICK_RATE)
pygame.init()
new_game = Game(SCREEN_TITLE, SCREEN_WIDTH, SCREEN_HEIGHT)
new_game.run_game_loop()
pygame.quit()
quit()
Right now I am learning to code with python so im following a course online and since I couldn't get help from the forums of that website I thought I might ask the question here! So I've looked at the code multiple times to check for spelling mistakes but I couldn't find any and anyway i think that it's' not about something missing but it has something to do with pygame.display.update ! Can somebody pls help me?
Without running your code or having a stack trace of where the problem happens, we need to debug the code for you first. So it would be beneficial to add a full stack trace to your questions. I'm pretty confident however that there's two issues that you should work out.
pygame.display.update() should be correctly indented to be in the while loop of your main game event loop. Secondly, the pygame.init() should be run before any other initialization (or at least so I've been taught over the years and every example points to)
Try this out, I think it solves your problem:
# Pygame development 4
# Focus on making code object oriented
# Introduce classes and objects into our code
# Gain access to the pygame library
import pygame
pygame.init()
# Size of the screen
SCREEN_TITLE = 'Crossy RPG'
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
# Colors according to RGB codes
WHITE_COLOR = (255, 255, 255)
BLACK_COLOR = (0, 0 , 0)
# Clock used to update game events and frames
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.SysFont('comicsans', 75)
class Game:
# Typical rate of 60, equivalent to fps
TICK_RATE = 60
# Initializer for the game class to set up the width, height, and title
def __init__(self, title, width, height):
self.title = title
self.width = width
self.height = height
# Create the window of specified size in white to display the game
self.game_screen = pygame.display.set_mode((width, height))
# Set the game window color to white
self.game_screen.fill(WHITE_COLOR)
pygame.display.set_caption(title)
def run_game_loop(self):
is_game_over = False
# Main game loop, used to update all gameplay suh as movement, check, and graphics
# Runs unit is_game_over = True
while not is_game_over:
# A loop to get a;l of the events occuring at any given time
# Events are most often mouse movement, mouse and button clicks, or eit events
for event in pygame.event.get():
# If we have a quite type event(exit out) then exit out of the game loop
if event.type == pygame.QUIT:
is_game_over = True
print(event)
# Update all game graphics
pygame.display.update()
# Tick the clock to update everything within the game
clock.tick(self.TICK_RATE)
new_game = Game(SCREEN_TITLE, SCREEN_WIDTH, SCREEN_HEIGHT)
new_game.run_game_loop()
pygame.quit()
This also seams to be a school assignment and not a online course (but I might be wrong here), never the less I'll leave this piece of advice if I'm right. I strongly suggest that if you bump into problems, ask your teacher for guidance. As there's always a reason for teachers giving you a challenge/problem to solve. It teaches you the latest techniques you've learned in class, and if you can't solve the problem with the tools that you've been given - you've most likely haven't learned the fundamentals that has been taught out - and you should really re-do some steps.
I am currently following a beginner pygame tutorial on YouTube here but even though I copied the code exactly from the tutorial my pygame window only stays open for about a second and then closes.
note: someone asked this question about three years ago here but it didn't fix my problem.
my code is below
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')
Your script is ending and so pygame closes everything.
You have to create a loop in order for your game to continue running, with a condition to exit the loop.
You also need to initialize the display with pygame.display.init()
import pygame
pygame.init()
pygame.display.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')
clock = pygame.time.Clock()
FPS = 60 # Frames per second.
# Some shortcuts for colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# For example, display a white rect
rect = pygame.Rect((0, 0), (32, 32))
image = pygame.Surface((32, 32))
image.fill(WHITE)
# Game loop
while True:
# Ensure game runs at a constant speed
clock.tick(FPS)
# 1. Handle events
for event in pygame.event.get():
# User pressed the close button ?
if event.type == pygame.QUIT:
quit()
# Close the program. Other methods like 'raise SystemExit' or 'sys.exit()'.
# Calling 'pygame.quit()' won't close the program! It will just uninitialize the modules.
# 2. Put updates to the game logic here
# 3. Render
win.fill(BLACK) # first clear the screen
win.blit(image, rect) # draw whatever you need
pygame.display.flip() # copy to the screen
I'm making a game analyser, and I thought it would be nice if I had a user iterface instead of just using text and raw input to communicate. I am having problems with 'blitting' an image to my screen.
My image is inside the pycharm file called 'CATANYLISER' as is my code.
import pygame
pygame.init()
# py-game variables
(width, height) = (1000, 600)
window = pygame.display.set_mode((width, height))
window_title = pygame.display.set_caption('the CATANALYSER')
does_quit = False
# py-game images
empty_board = pygame.image.load('empty_board.png')
# py-game window loop
while not does_quit:
# receives input from window
for event in pygame.event.get():
# stops program when red x clicked
if event.type == pygame.QUIT:
does_quit = True
window.blit(empty_board, (0, 0))
pygame.display.update()
# activates when the loop finishes, just makes sure everything shuts down properly
pygame.quit()
The expected result is the image on the screen in the top left corner. However when I run the program, I have an empty screen (pygame.QUIT still works).
When I run this code there is no error message, and I am completely lost about how to fix this.
first, make sure that the empty_board.png is in your working directory.
Second, you have to clear the screen before each frame using window.fill([255, 255, 255])
Finally, you could try using pygame.display.flip() instead of update()
My code would look like:
import pygame
pygame.init()
window = pygame.display.set_mode([640, 480])
doQuit = False
board = pygame.image.load("empty_board.png")
while not doQuit:
window.fill([255, 255, 255])
window.blit(board, (0, 0))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
doQuit = True
pygame.quit()
I have tried to set single pixels in pygame with pygame.PixelArray. Unfortunately, It looks like pygame automatically anti-aliases those pixels. This is what I have tried so far:
import pygame
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
WHITE = (255,255,255)
class GUI:
def __init__(self):
self.screen = pygame.display.set_mode((300, 300))
pygame.mouse.set_visible(True)
self.clock = pygame.time.Clock()
def gameloop(self):
running = True
while running:
self.screen.fill(WHITE)
# event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# drawing
# for some reason, everything gets anti-aliased
pixel_array = pygame.PixelArray(self.screen)
pixel_array[100][100] = BLACK
pixel_array[100][101] = BLUE
pixel_array[101][100] = BLUE
pixel_array[101][101] = BLACK
del pixel_array
# update full display
pygame.display.flip()
self.clock.tick(30)
def main():
pygame.init()
gui = GUI()
gui.gameloop()
pygame.quit()
if __name__ == '__main__':
main()
What I have got:
What I expected to get:
System:
Python version: 3.7.2 (64-bit)
OS: Windows 10 Home Version 1803 Build 17134.590
pygame version: 1.9.4
Display: Integrated in Lenovo-Laptop (1920 x 1080)
Processor: Intel-Core-i5-6300HQ
IGP: Intel HD Graphics 530
GPU: Nvidia GeForce GTX 960M
After a hint from Eric, I figured out that the problem wasn't caused by pygame, but by the display resolution settings. The display was scaled to 125% by default.
I don't know how to describe where you can find these settings in english since my Windows is set to german, so I made screenshots: