Trying to design and call open a basic customized pygame window that pops up right after the program starts. The window I'm producing gets minimized by default instead of just opening. It's also not updating the color, and it immediately crashes when I open the tab that it's in.
# I'm running Windows 10 with Spyder (Python 3.9), if that matters
# This is the entire code:
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter Friends (Version 1.0)")
# Color presets
WHITE = (255,255,255)
BLACK = (0,0,0)
# Event loop
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
WIN.fill(WHITE)
pygame.display.update()
pygame.quit()
# Ensure the game only executes in the file named: space_shooter.py
if __name__ == "__space_shooter__":
main()
For context, I'm a beginner level student just trying to generate a basic white display for now, with dimensions: 9ooW x 500H, and centered ideally so that the pygame window's center is superimposed onto the center of my computer screen. I want this window to pop up as soon as the program starts running, and it should stay open for an indefinite amount of time, or until exited from with the X icon.
It seems to be producing the window right away as intended, but it places it into a minimized tab instead of an opened window display for some reason. The window pops open if I click on the tab, but it's filled in with black regardless of what values I insert into WIN.fill(R,B,G) as arguments. Also, the program immediately becomes non-responsive with the message: (Not responding) next to the game's title (at the top of the pygame window, not in the Spyder terminal).
Seems like it's not able to update for some reason, possibly causing it to crash, but I'm not really sure. I'm not getting any runtime or syntax errors from Python, but I do get a "Python is not responding" message from Windows in the pygame window as well as whenever I try to close the window using the X icon. Any help is much appreciated!
The problem is in the following line:
if __name__ == "__space_shooter__":
The __name__ variable will not contain the file name of the current script. If the script is ran directly, it will contain "__main__". If the script is imported by another script, it will contain the file name of that other script.
In order to check the script's file name, which you according to the comment wanted to do, you have to use the __file__ variable. The only problem is that the __file__ variable does not only containt the file name, but also the file path and the file extension. That's why I would use the str.endswith function, which checks whether a certain string ends with a given string. There are also some more complicate and reliable ways, but I will leave it to this:
if __file__.endswith("space_shooter.py"):
However, it is more common to check whether the current file is being ran directly instead of being imported from another file. This allows other files to import and use the functions and classes present in the file, without that everything in the file is ran too.
For this, you have to use the __name__ variable:
if __name__ == "__main__":
As said above, the __name__ variable will contain "__main__" when the file is ran directly. Thus we can compare __name__ with it to know whether the file is ran directly or not.
For more information on the __name__ variable, there is more explanation and a useful example.
Related
I need to modify a script in psychopy. The thing I need is the subject to press and hold a buttom in the keyboard, but I'd like to have two responses: one when he/her presses it (and the windows with text has to change), and the second when he/her releases it (and the windows with text has to change again).
I am using event.getKeys function of psychopy, and then I'm using keyboard library.
after inizializing the window screen and the text and importing psychopy and the functions I need and keyboard library as key.
intro.draw()
win.flip() # reset the clock to record a response time and clear events
event.clearEvents('all')
event.globalKeys.clear() #to avoid problems with the keys you pressed before
intro_loop = True
while intro_loop:
intro_keys = kb.getKeys(["space"], waitRelease=True)
if key.is_pressed('space'):
intro.text = 'Hi, please follow these instructions :) '
intro.draw()
win.flip() # reset the clock to record a response time and clear events
if len(intro_keys):
win.close()
intro_loop = False
I did the same in another script (just to try) but instead of having a window text screen I printed two different things, and it worked. in this script, instead, it completely ignores the function "key.is_pressed".
do you have any ideas?
I'm writing a python curses game (https://github.com/pankshok/xoinvader).
I found a problem: in terminal emulator it works fine, but in tty screen blinks.
I tried to use curses.flash(), but it got even worse.
for example, screen field:
self.screen = curses.newwin(80, 24, 0, 0)
Main loop:
def loop(self):
while True:
self.events()
self.update()
self.render()
render: (https://github.com/pankshok/xoinvader/blob/master/xoi.py#L175)
self.screen.clear()
#draw some characters
self.screen.refresh()
time.sleep(0.03)
Constant time in sleep function is temporary, until I write 60 render calls controller.
How to implement render method correctly?
Thanks in advance,
Paul.
Don't call clear to clear the screen, use erase instead. Using clear sets a flag so that when you call refresh the first thing it does is clear the screen of the terminal. This is what is causing the terminal's screen to appear to blink. The user sees the old screen, then a completely blank screen, then your new screen. If you use erase then it will instead modify the old screen to look like the new one.
You may still see some odd flashing or other artifacts on slow terminals. Try calling screen.idcok(False) and screen.idlok(False) to stop curses from using insert and deletion operations to update the screen.
I'm new to Python and trying to learn graphics with John Zelle's graphics.py. I'm writing the Python scripts in MacVim and executing from the terminal (Mac OS 10.9.2) on Python 3. If I try to open a new window with GraphWin() the window opens briefly but then immediately closes.
Ex:
from graphics import *
win = GraphWin("circle",500,500)
c = Circle(point(100,100),30)
c.draw(win)
GUI elements with TkInter work just fine.
Any ideas why this might be happening?
Thanks!
If the statements you've shown in your question were entered as a script, and you just ran the script, then the problem is that the window is closed implicitly when the script ends. You will see in the very first example from the documentation (which also appears in the source code for graphics.py itself):
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # Pause to view result
win.close()
main()
Notice that the author has specifically included a statement to pause before closing the window.
If, instead of a script, you just type the statements in one by one at an interactive Python prompt, then as long as that Python prompt is open, the graphics window stays open (until you explicitly close it, or close the Python session).
I have two files, one to generate a world, and another to run the main code. However, the main screen keeps crashing for no reason. I think the world gen may also be broken, but it does at least pass on valid data to the main code.
# Main loop.
while RUNNING:
# Fill the screen.
screen.fill((0,0,0))
# Event handling.
for eventa in event.get():
if eventa.type == QUIT:
RUNNING = f
screen.fill(SCREENCOLOR)
# Draw the world.
for tile in WORLD:
if tile.surface == None:
pass
else:
screen.blit(tile.surface,tile.location)
# Draw the character
screen.blit(PLAYER["image"],PLAYER["loc"])
# Pygame commands clear up.
clock.tick(FPS)
screen.flip()
This code doesn't even fill the screen with white. This may just be too much data to handle, sorry if it is.
World generator
Main code
Previous question
I'm fairly sure that you aren't inserting too many things onto the screen. I believe that the problem is far more simple. You have said screen.flip() However, a surface object has no attribute called flip. You must be confused with the function pygame.display.flip() If you use this instead, the game shall display its visual output.
To display a wxPython window in full screen mode you use:
ShowFullScreen(True)
How do you get out of full screen though? I've tried the obvious way:
ShowFullScreen(True)
sleep(5)
ShowFullScreen(False)
This doesn't work though. When I run the script, nothing appears. After 5 seconds a window roughly 200x250 appears in the top-left corner of the screen, without anything inside of it. It doesn't appear to have any borders either.
If I change this to
showFullScreen(True)
then I get stuck with a full screen window that I have to use Alt + F2 -> xkill to get out of.
It looks like you need to Show() the window first. (According to the documentation, you shouldn't have to. Maybe this is a bug.) I tested on Mac OS X and Windows - they both exhibit issues if you don't call Show() first.
Also note that you shouldn't sleep in the main GUI thread. You'll hang the UI. Using CallLater is one potential solution, as shown in my example.
Working example:
import wx
def main():
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, 'Full Screen Test')
frame.Show()
frame.ShowFullScreen(True)
wx.CallLater(5000, frame.ShowFullScreen, False)
app.MainLoop()
if __name__ == '__main__':
main()
The documentation for ShowFullScreen reads:
ShowFullScreen(show, style=wx.FULLSCREEN_ALL)
Depending on the value of show parameter the window is either shown full screen or restored to its normal state.
Parameters:
show (bool)
style (long): is a bit list containing some or all of the following values, which indicate what elements of the window to hide in full-screen mode:
wx.FULLSCREEN_NOMENUBAR
wx.FULLSCREEN_NOTOOLBAR
wx.FULLSCREEN_NOSTATUSBAR
wx.FULLSCREEN_NOBORDER
wx.FULLSCREEN_NOCAPTION
wx.FULLSCREEN_ALL (all of the above)
So put your Full Screen toggle event/s in a Menu and start full screen mode with:
self.window.ShowFullScreen(True, style=(wx.FULLSCREEN_NOTOOLBAR | wx.FULLSCREEN_NOSTATUSBAR |wx.FULLSCREEN_NOBORDER |wx.FULLSCREEN_NOCAPTION))
Note that I omitted wx.FULLSCREEN_NOMENUBAR, in this way you will still be able to access the menu to turn full screen mode off again.