The following code causes my game to shut down. I do not know what is the problem with this code.
pygame.font.init()
font=pygame.font.Font(None, 36)
text = font.render("Game Over", 1, (10, 10, 10))
background_image.blit(text, (0,0))
pygame.font.quit()
I want to display this text in the top left corner of the screen. Thanks.
It works for me -
I'd guess your platform is not getting along quite well with the "None" font you are passing - try passing a complete path to a (in disk) font file (a TTF file) as the first parameter to pygame.font.Font -
Also, save your script and run it from the command shell to get hold of proper error messages.
Also, there is no need to call "pygame.font.quit" - just call "pygame.quit" when exiting your program.
Related
I'm making an interactive map for my class, using Zelle's graphics.py . I got the map , and the data all set, but I can't figure out how to get the graphics window to update and draw new objects (route markers) on the map, after recieving user input. I've tried using a for loop and doing the update() method, no luck. Once the window is up, I'm supposed to get user input and the map is supposed to reflect that, and I can't figure out that last little bit.
from graphics import *
win = GraphWin("map" , 500,500)
win.setBackground("black")
textbox = Entry(Point(250,250),10)
textbox.draw(win)
text = textbox.getText()
if text == "hello":
line = Line (Point(100,100), Point(200,100))
line.draw(win)
win.getMouse()
win.close()
So once the desired User input is recieved how do i get the changes to show up on screen?
Your primary issue is that text = textbox.getText() executes before you get a chance to type input. This SO answer discusses this issue of Zelle graphics lacking an event model. What it recommends is you ask your user to click the mouse after entring input to force the program to wait:
from graphics import *
win = GraphWin("map", 500, 500)
textbox = Entry(Point(250, 250), 10)
textbox.draw(win)
win.getMouse()
text = textbox.getText()
if text == "hello":
line = Line(Point(100, 100), Point(200, 100))
line.draw(win)
win.getMouse()
win.close()
You can do that in a loop to get all your locations and use a keyword like "done" to break out of the mouse wait loop.
Your secondary issue is you were drawing a black line on a black background so you'd never see it had it worked correctly.
I am writing a python program that gradually changes an image step by step, adjusting each pixel by a small amount in each step. To get a visualization of what the program is doing during runtime, I want it to display the image at each step, always overwriting the currently shown image so that it doesen't open bunch of display windows.
I already tried matplotlib, opencv and skimage, with their according possibilities to display an image and update the frame content in the course of the program:
# using scimage
viewer = ImageViewer(image)
viewer.show(main_window=False) # set the parameter to false so that the code doesn't block here but continues computation
..other code..
viewer.update_image(new_image)
# using matplotlib
myplot = plt.imshow(image)
plt.show(block=False)
.. other code..
myplot.set_data(new_image)
plt.show()
# using opencv
cv2.imshow('image',image)
.. other code ..
cv2.imshow('image', new_image)
I always ran into the problem that when it was supposed to open a frame with an image, it did not display the image but only a black screen. Weirdly enough, when I ran the code in IntelliJ in debug-mode and hit a breakpoint after the display-function, it worked.
What can I do so that it is displayed correctly when running the program normally and not with a breakpoint?
Here's the thing, I think your program does work, except it does and finishes unless you tell it to pause, which is why your breakpoint strategy is working.
Try pausing after showing image -
You can ask for user input. It'll pause until you enter some input to the program.
Put the program thread to sleep for some specified amount of time. This'll freeze your program for some given specified time, but you'll be able to see the image if it's already rendered.
Edit -
Since opencv's waitKey method is working for you now, you can use this method again to prevent the program from closing image window. Use waitKey(0) as your last program statement. It waits for a key press indefinitely, and returns the pressed key's code. Press any key to continue (but remember to have your image window in focus or it won't work), and your program should close if it's used in the end.
Also, I've striked earlier suggested options for pausing a program, because I'm unsure if it would've helped. I think waitKey method is more complex, and helps pause the program without freezing it.
Well, I am still not sure what exactly your goal is but here is a code piece that modifies an image inside of a window whenever the upper button is pressed.
from tkinter import Tk, Canvas, Button, Label, PhotoImage, mainloop
import random
WIDTH, HEIGHT = 800, 600
def modify_image():
print ("modifiying image...")
for x in range(1000):
img.put ( '#%06x' % random.randint(0, 16777215), # 6 char hex color
( random.randint(0, WIDTH), random.randint(0, HEIGHT) ) # (x, y)
)
canvas.update_idletasks()
print ("done")
canvas = Canvas(Tk(), width=WIDTH, height=HEIGHT, bg="#000000")
canvas.pack()
Button(canvas,text="modifiying image",command=modify_image).pack()
img = PhotoImage(width=WIDTH, height=HEIGHT)
Label(canvas,image=img).pack()
mainloop()
The function modify_image() adds 1000 random pixels to the image within the main window. Note the tkinter module is a default python module.
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) # Все мониторы которые есть
This question already has answers here:
How can I convert pygame to exe?
(6 answers)
Pygame2Exe Errors that I can't fix
(3 answers)
Closed 1 year ago.
I want to be able to convert .py to .exe for python 3 pygame 1.9.4 projects (on my Windows 10 computer), and I have successfully converted some files by using auto py to exe (one file, console based):
https://nitratine.net/blog/post/auto-py-to-exe/.
For example, I tried to convert the code that is quite far up on this site:
http://openbookproject.net/thinkcs/python/english3e/pygame.html. That is:
import pygame
def main():
""" Set up the game and run the main game loop """
pygame.init() # Prepare the pygame module for use
surface_sz = 480 # Desired physical surface size, in pixels.
# Create surface of (width, height), and its window.
main_surface = pygame.display.set_mode((surface_sz, surface_sz))
# Set up some data to describe a small rectangle and its color
small_rect = (300, 200, 150, 90)
some_color = (255, 0, 0) # A color is a mix of (Red, Green, Blue)
while True:
ev = pygame.event.poll() # Look for any event
if ev.type == pygame.QUIT: # Window close button clicked?
break # ... leave game loop
# Update your game objects and data structures here...
# We draw everything from scratch on each frame.
# So first fill everything with the background color
main_surface.fill((0, 200, 255))
# Overpaint a smaller rectangle on the main surface
main_surface.fill(some_color, small_rect)
# Now the surface is ready, tell pygame to display it!
pygame.display.flip()
pygame.quit() # Once we leave the loop, close the window.
main()
The .exe file ran as it should when opened. However, some programs that I write are only partially functioning after the conversion.
One such program would be:
import pygame as pg
def main():
pg.init()
pg.display.set_caption('Some Caption')
screen = pg.display.set_mode((640, 480))
afont = pg.font.SysFont("some_font", 32)
done=False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
screen.fill(0)
sometext = afont.render("Amazing text"
.format(0, 0), True, (250,200,250))
screen.blit(sometext, (10, 50))
pg.display.flip()
if __name__.endswith('__main__'):
main()
pg.quit()
After converted to exe, when I open it, some text about pygame appears and also the screen that is meant to pop up, showing the caption which I've set ('Some Caption'). The screen which popped up is however black and closes after a while, not showing what it should. However, I did get my exe file without any errors (which I could see anyway in the Output of the GUI which I used for the conversion i.e. auto py to exe). So in search of solutions I found this website:
https://nitratine.net/blog/post/issues-when-using-auto-py-to-exe/.
There were alot about error messages and general information but the thing I saw about program that opens but not doing what it should before closing was:
The Terminal Just Opens and Closes But There Are No Errors If you
double click to run your Python script, what happens? Does it open and
close also? That means this tool has done it's job correctly and the
script is finishing just like it should.
You most likely think the output should stay visible because you are
always using IDLE or an IDE and that's what those tools do. Add a
statement like input() at the end of your script to block execution
and wait for you to press enter before closing.
This, is not the solution for my problem since my program works if I double click on the python script. However, I think that it has a good point i.e that there might be something in my code that do not handle the conversion well, which is probable since the code from http://openbookproject.net/thinkcs/python/english3e/pygame.html did work after being converted to .exe when the same method was used.
My question is therefore, what is it that make my code not work after the conversion from .py to .exe?, and in that case, in what way might it be fixable?. The knowledge of what works and not when it comes to the converting .py to .exe would enable more programs to function correctly when they are .exe.
Thank you
import pygame
import os
import sys
import time
from pygame.locals import *
pygame.init()
#Colours here
RED = pygame.Color(150, 0, 0)
GREEN = pygame.Color( 0, 150, 0)
BLUE = pygame.Color( 0, 0, 150)
BLACK = pygame.Color( 0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
FPS = pygame.time.Clock()
WIDTH = 1024
HEIGHT = 768
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Penaldo v0.1')
#Set BACKGROUND to an instance of pygame.Surface, which will get its coordinates from the previous ones we assigned to the game's display
BACKGROUND = pygame.Surface((SCREEN.get_width(), SCREEN.get_height()))
SCREEN.blit(BACKGROUND, (0, 0))
key_press = pygame.key.get_pressed()
class Player():
def __init__(self):
#Try to load our sprite.
#'r' makes it a raw string so it ignores escape sequences
self.player = pygame.image.load(r"\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png")
self.p_rect = self.player.get_rect()
#Spawn the player just in the middle of our screen
self.p_rect.centerx = WIDTH / 2
self.p_rect.centery = HEIGHT / 2
def move(self):
if key_press[UP]:
self.p_rect.y -= 5
elif key_press[DOWN]:
self.p_rect.y += 5
elif key_press[LEFT]:
self.p_rect.x -= 5
elif key_press[RIGHT]:
self.p_rect.x += 5
while True:
for event in pygame.event.get():
if event.type == QUIT:
#Some IDLE friendliness (prevents from hanging)
pygame.quit()
sys.exit()
BACKGROUND.fill(GREEN)
p1 = Player()
# FOR THE GAME TO WORK you have to include this one inside main while-loop (no display update = no game)
pygame.display.update()
FPS.tick(40)
The full error message is:
Traceback (most recent call last):
File "C:\Users\NZXT\Documents\GameLab\Penaldo\game\version1\Penaldo.py", line 79, in <module>
p1 = Player()
File "C:\Users\NZXT\Documents\GameLab\Penaldo\game\version1\Penaldo.py", line 49, in __init__
self.player = pygame.image.load(r"\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png")
error: Couldn't open \..\..\resources\mario_sprite_by_killer828-d3iw0tz.png
I read a few questions such as Python 2.6: "Couldn't open image" error, error: Couldn't open Image and I've tried to implement the different tips but the window just goes black and hangs.
I have a few ideas.
Perhaps you entered the image name incorrectly.
Or the folders in the path don't exist.
You may have misplaced the file.
You didn't consider your operating system.
And here are a few suggestions:
Rather than backslashes, use os.path.join('..', '..', 'resources', 'mario_sprite_by_killer828-d3iw0tz.png') inside pygame.image.load. This will correctly load for Linux, Windows, and Mac which ever one you may be using.
Try using a more organized arrangement so that backtracking that far will not be necessary.
Check and/or rename the file to ensure you're using the correct path. Make sure file is actually a png.
Use os.chdir to change the current directory to the folder in which the image is contained then use pygame.image.load('mario_sprite_by_killer828-d3iw0tz.png') as you normally would.
Give these a try. By the way, your key events won't work as expected because the key_press variable isn't continuously updated, you simply initialized it at the beginning.
Looking at that /../../ I see you are trying to look for a dynamic file path depending on the users file path to the image? That isn't how it works, and that is why you are getting that error. It can't find the .PNG file because there is no such thing as :
\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png
You can look at this article that explains it well: Relative paths in Python
Usually to ensure the image file can be loaded without raising errors about not being able to find your image, put that image in the same folder as your program. As for PyCharm users, just copy and paste the file into your current project that has the correct program. Using os.path.join() might be better if you dislike doing it the other way. Try going to the Pygame Docs for more information if you have time. Your problem is that you are using backward slashes () instead of using forward slashes (/). You should change your path from:
\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png
to:
/../../resources/mario_sprite_by_killer828-d3iw0tz.png
Credit for this answer and the real explanation of your problem can be found in this problem in Stack Overflow: Python 2.6: "Couldn't open image" error
I hope this helps you! Oh, if the question link above doesn't help, use the Pygame Docs link instead.