Pygame won't draw or fill screen - python

I posted this question yesterday, but I accidentally posted the wrong code. The program still doesn't work though. I am trying to make a game using pygame and my pictures come from an app called Pixel Art Studio. When I run the code though, I don't get any error messages, just a blank, white screen. I'm following a python programming book called Hello World but this is an original program. Please tell me what I've done wrong, here's my code.
import pygame, sys
guyimages = ['swordsmanguy.pxm','swordsmanstabup.pxm','swordsmanstabstraight.pxm','swordsmanstabdown.pxm']
legsimages = ['swordsman.legs1.pxm','swordsman.legs2.pxm','swordsman.legs3.pxm','swordsman.legs2.3.pxm','swordsman.legs2.2.pxm']
class avatar(pygame.sprite.Sprite):
def __init__(self):
pygame.sprit.Sprite.__init__(self)
self.image = pygame.image.load(guyimages["swordsmanguy.pxm"])
self.rect = self.image.get_rect()
self.rect.center = [250, 250]
self.angle = 0
def animate():
screen.fill([255,255,255])
screen.blit(avatar.image, avatar.rect)
pygame.display.flip
pygame.init()
screen = pygame.display.set_mode([960, 640])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
animate()
pygame.quit()

When you set self.image you reference the guyimages list like it's a dictionary. Additionally, there seem to be some parentheses missing from your code. Do you get an error in the terminal / command prompt window from which you run this script?

You are missing parentheses after animate in the code you posted.
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
animate #HERE MISSING PARENTHESES

Related

pygame.error: video system not initialized We are making a cave game [duplicate]

I am getting this error whenever I attempt to execute my pygame code:
pygame.error: video system not initialized
from sys import exit
import pygame
from pygame.locals import *
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = screen_width, screen_height = 600, 400
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
def game_loop():
fps_cap = 120
running = True
while running:
clock.tick(fps_cap)
for event in pygame.event.get(): # error is here
if event.type == pygame.QUIT:
running = False
screen.fill(white)
pygame.display.flip()
pygame.quit()
exit()
game_loop()
#!/usr/bin/env python
You haven't called pygame.init() anywhere.
See the basic Intro tutorial, or the specific Import and Initialize tutorial, which explains:
Before you can do much with pygame, you will need to initialize it. The most common way to do this is just make one call.
pygame.init()
This will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do. You can also easily initialize each pygame module by hand. For example to only initialize the font module you would just call.
In your particular case, it's probably pygame.display that's complaining that you called either its set_caption or its flip without calling its init first. But really, as the tutorial says, it's better to just init everything at the top than to try to figure out exactly what needs to be initialized when.
Changing code to this, avoids that error.
while running:
clock.tick(fps_cap)
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
pygame.quit()
if running:
screen.fill(white)
pygame.display.flip()
#this will fool the system to think it has video access
import os
import sys
os.environ["SDL_VIDEODRIVER"] = "dummy"
You just need to add
exit()
To stop running code
example :
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
exit() # Solution
You get an error because you try to set the window title (with set_caption()) but you haven't created a pygame window, so your screen variable is just a tuple containing the size of your future window.
To create a pygame window, you have to call pygame.display.set_mode(windowSize).
Good luck :)
If you doing pygame.init() then solve the problem video system initialized.
but you get the next error like:
(AttributeError: tuple object has no attribute 'fill') this.
this problem is solving when you doing this
screen = pygame.display.set_mode((600, 400))
but not doing like
screen = screen_width, screen_height = 600, 400
Then the full problem is solved.
I made some modifications to your code:
import os
import sys
import math
import pygame
import pygame.mixer
from pygame.locals import *
pygame.init()
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
while True:
clock.tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.fill(green)
pygame.display.flip()
For me, it was a problem because I didn't set pygame.quit() out of the loop at the end.
You have to add:
pygame.init()
Before you quit the display you should stop the while loop.
If you using class for your pygame window don't use pygame.init() in your class. Use pygame.init() at below libraries.
You need to initialized pygame using this command pygame.init
If the problem is not solved then following this step
this problem happens when you using a beta version.
so my suggestion is please use the new, old version(If now lunch 3.8 python, you
need to install python 3.7)
Now goto python terminal and install pygame (pip install pygame)
now the problem is solved...

Pygame: why am I receiving the error "video system not initialized" when I used init()? [duplicate]

I am getting this error whenever I attempt to execute my pygame code:
pygame.error: video system not initialized
from sys import exit
import pygame
from pygame.locals import *
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = screen_width, screen_height = 600, 400
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
def game_loop():
fps_cap = 120
running = True
while running:
clock.tick(fps_cap)
for event in pygame.event.get(): # error is here
if event.type == pygame.QUIT:
running = False
screen.fill(white)
pygame.display.flip()
pygame.quit()
exit()
game_loop()
#!/usr/bin/env python
You haven't called pygame.init() anywhere.
See the basic Intro tutorial, or the specific Import and Initialize tutorial, which explains:
Before you can do much with pygame, you will need to initialize it. The most common way to do this is just make one call.
pygame.init()
This will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do. You can also easily initialize each pygame module by hand. For example to only initialize the font module you would just call.
In your particular case, it's probably pygame.display that's complaining that you called either its set_caption or its flip without calling its init first. But really, as the tutorial says, it's better to just init everything at the top than to try to figure out exactly what needs to be initialized when.
Changing code to this, avoids that error.
while running:
clock.tick(fps_cap)
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
pygame.quit()
if running:
screen.fill(white)
pygame.display.flip()
#this will fool the system to think it has video access
import os
import sys
os.environ["SDL_VIDEODRIVER"] = "dummy"
You just need to add
exit()
To stop running code
example :
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
exit() # Solution
You get an error because you try to set the window title (with set_caption()) but you haven't created a pygame window, so your screen variable is just a tuple containing the size of your future window.
To create a pygame window, you have to call pygame.display.set_mode(windowSize).
Good luck :)
If you doing pygame.init() then solve the problem video system initialized.
but you get the next error like:
(AttributeError: tuple object has no attribute 'fill') this.
this problem is solving when you doing this
screen = pygame.display.set_mode((600, 400))
but not doing like
screen = screen_width, screen_height = 600, 400
Then the full problem is solved.
I made some modifications to your code:
import os
import sys
import math
import pygame
import pygame.mixer
from pygame.locals import *
pygame.init()
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
while True:
clock.tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.fill(green)
pygame.display.flip()
For me, it was a problem because I didn't set pygame.quit() out of the loop at the end.
You have to add:
pygame.init()
Before you quit the display you should stop the while loop.
If you using class for your pygame window don't use pygame.init() in your class. Use pygame.init() at below libraries.
You need to initialized pygame using this command pygame.init
If the problem is not solved then following this step
this problem happens when you using a beta version.
so my suggestion is please use the new, old version(If now lunch 3.8 python, you
need to install python 3.7)
Now goto python terminal and install pygame (pip install pygame)
now the problem is solved...

Pycharm - pygame shows only black screen

Here is the code
import pygame
pygame.init()
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
background = pygame.image.load("D:/Python/Pygame_200830/Background.png")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#screen.fill((0, 0, 255))
screen.blit(background, (0, 0))
pygame.display.update()
pygame.quit()
if I open this with VS code, it works well but, when I do this with Pycham. I can't see "backgound.png"
it's just only black display... and the only difference is IDE program.
I already added external function or something... only that backgound is the problem.
Could you let me know what is the reason...?
It is likely that the root cause of your problem is from Pycharm configurations or venv. see if you can open the python console. If you're new to pycharm, you can find the 'python console' option at the bottom of the screen.
Also here's a link that might help you. try some of the solutions there:
https://www.reddit.com/r/learnpython/comments/au6lvd/pycharm_code_works_but_doesnt_display_output/

Pygame. Mysterious error. Event referenced before assignment error

I am trying to make a python space shooter game with pygame.
The error I am getting is: local variable 'event' referenced before assignment.
It is mysterious, because sometimes it appears and breaks my program, and sometimes it doesn't. There is no pattern to the error occurrences, it just happens randomly out of nowhere.
I could run the program 2 times, and it would work fine, but then I run it again, and it gives this error.
The code that I am showing is a very simplified version of the real program, but it still produces the same error.
import pygame
WIDTH = 640
HEIGHT = 660
FPS = 30
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
BLUE = (0,0,255)
GREEN = (0,255,0)
pygame.init()
pygame.mixer.init()
gamedisplay = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game!")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
def quit_game():
pygame.quit()
def message_to_screen(msg, colour, x, y):#This function is used to display messages to the game display.
font = pygame.font.SysFont(None, 25)
text = font.render(msg, True, colour)
gamedisplay.blit(text, (x,y))
def start_screen():
global intro_running
intro_running = True
while intro_running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
if event.key == pygame.K_a:
main_game_loop()
gamedisplay.fill(WHITE)
message_to_screen("start screen: press \"a\" to start", RED, 200, 200)
pygame.display.update()#Updating the display.
def main_game_loop():
intro_running = False#I make intro_running equal False here so that when this subprogram starts, the start_screen subprogram will end
running = True
while running:
clock.tick(FPS)
pygame.mouse.set_visible(0)#Makes the mouse invisible.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
gamedisplay.fill(GREEN)
message_to_screen("Main game will be here", RED, 200, 200)
all_sprites.draw(gamedisplay)
all_sprites.update(event)#The event parameter needs to be passed, because some sprites in the group need it to check for events.
pygame.display.update()
start_screen()
The full error is:
Traceback (most recent call last):
File "C:/Users/Home/Documents/Python/pygame/test game/re-creation.py", line 106, in <module>
start_screen()
File "C:/Users/Home/Documents/Python/pygame/test game/re-creation.py", line 64, in <module>
main_game_loop()
File "C:/Users/Home/Documents/Python/pygame/test game/re-creation.py", line 98, in <module>
all_sprites.update(event)#All sprites will be updated, each frame.
builtins.UnboundLocalError: local variable 'event' referenced before assignment
All help will be greatly appreciated.
Thank you.
Your sprites probably doesn't need the event argument but it's your game...you can easily fix this by placing it inside the event loop, since your error was caused because event was never defined during the first iteration of the while loop since there wasn't any event therefore the variable event was never generated.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
all_sprites.update(event) # this will guarantee that there's an event
But you can also consider doing this to make sure the sprite will always get updated:
class mysprite(pygame.sprite.Sprite): # example sprite class
def __init__(self, event = None): # allow the event to have a default None argument
if event is None:
# do stuff without the event
return
# do stuff with the event
# the event loop snippet
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
all_sprites.update(event) # this will guarantee that there's an event
all_sprites.update() # without the event outside of the event loop in the while loop, where the all_sprites.update(event) used to be in your example, so the sprites will always get updated
In addition to what was provided in the other answer (you have to apply what is suggested there) there are also other causes of trouble with Pygame:
Pygame mysterious errors could have something to do with what else is going on the computer. I run your script thousand times without any error, BUT ... I witnessed while using a screenshot utility to capture the Pygame window a freezing display to a degree that I had to reboot the computer (but only if special timing of closing the Pygame window and doing the screenshot came together). From this experience I suggest in case the advice given in the other answer doesn't prevent your game from crash for what reason ever:
CHECK which of the applications running in background or foreground may have interfere with Pygame.
It could maybe be easy to detect as there are times the error occurs and times at which it doesn't, but if in addition a special timing of events of the application which interfere with Pygame is necessary for the error to occur it could be very hard to find.
There is no guarantee that this will solve your problem, but maybe it can.
If you want to witness yourself that Pygame handling of events and refreshing the display is not well designed just run a very simple Pygame application doing nothing else as showing an empty window with FPS of one frame per second (FPSclock = pygame.time.Clock() -> FPSclock.tick(1)). If on your box happens the same as on mine you will see the CPU being extremely busy with Pygame. Pygame is just a TOY - don't expect from it too much ...
Maybe you can find out how to modify your code to avoid that the special error occurs, BUT this is with high probability a kind of lottery game. I suppose there is no way to make Pygame run 100% safe from errors and problems under any circumstances. If you want that, switch to another known as stable and mature gaming engine.
It's life - if you gain something on one side you loose some on the other side. There is sure a price to pay for the ease of programming games with Pygame - maybe you can arrange yourself with accepting that it is not a problem if occasionally a mystic error comes out of nowhere?

PyGame any touchscreen

I am trying to create a simple program in which a user can move a shape on the screen using his finger (on a touchscreen).
this is my code so far:
import pygame
def main():
pygame.init()
DISPLAY = pygame.display.set_mode((1000,500),0,32)
WHITE = (255,255,255)
blue = (0,0,255)
DISPLAY.fill(WHITE)
pygame.mouse.set_visible(False)
pygame.draw.rect(DISPLAY, blue,(480,200,50,250))
pygame.display.update()
pygame.mouse.set_pos(480, 200)
while True:
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
pygame.draw.rect(DISPLAY, blue, (pos[0]-25,pos[1], 50, 250))
pygame.display. update()
DISPLAY.fill(WHITE)
main()
The problem is that when I touch the screen, nothing will happen until I move my finger. If I print the events I can see that there is no event listed until I start moving my finger, so that is probably the reason.
I want to be able to register the finger press (as an event I guess) on the screen even before it starts to move, is there anyway to do this using PyGame?
Thanks.
In case anyone is stumbling across this later, in pygame 2 there is much better touch support. You can install with
pip install pygame==2.0.0.dev6
(check the pygame github for the most recent version) And there are three new event types. pygame.FINGERDOWN, pygame.FINGERUP, and pygame.FINGERMOTION. The pygame.FINGERUP event registers the touch input right when the screen is touched instead of when the screen is released like pygame.MOUSEBUTTONDOWN
I have made a game that utilises a computer touch screen and manages the touch quite well by handling two types of events. One is pygame.MOUSEMOTION and the other one is pygame.MOUSEBUTTONDOWN. Both of them contain the attribute event.pos. Problem is, at least when it comes to my touch screen (Lenovo), that the initial touch is not registered by the event handler of pygame.
You can confirm this by printing all the events to the terminal while touching your screen. I get nothing until I release or move my finger but on release I get the event pygame.MOUSEBUTTONDOWN rapidly followed by pygame.MOUSEBUTTONUP.
I know that this doesn't really solve your problem, but it might perhaps help you in some way. Otherwise, check out Kivy. There might be a solution there.
import pygame
def main():
pygame.init()
DISPLAY = pygame.display.set_mode((1000,500),0,32)
WHITE = (255,255,255)
blue = (0,0,255)
DISPLAY.fill(WHITE)
pygame.mouse.set_visible(False)
pygame.draw.rect(DISPLAY, blue,(480,200,50,250))
pygame.display.update()
pygame.mouse.set_pos(480, 200)
while True:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN or event.type == MOUSEMOTION:
pos = event.pos
pygame.draw.rect(DISPLAY, blue, (pos[0]-25,pos[1], 50, 250))
pygame.display. update()
DISPLAY.fill(WHITE)
main()

Categories