So I just finished up with a good amount of learning python and working on learning pygame. So I am following along with this free online book, and the first thing of code in the book of making a window with hello world on the top is giving me an error:
Heres the code:
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Heres the error:
File "pygame.py", line 9
if event.type == QUIT:
^
IndentationError: expected an indented block
Thanks in advance!
As presented, this code works fine at this end. If you are still having a problem I suggest you look at tabs vs spaces in your editor.
Be aware that Python is a space sensitive language. The compiler actually cares whether there is a mix of spaces and tabs throughout the program.
Stick to one of either kind throughout your code and this will resolve the issue.
Related
I have a simple Pygame display:
pygame.init()
screen = pygame.display.set_mode((1024, 576))
clock = pygame.time.Clock()
while True:
for event in pygame.event.get(): # to handle clicks on the screen (prevent crash)
if event.type == pygame.QUIT:
pygame.display.quit()
if event.type == pygame.DROPFILE:
path = event.file
print(path)
pygame.display.update()
I'm currently testing the "drop file" event to use it in a project I'm working on. Unfortunately, when I drag a file onto the screen, the cursor turns into a "not allowed" sign and nothing happens when I drop the file. Why does it happen?
Without changing your code much (adding 'import pygame'), it doesn't work for me either. I droped a file and then the same happend for me what happend for you. Thats what I thought.
I first tried Python 3.8.6 with Pygame 1.9.6. Then I remembered, that I have an other installation of Python with 3.9.1 and Pygame version 2.0.0.
This second combination worked for me. I don't know which part made the difference in the end, but I think they did much work for pygame 2.0.0, so give it a try.
This works for me on Windows 10.
I´m a newbie on pygame, and i have this code for trying to do kind of a startscreen for a football game, this start screen has a static background image that is"img_start_screen" and the logo of the game that I want it to have a little animation that stops when it reaches the certain point on the screen, that logo is the variable "logo"
import pygame,sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((1280,720))
pygame.display.set_caption("CEFoot 3.0")
FPS=60
fpsClock=pygame.time.Clock()
img_start_screen=pygame.image.load("start_screen.gif")
logo=pygame.image.load("logo8bit.png")
logox=390
logoy=0
direction="down"
while True:
window.blit(img_start_screen,(0,0))
if direction == "down":
logoy+=5
if logoy==300:
direction="center"
if direction == "center":
pass
screen.blit(logo,(logox,logoy))
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update
fpsClock.tick(FPS)
The problem is that when I run the code it starts as a black screen and not until I move the window "out" of the Windows screen it refreshes, the images aren´t the problem as I ran the code without them and it showed the same black screen. I´m beginning to think that it isn´t code problem but compability as I´m running Python 3.2 and Pygame 1.9(I think) the last version that is really old , all this on Windows 10, so this might be the problem.Thanks in advance.
As you know pygame.display.update is a function
as seen if you print it:
>>> print pygame.display.update
<built-in function update>
so when you call pygame.display.update without parenthesis () you are merely stating a reference to a function. Whereas if you use parenthesis you call the function:
>>> print pygame.display.update()
None
this calls the function and returns None
This question already has answers here:
pygame.event.get() not returning any events when inside a thread
(1 answer)
Is it possible to make the keyboard module work with pygame and threading
(1 answer)
Closed 1 year ago.
I was writing a small program in python 2.7.10 with pygame. Im using multithreading to play sounds (with winsound) and still draw things fast. I was trying to replicate a similar idea of some videos i saw on youtube of sorting algorithms. Unfortunately it runs for about 10 seconds then randomly crashes, the sounds keep going but the pygame window goes not responding and the drawing does not change. Even if i put a print "hi" in the code somewhere it will still be printing in the console but pygame will still have gone not responding. Cant think of whats wrong but it may be something with the multithreading (im very new to it!)
from random import randint
import pygame,winsound,threading,time
from pygame.locals import *
screen=pygame.display.set_mode([1000,500])
def bubbleSort(listName):
sorting=True
while sorting:
listChanged=False
for i in range(len(listName)-1):
draw(listName,1000/len(listName),500/11,i)
if listName[i] < listName[i+1]:
listName[i],listName[i+1]=listName[i+1],listName[i]
threading.Thread(target=playsound,args=([listName[i]])).start()
listChanged=True
if not listChanged:
sorting=False
time.sleep(10)
pygame.quit()
def playsound(frequency):
winsound.Beep(frequency*100,100)
def draw(listName,width,height,comparing):
print "hi"
screen.fill([0,0,0])
for i in range(len(listName)):
if i == comparing or i == comparing+1:
pygame.draw.rect(screen,[0,255,0],[width*(len(listName)-i),500-(height*listName[i]),width,500])
else:
pygame.draw.rect(screen,[255,255,255],[width*(len(listName)-i),500-(height*listName[i]),width,500])
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
pygame.display.update()
list1=[]
for i in range(100):
list1.append(randint(1,10))
threading.Thread(target=bubbleSort,args=([list1])).start()
I am learning to use Pygame, and when I use sys.exit(), I run into a problem. Here is the code:
import pygame, sys,os
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode((468, 60))
pygame.display.set_caption('Game')
screen = pygame.display.get_surface()
file_name = os.path.join("data","image.bmp")
surface = pygame.image.load(file_name)
screen.blit(surface, (0,0))
pygame.display.flip()
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
else:
print event
while True:
input(pygame.event.get())
It's really just the code from the pygame tutorial. The problem occurs when I actually try to exit, regardless of what event I try to use to sys.exit().
Traceback (most recent call last):
File "C:/Python27/Lib/site-packages/pygame/examples/test.py", line 25, in <module>
input(pygame.event.get())
File "C:/Python27/Lib/site-packages/pygame/examples/test.py", line 20, in input
sys.exit(0)
SystemExit: 0
... And then the program doesn't exit. What am I doing wrong here? Because I did notice that this code was for an antiquated version of Python.
sys.exit()
alone is a bit unholy with pygame.. the proper way to exit a pygame app is to first break out of the mainloop then quit pygame then quit the program. ie.
while running == True:
# catch events
if event_type == quit:
running = False # breaks out of the loop
pygame.quit() # quits pygame
sys.exit()
also it seems to me that you aren't catching the event properly.. it should be
if event.type == pygame.QUIT:
you can read more about events in pygame here.
sys.exit just throws an exception (a SystemExit exception). This has two unusual effects:
It only exits the current thread in a multithreaded application
The exception could have been caught.
I solved this problem and the right code is below:
running = True
while running == True:
for event in pygame.event.get():
if event.type == QUIT:
running = False # Exiting the while loop
screen.blit(background, (0,0))
pygame.display.update()
pygame.quit() # Call the quit() method outside the while loop to end the application.
I have read in some sources there is a conflict between the mainloop() in Tkinter which runs the Python shell and Pygame.init() which the sys.exit() command follows.
The suggestion was to run the game from the command line to get round the problem rather than load the game using run (F5) from the shell.
A good side effect of this was that in my space invaders game, which does a lot of variable updating: 35 times a second, was that the animation ran correctly whereas from the shell it ran poorly and was jerky.
If i use the following code:
if event.type == QUIT:
pygame.quit()
sys.exit()
the game exits correctly but leaves an error message in the shell which has no effect on the game and is largely redundant. It is just a little ugly. This does not happen from the command line.
Summary: try running the game from the command line to avoid Tkinter problems
If you still have the issue, (after breaking the loop) try using sys.exit(0) instead of sys.exit(). Hope it'll help. It worked for me. It seems pygame expects the 'status' argument (i.e. 0 here) to be passed in explicitly.
See the below example:
isRunning = True
while isRunning:
# Catch events
if event.type == pygame.QUIT:
isRunning = False # Breaks the loop
pygame.quit()
sys.exit(0)
I'm trying to write a simple program to play music files with Pygame. My script is below.
import pygame
import sys
import time
FRAMERATE = 30
if len(sys.argv) < 2:
sys.exit(2)
filename = sys.argv[1]
clock = pygame.time.Clock()
pygame.init()
pygame.mixer.init(frequency=44100)
pygame.mixer.music.load(filename)
print "%s loaded!" % filename
pygame.mixer.music.play(1)
while pygame.mixer.music.get_busy():
clock.tick(FRAMERATE)
But I'm having some puzzling problems. The "[File name] loaded!" message always prints, but sometimes it never enters the loop and exits immediately. If I check on the status of pygame.mixer.music.get_busy(), it appears to be false immediately after the pygame.mixer.music.play(1) command. This happens erratically; I just tried running the program with no changes to the code, having it work once and encounter this problem once right afterward. Does anyone know what could be causing these seemingly random playback problems?
I imagine this is because the actual music playback is happening on another thread, so it sometimes hasn't finished starting at the point you first call get_busy().
If that's the case, it seems like a bug in either pygame or SDL_mixer (which pygame uses.)
As an alternative way of checking for music completion, you can get pygame to give you an event when the music finishes and check for that. Like this:
pygame.mixer.music.set_endevent(pygame.USEREVENT)
quit = False
while not quit:
clock.tick(FRAMERATE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit = True
if event.type == pygame.USEREVENT:
print "Music ended"
quit = True