Why doesn't my simple python pygame program open a window? - python

I am trying to learn how to make a game of Snake in Python. I found a tutorial using pygame, but I'm having trouble making it work. Here's my code :
import os, pygame
os.environ["SDL_VIDEODRIVER"] = "dummy"
pygame.init()
dis = pygame.display.set_mode((400,300))
pygame.display.set_caption('Test')
while 1 :
pygame.display.update()
pygame.quit()
quit()
The problem is that the game window simply doesn't open. I get ALSA lib pcm.c:8424:(snd_pcm_recover) underrun occurred errors but I think those are related to the sound. Other than that, no message in the console.
The code is running in a debian 11 VM inside a Windows 7 host.

Delete the os.environ["SDL_VIDEODRIVER"] = "dummy"
From this
You can use PyGame without opening a visible display (e.g. for testing, or for integrating with other frameworks that have their own displays) by using SDL environment variables before you initialise pygame. Environment variables can be set with the os.environ dict in python.

As the documentation states, the dummy mode is designed to create an SDL environment without opening a window. Because in this case, we do actually want to create a window, You should remove the line os.environ["SDL_VIDEODRIVER"] = "dummy". This does also mean that you don't have to import the os module.

Related

Python Crash Course Alien Invasion issue

This is in regards to the book "Python Crash Course 2nd Edition".
After going through the "Drawing the Ship to the Screen" section in Chapter 12, I get a black screen, instead of a grey screen, and I'm not seeing the ship show up when I run my alien_invasion.py. I have tried running Matthes' downloadable resource file for that step, and I still get a black screen. I'm running these .py files from Sublime text, but have tried using terminal to run them (I get indent errors) and python IDLE to run them (gives me a pygame module not found error, though I know pygame is installed and found by Sublime).
Here is the code for the game that should no display a grey background and a ship at the bottom of the screen, if you have the ship image:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
def run_game(self):
"""Start the main loop for the game."""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
# Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
Im using Mac OS version 10.14.6.
Any solutions for this issue, or better practices or programs that I should be writing/running these game modules in?
Anyone with a Mac that has successfully installed pygame and/or has gotten alien_invasion to work?
One reply to my reddit post about this said they had a similar issue on Mac OS but when they tried on linux it worked fine...
Is there another alternative for Mac people to use short of installing linux on a separate partition or something?
Thanks for your help!
Found a solution on Eric Matthes's github. Uff da, pygame is not stable on python 3.8.2 yet...I needed to install the dev version of pygame to run with python 3.8.2.
From Eric's github:
The stable version of Pygame has not been updated to work with Python 3.8 yet. However, there is a recent development version that works with Python 3.8. To install it, run the following command:
$ python -m pip install pygame==2.0.0.dev6
You should use the same command you use to run a Python terminal session on your system, which might be python, python3, py, python3.8, or something else.
If you’ve had any issues running Pygame on macOS, this version of Pygame should address those issues as well.
I had the same issues, black screen and no ship. What solved the issue for me was, under settings, playing with the height and width. I'm a novice at this but I found that when I centered the ship instead of bottom center, the ship barely showed up at the bottom. Eventually I was able to center it at the bottom of the screen.
I had this issue with the black screen closing immediately after. The code has the ship in folder 'images/ship.bmp'. Make sure the destination is accurate. Mine was in a slightly different location as I have a project folder for the book.
Mine was 'Python Crash Course/Alien Invasion/images/ship.bmp'

Pygame headless setup

I am using pygame's joystick api to use a joystick with my project on a headless system, but pygame requires a "screen" so I have setup a dummy video system to over come this. It worked fine but now all of a sudden it gives me this error:
Traceback (most recent call last):
File "compact.py", line 10, in <module>
screen = display.set_mode((1, 1))
pygame.error: Unable to open a console terminal
Here is what I have as the headless setup that is supposed to over come this issue.
from pygame import *
import os
import RPi.GPIO as GPIO
os.environ["SDL_VIDEODRIVER"] = "dummy"
screen = display.set_mode((1, 1))
Pygame is trying to open a console which means you're running this script through ssh or cron or somewhere else that doesn't have access to the console. I would try skipping set_mode (since the dummy driver likely doesn't have modes to set) and just try to initialize the display. You can try running it as root which might give it access. You can also try telling it to use fbcon.
os.putenv('SDL_VIDEODRIVER', 'fbcon')
pygame.display.init()
If you don't have an actual monitor connected to the Raspberry Pi, pygame.display will not work. However, there are 2 ways to trick the system into creating a virtual display so that you can run Pygame without a monitor:
You can trick the raspberry pi into thinking there is a monitor attached by using a hdmi emulator dummy plug:
Alternatively, go to /boot folder, edit the config.txt file with sudo or root access, set:
hdmi_force_hotplug=1 (without the #)
And the pi will create a virtual display even if there is no actual monitor attached.

pygame headless no font [duplicate]

I am using pygame's joystick api to use a joystick with my project on a headless system, but pygame requires a "screen" so I have setup a dummy video system to over come this. It worked fine but now all of a sudden it gives me this error:
Traceback (most recent call last):
File "compact.py", line 10, in <module>
screen = display.set_mode((1, 1))
pygame.error: Unable to open a console terminal
Here is what I have as the headless setup that is supposed to over come this issue.
from pygame import *
import os
import RPi.GPIO as GPIO
os.environ["SDL_VIDEODRIVER"] = "dummy"
screen = display.set_mode((1, 1))
Pygame is trying to open a console which means you're running this script through ssh or cron or somewhere else that doesn't have access to the console. I would try skipping set_mode (since the dummy driver likely doesn't have modes to set) and just try to initialize the display. You can try running it as root which might give it access. You can also try telling it to use fbcon.
os.putenv('SDL_VIDEODRIVER', 'fbcon')
pygame.display.init()
If you don't have an actual monitor connected to the Raspberry Pi, pygame.display will not work. However, there are 2 ways to trick the system into creating a virtual display so that you can run Pygame without a monitor:
You can trick the raspberry pi into thinking there is a monitor attached by using a hdmi emulator dummy plug:
Alternatively, go to /boot folder, edit the config.txt file with sudo or root access, set:
hdmi_force_hotplug=1 (without the #)
And the pi will create a virtual display even if there is no actual monitor attached.

vlc mac python bindings video output and location of vlc.py

I am hoping that someone can help with a Python bindings output question (using vlc.py)
I have a basic test script that uses vlc.py which runs but does not play the video.
import vlc
def setup_player(filename):
vlc_instance = vlc.Instance('--no-audio', '--fullscreen')
player = vlc_instance.media_player_new()
media = vlc_instance.media_new(filename)
player.set_media(media)
print media.get_mrl() # File location to get title
print player.get_length() #Time duration of file -1 means there is no media
print player.get_state() #Player's state
player.play()
setup_player('foo.mp4')
This outputs
file:///Users/admin/Sites/pythontest/foo.mp4
-1
State.NothingSpecial
I am unsure where to install the vlc.py module and hoping someone can help. I'm on MacOs, VLC 2.0.9, Python 2.7.3. Running python through the terminal.
At the moment I have the vlc.py module in the same directory as my test script - and outside of the VLC.app directories and although the script is executing without errors it isn't playing the video or returning any parameters about the specified mp4 file.
Apologies for a banal question! Any help very gratefully received.
It seems that the player.play() function is not blocking, but instead returns immediately.
If the Python script then terminates, the player is destroyed right after it has been created.
If you look at the example player in vlc.py, it has a while True loop at the very end that basically reads key presses over and over again in order to implement a simple user interface.
So if you simply add
while True:
pass
at the end of your function, it should continue playing (terminate with CTRL+C until you implement some sort of user input handling).
As for "installing" the script: Unfortunately, the vlc.py module they provide is just that, a simple stand-alone Python module. It's not packaged as a setuptools distribution that you could just install with pip or easy_install like most other Python modules. That means you can (or rather have to) drop it into a location that will be in sys.path yourself.
The current working directory where you launch your script from works for that, but if you want a more permanent location you could drop it into your Python's site-packages (/Users/<your-username>/Library/Python/2.7/lib/python/site-packages for example if you're using the standard OS X framework Python).
Since the API calls succeed, it means that the bindings work correctly. The problem here is rather that the macos x video output module is not able to instanciate its own window. It must be embedded in a native Cocoa widget.
You can use the qt example from the vlc repository or use the x11 video output module, combined with the MacOS X X11 server (which has to be installed for recent versions of MacOS X).

Pygame error "Video system not initialized" on ubuntu server with only terminal

I'm using pygame on a PC (PC-104) with ubuntu server, for this reason it only has terminal, not UI.
On my laptop the code works perfecly, running the code on the terminal "eg: python game.py", but on the PC104 it gives "Video system not initialized", I read the error is shown because it is a way to use events on a system without UI?
Thanks.
Thank for your answer jsbueno. I was able to found a solution a few weeks ago but forget to answer the question.
I wasn't able to run any pygame script with any other library than X11. But I found that one can run the script with no graphics library. Just setting the SDL_VIDEOLIBRARY enviroment variable to "dummy".
This is posible on bash but I prefer to do it on python:
os.environ["SDL_VIDEODRIVER"] = "dummy"
With this I was able to run the pygame script, detect joystick events, etc.
It is possible to run pygame programs in a system without X11 if you set it to use framebuffer or vgalib - the docs even talk about using aalib (which would display graphics using ascii art on the terminal.)
This part of the documentation has it:
Pygame will select from one of several internal display backends when
it is initialized. The display mode will be chosen depending on the
platform and permissions of current user. Before the display module is
initialized the environment variable SDL_VIDEODRIVER can be set to
control which backend is used. The systems with multiple choices are
listed here.
Windows : windib, directx
Unix : x11, dga, fbcon, directfb,
ggi, vgl, svgalib, aalib
So, what you have to do is set the SDL_VIDEODRIVER environment variable before starting your code. And being shure the proper lib. is installed.
For more information:
http://www.pygame.org/docs/ref/display.html

Categories

Resources