Pygame Window created in the background - python

When I start my program that has to open pygame window, it opens it behind the current window. What have I to write to make a focus on pygame window and it won't be as background? This is for a game for mathematics revision so I need to use the python shell as well, in this example for (1+1).
This is the code I run. (just as an example)
import pygame
play = input("DO you want to play the game(y,n): ")
if play == "y":
pygame.init()
font = pygame.font.SysFont("None", 24, bold = False, italic = False )
Screen = pygame.display.set_mode((800, 600))
black = (0,0,0)
Screen.fill(black)
pygame.display.set_caption("Snake Game")
pygame.draw.rect(Screen, (218,123,255), ((0,0),(600,20)),0)
pygame.draw.rect(Screen, (0,197,243), ((0,20),(800, 580)), 16)
pygame.display.update()
#Play game for some time
Add = input("1 + 1 = ")
#Continue game on the pygame window

The only way to have the system position the pygame window in front of all the other ones is to not use the Python Shell.
Aside from doing that I do not think that there is any way to change how the system positions the window in pygame. I haven't found anything that changes whether it is positioned behind or in front of the current window. Correct me if I am wrong but I would guess that is the OS's job.
Thus, you must do everything in Pygame or else you will have the user switching between windows.
To fix this problem:
Remove all uses of the input function and use of the Python shell.
Implement a way to ask the mathematics questions in Pygame using font rendering
Implement a way to let the user type in an answer and enter it in. This can be done using font rendering and input handling.
I hope this answer helped you and if you have any further questions please feel free to post a comment below!

Related

How come I can't give my pygame window a name or an icon? [duplicate]

This question already has an answer here:
Icons are not displayed properly with pygame
(1 answer)
Closed 1 year ago.
A screenshot of me running my code is below
and here is my actual code:
import pygame
pygame.init()
#create the screen
screen = pygame.display.set_mode((800, 600))
Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo-flying.png')
pygame.display.set_icon(icon)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
I don't understand why it's not working. My code looks right, my icons in my directory, but nothing is coming up. Is it something I forgot to download? Is my code wrong?
This is the tutorial I'm following: https://www.youtube.com/watch?v=_HF852IONl8
One last thing that might be important to know is that even when I run my window without trying to change the title and icon, it's blank. This leads me to believe that there's a package I still haven't downloaded but I really don't know.
First of all change the pixel size of this image 'ufo-flying.png' to 32 x 32. To do this open this image with any photo editor app on pc. Choose the "resize" option. Now change the width and height to 32 x 32. You may use this site to change the pixels of this image. https://www.reduceimages.com/ Now save this image to the folder which contains this python code file(main.py). If you are using Pycharm then you can find this folder in the "PycharmProjects" folder on your pc. After doing this, run your code and it will work fine. Cheers!
See pygame.display.set_icon():
[...] Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode() to create the icon before the display mode is set.
Set the icon before screen = pygame.display.set_mode((800, 600)):
icon = pygame.image.load('ufo-flying.png')
pygame.display.set_icon(icon)
screen = pygame.display.set_mode((800, 600))
In addition, the size of the icon is limited:
[...] You can pass any surface, but most systems want a smaller image around 32x32.
If the icon is not displayed, try a smaller icon.

Is there a way to make the message box show up in front of a PyGame Window?

For school, we have to code this dumb zombies game but whatever, onto the question.
I'm using the module 'ctypes' to get a message box in python but whenever we use it, the message box is showing up below the PyGame Window, which is really annoying, because we have to click on the tab at the bottom and it's just a glorified pain. Here's the code:
answer = ctypes.windll.user32.MessageBoxW(0, "Save survivor using ammo?", "Oh no, a zombie is approaching!", 4)
if answer == 6:
survivor()
ammo -= 1
It's a prompt that asks to save the survivor or abandon them, but the message box keeps showing up at the bottom. Is there some kind of parameter that I can apply that puts it in front of the pygame window?
MessageBox supports the uType flag MB_TOPMOST (0x00040000):
MB_YESNO = 4
MB_TOPMOST = 0x40000
uType = MB_YESNO | MB_TOPMOST
answer = ctypes.windll.user32.MessageBoxW(
0, "Save survivor using ammo?", "Oh no, a zombie is approaching!", uType)

Pygame, the window becomes irresponsive when I try to click it

I'm working on a game with Pygame and it was going well...until it decided to not respond. Here's my code:(sorry if the formatting doesn't work im new to stackoverflow)
#MODULES USED (use from to make calling functions easier)
from random import *
from pygame import *
import pygame
from pygame.locals import *
pygame.init()
from time import *
#INITIALISE THE PYGAME WINDOW
pygame.event.pump()
screen = display.set_mode([500, 500])
blue = [230, 242, 255]
screen.fill(blue)
pygame.display.update()
default = pygame.image.load("default.jpg")
screen.blit(default, (0,0))
pygame.display.update()
click = pygame.mouse.get_pressed()
#BASIC HEXAPAWN
#ALL POSSIBLE COMPUTER'S MOVE BOARDS AS ARRAY HERE
#TThe moves from the board images are left to right
class Board:
def __init__(self, board, moves):
self.board = board
self.moves = moves
boards1 = [pygame.image.load("a1.jpg"), pygame.image.load("a2.jpg"), pygame.image.load("a3.jpg")] #move1 boards
#irrelevant stuff removed, just initialising the other boards.
#GAME MAIN LOOP
while True:
#START GAME - 1st move
print("You play as O, computer is X")
currentboard = "O O O\n# # #\nX X X"
print(currentboard)
#PLAYER MOVE 1
screen.blit(boards1[0], (0, 250))
pygame.display.update()
if boards1[0].get_rect().collidepoint(pygame.mouse.get_pos()) and click:
screen.blit(boards1[0], (0,0))
pmove = 0
#note: I haven't added the other board options yet.
currentboard = boards1[pmove]
#[insert more unnecessary code here]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.quit()
Basically whenever I run the code, the Pygame window looks alright, but when I try to click on the image it just stops responding. Also the window is always stuck on a loading cursor, idk why.
I've tried everything I could find but, nope, not working.
If anyone can help then I'd appreciate it.
Thanks :)
Eleeza
edit:i didnt know others could edit my posts too
Clearing some stuff up, when I ran my code, there were no errors, no Traceback the only problem is the unresponsive thing.
Also sorry im really bad at explaining things :/
There are a few things going on, but the main one is that you have you click variable set only once when the program starts.
Move click = pygame.mouse.get_pressed() inside of the main loop.
If you do that and it still hangs, you should show the rest of your code.
Also, the full code is not there, so I can't be 100% sure, but I don't think that break should be there.

Tab out of Pygame fullscreen window without crashing it

So I'm using Pygame to create a fancy display for a program I am writing. I chose Pygame because it's easy to get started and does a great job with animations. I want the display to be as big as I can make it so as much information can be shown as possible. Here is the kicker however, I still want to be able to get to the console of the program.
Pygame forces a fullscreen window to the front, so you cant tab out, and moving the windows to another windows desktop crashes the display. I would do a key trick to switch the pygame mode, but I cannot use pygame.event.get() because of how the program the threaded.
Is there a way to make it a full-screen window so that I can tab out and leave it up in the background? I dont really want it to just be a normal window because it is not as big that way.
The display crashes after I tab out and back in, here is what that looks like:
I also get a non-zero exit code: -805306369 (0xCFFFFFFF)
Here is a broken down version of the code that still gives me this error, you'll notice there are some things in here you wouldn't have if this was your full program, but I wanted to retain as much architecture as I could.
import pygame
import os
BACKGROUND = (9, 17, 27)
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
pygame.init()
pygame.font.init()
infoObject = pygame.display.Info()
SIZE = (infoObject.current_w, infoObject.current_h)
X_CENTER = SIZE[0]/2
Y_CENTER = SIZE[1]/2
# create a borderless window that's as big as the entire screen
SCREEN = pygame.display.set_mode((SIZE[0], SIZE[1]), pygame.NOFRAME)
clock = pygame.time.Clock()
TextFont = pygame.font.SysFont('Courant', 30)
class DisplayState:
state = type(bool)
def __init__(self):
self.state = True
def get_state(self):
return self.state
def change_state(self, new_state):
self.state = new_state
def main(display_state_object):
running = True
while running:
if display_state_object.get_state():
SCREEN.fill(BACKGROUND)
pygame.display.flip()
else:
return 1
return
if __name__ == "__main__":
main(DisplayState())
EDIT
I think it is a multi-threading problem! See this code:
Produces Error
def start_display():
display(params)
def display(params):
pygame loop
if __name__ == "__main__":
display_thread = threading.Thread(target=start_display)
display_thread.start()
Does not produce error
def display(params):
pygame loop
if __name__ == "__main__":
display_thread = threading.Thread(target=display(params))
display_thread.start
# marker
One problem with the version that does work, the program does not seem to be continuing forwards outside the thread (ie the marker is never reached). Is this how the threading library works? It may explain why I had the middle man function present. Maybe this is a different problem and deserves its own question?
EDIT
Setting up the thread like this allows the main thread to continue, but brings back the pygame error:
threading.Thread(target=display, args=(DisplayState(),))
There's no easy way to do this on windows/sdl using the real fullscreen mode, and the usual way to solve this is to use a borderless window.
Here's how to create such a "fake" fullscreen window in pygame:
import pygame
import os
# you can control the starting position of the window with the SDL_VIDEO_WINDOW_POS variable
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
pygame.init()
# now let's see how big our screen is
info = pygame.display.Info()
# and create a borderless window that's as big as the entire screen
screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.NOFRAME)
You have to call one of the pygame event functions (e.g. pygame.event.pump() or pygame.event.get()) each frame or the window will become unresponsive and the program will appear to have crashed. If you call one of those functions, you should be able to press Alt+Tab (in Windows) to get back to the desktop without crashing the program (if you select the desktop, the window will be minimized and if you select another window, it will just be brought to the front).
def main(display_state_object):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
# Press Esc to quit.
if event.key == pygame.K_ESCAPE:
running = False
if display_state_object.get_state():
SCREEN.fill(BACKGROUND)
pygame.display.flip()
else:
return 1
return

pygame dual monitors and fullscreen

I am using pygame to program a simple behavioral test. I'm running it on my macbook pro and have almost all the functionality working. However, during testing I'll have a second, external monitor that the subject sees and the laptop monitor. I'd like to have the game so up fullscreen on the external monitor and not on the laptop's monitor so that I can monitor performance. Currently, the start of the file looks something like:
#! /usr/bin/env python2.6
import pygame
import sys
stdscr = curses.initscr()
pygame.init()
screen = pygame.display.set_mode((1900, 1100), pygame.RESIZABLE)
I was thinking of starting the game in a resizable screen, but that OS X has problems resizing the window.
Pygame doesn't support two displays in a single pygame process(yet). See the question here and developer answer immediately after, where he says
Once SDL 1.3 is finished then pygame will get support for using multiple windows in the same process.
So, your options are:
Use multiple processes. Two pygame instances, each maximized on its own screen, communicating back and forth (you could use any of: the very cool python multiprocessing module, local TCP, pipes, writing/reading files, etc)
Set the same resolution on both of your displays, and create a large (wide) window that spans them with your information on one half and the user display on the other. Then manually place the window so that the user side is on their screen and yours is on the laptop screen. It's hacky, but might a better use of your time than engineering a better solution ("If it's studpid and it works, it ain't stupid" ;).
Use pyglet, which is similar to pygame and supports full screen windows: pyglet.window.Window(fullscreen=True, screens[1])
Good luck.
I do not know if you can do this in OS X, but this is worth mentioning for the Windows users out there, if you just want to have your program to run full screen on the second screen and you are on windows, just set the other screen as the main one.
The setting can be found under Rearrange Your Displays in settings.
So far for me anything that I can run on my main display can run this way, no need to change your code.
I did something silly but it works.
i get the number of monitors with get_monitors()
than i use SDL to change the pygame window's display position by adding to it the width of the smallest screen, to be sure that the window will be positionned in the second monitor.
from screeninfo import get_monitors
numberOfmonitors = 0
smallScreenWidth = 9999
for monitor in get_monitors():
#getting the smallest screen width
smallScreenWidth = min(smallScreenWidth, monitor.width)
numberOfmonitors += 1
if numberOfmonitors > 1:
x = smallScreenWidth
y = 0
#this will position the pygame window in the second monitor
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
#you can check with a small window
#screen = pygame.display.set_mode((100,100))
#or go full screen in second monitor
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
#if you want to do other tasks on the laptop (first monitor) while the pygame window is being displayed on the second monitor, you shoudn't use fullscreen but instead get the second monitor's width and heigh using monitor.width and monitor.height, and set the display mode like
screen = pygame.display.set_mode((width,height))
display = pyglet.canvas.get_display()
display = display.get_screens()
win = pyglet.window.Window(screen=display[1])
------------------------------------------------------
screen=display[Номер монитора]
------------------------------------------------------
display = pyglet.canvas.get_display()
display = display.get_screens()
print(display) # Все мониторы которые есть

Categories

Resources