Can't import any pygame functions (E1101) - python-3.x

When I run the following code, a white screen appears and then quickly disappears. I installed pygame on the VSCode terminal with pip3 (I am on mac) and now that I finally got it to import pygame, I get multiple errors for every function called such as "clock" or "pygame.KEYDOWN". They say "Module 'pygame' has no 'KEYDOWN' member" [E1101]. I also get an error with the "init" member.
I've seen other posts that tell me to copy and paste something into the json settings, but when I tried that I got even more errors.
#Game
#By Robert Smith
#Initialize python
import pygame
pygame.init()
#Set the screen
screen = pygame.display.set_mode((640, 480))
background = pygame.Surface(screen.get_size())
background.fill((255,255,255))
background = background.convert()
screen.blit(background, (0 , 0))
#Make the window exitable
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop == False #close the window
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
#Set the framerate
milliseconds = clock.tick(60)#DO NOT GO FASTER THAN THIS FRAMERATE

Try this:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop == False #close the window
elif event.type == keys[pygame.K_DOWN]:
if event.key == keys[pygame.K_ESCAPE]:
mainloop = False
And this:
milliseconds = pygame.time.Clock.tick(60)

Related

PyGame. Second composition in modul "mixer.music. doesnt playing, but first plays normally [duplicate]

I tried to use python to display image:
import pygame
win = pygame.display.set_mode((500, 500))
DisplayImage("Prologue.jpg", win)
And when it runs, nothing happened. It also happened for
DisplayImage("Streets.jpg", win)
However, when I tried the exact same thing later on in the code, it ran perfectly.
I checked, the picture was in the same folder as the .py file, and I didn't type the name wrong.
The function is:
def DisplayImage(imageName, screen):
screen.fill((0, 0, 0))
Image = pygame.image.load(imageName).convert()
screen_rect = screen.get_rect()
Image_rect = Image.get_rect().fit(screen_rect)
Image = pygame.transform.scale(Image, Image_rect.size)
screen.blit(Image, [0, 0])
pygame.display.update()
Update:
I commented out all of the lines and copy and pasted that line out so it's the only line that runs. It runs perfectly.
Update 2:
Found the issue. The reason it doesn't work was that the pygame window was "not responding". I don't know what caused it to not respond, but in one of the test runs I didn't make it show "not responding", and the images were loaded fine. The "not responding" always shows up when I type in my player name, and the function looks like this:
def createName():
playerName = input("Enter the player name\n")
desiredName = input("Is "+playerName+" the desired name?[1]Yes/[2]No\n")
if desiredName == "1":
return playerName
elif desiredName == "2":
playerName = createName()
Sometimes when I type the player name nothing happens, and the letters only show up after a while. If this happens, the pygame window is bound to not respond.
You cannot use input in the application loop. input waits for an input. While the system is waiting for input, the application loop will halt and the game will not respond.
Use the KEYDOWN event instead of input:
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if pygame.key == pygame.K_1:
# [...]
if pygame.key == pygame.K_2:
# [...]
Another option is to get the input in a separate thread.
Minimal example:
import pygame
import threading
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
color = "red"
def get_input():
global color
color = input('enter color (e.g. blue): ')
input_thread = threading.Thread(target=get_input)
input_thread.start()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window_center = window.get_rect().center
window.fill(0)
pygame.draw.circle(window, color, window_center, 100)
pygame.display.flip()
pygame.quit()
exit()

Pygame gamepad won't run anymore with an Xbox 360 controller and an Ubuntu machine [duplicate]

This code goes into infinite loop. I cant use A button on xbox 360 controller
import pygame
from pygame import joystick
pygame.init()
joystick = pygame.joystick.Joystick(0)
pygame.joystick.init()
print("start")
while True:
if joystick.get_button(0) == 1 :
print("stoped")
break
I cant use A button on xbox 360 controller
Personnaly, I can, so this seems to be possible. You are just missing that pretty much every user input needs to be updated by pygame through pygame.event.get().
From the pygame documentation:
Once the device is initialized the pygame event queue will start receiving events about its input.
So, apparently you need to get the events in the while loop like such to make the joystick work:
import pygame
from pygame.locals import *
pygame.init()
joystick = pygame.joystick.Joystick(0)
while True:
for event in pygame.event.get(): # get the events (update the joystick)
if event.type == QUIT: # allow to click on the X button to close the window
pygame.quit()
exit()
if joystick.get_button(0):
print("stopped")
break
Also,
In the line if joystick.get_button(0) == 1, you don't need to type == 1 because the statement is already True.
You are initializing pygame.joystick twice: through the line pygame.init() and pygame.joystick.init().
You don't need to type from pygame import joystick because you already already have it in the line import pygame.
You can take this as reference and use it in your own way.
import pygame
import sys
pygame.init()
pygame.joystick.init()
clock = pygame.time.Clock()
WIDTH,HEIGHT = 500,500
WHITE = (255,255,255)
BLUE = (0,0,255)
BLUISH = (75,75,255)
YELLOW =(255,255,0)
screen = pygame.display.set_mode((WIDTH,HEIGHT))
smile = pygame.image.load("smile.jpg")
smile = pygame.transform.scale(smile,(WIDTH,HEIGHT))
idle = pygame.image.load("idle.jpg")
idle = pygame.transform.scale(idle,(WIDTH,HEIGHT))
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.JOYBUTTONDOWN:
if event.button == 0: #press A button to smile
screen.fill(WHITE)
screen.blit(smile,(0,0))
pygame.display.update()
clock.tick(10)
elif event.type == pygame.JOYBUTTONUP:
if event.button == 0:
screen.fill(WHITE)
screen.blit(idle,(0,0))
pygame.display.update()
clock.tick(10)

how to store multiple mouse click coordinates python

so Ive been trying to find a way to store multiple click x and y's with no luck, Ive worked with pygame and opencv but I cannot find a way to store multiple x and y's without deleting the previous set.
import pygame
pygame.init()
while True:
for e in pygame.event.get():
if e.type == pygame.MOUSEBUTTONDOWN:
print (pygame.mouse.get_pos())
Just append the event.pos or pygame.mouse.get_pos() to a list or collections.deque if the size should be limited.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
clicks = []
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
clicks.append(event.pos)
print(clicks)
screen.fill((30, 30, 30))
pg.display.flip()
clock.tick(30)
pg.quit()

Is there a way in pygame to make a programme pause when it's minimized?

I was playing Terraria the other day and in a new update they make the game pause when it's minimized. Obviously it's written in a different programme to python, but I was wondering if it was possible to replicate the effects.
You can use pygame.display.get_active() to check if window is minimized.
In example you can press SPACE to minimize window.
import pygame
import pygame.locals
pygame.init()
screen = pygame.display.set_mode((800,600))
count = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
pygame.display.iconify()
if pygame.display.get_active():
print count
count +=1
else:
print "minimized"
pygame.quit()
Or you can use pygame.ACTIVEEVENT to get information about more events - like minimize, mouse out of the window, etc.
import pygame
import pygame.locals
pygame.init()
screen = pygame.display.set_mode((800,600))
count = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
pygame.display.iconify()
elif event.type == pygame.ACTIVEEVENT:
print 'state:', event.state, '| gain:', event.gain,
if event.state == 1:
if event.gain == 0:
print "| mouse out",
elif event.gain == 1:
print "| mouse in",
elif event.state == 2:
if event.gain == 0:
print "| titlebar pressed",
elif event.gain == 1:
print "| titlebar unpressed",
elif event.state == 6:
if event.gain == 0:
print "| window minimized",
elif event.state == 4:
if event.gain == 1:
print "| window normal",
print
pygame.quit()
Both method work correctly only if pygame.event.get() was executed.
You can use the pygame.APPACTIVE event. From the documentation for the pygame.display.iconify:
Then the display mode is set, several events are placed on the pygame event queue. pygame.QUIT is sent when the user has requested the program to shutdown. The window will receive pygame.ACTIVEEVENT events as the display gains and loses input focus [This is when the window is minimized]. If the display is set with the pygame.RESIZABLE flag, pygame.VIDEORESIZE events will be sent when the user adjusts the window dimensions. Hardware displays that draw direct to the screen will get pygame.VIDEOEXPOSE events when portions of the window must be redrawn.
Look at the second example in furas' answer below, but don't use the polling approach of the first example for something like this, you don't want to spend time every frame trying to check if the window has been minimized.

"video system not initialized" While closing pygame window

I have two similar code snippets. Both run fine but One displays the error When i close the pygame window
Traceback (most recent call last):
File "/home/nabeel/Devalopment/Python/aaa.py", line 92, in <module>
pygame.display.flip()
pygame.error: video system not initialized
Here is the piece of code which throws error
import pygame
pygame.init()
done = False
screen = pygame.display.set_mode([640,480])
pygame.display.set_caption("my_game")
while not done:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.quit()
pygame.display.flip()
pygame.quit()
and here's the one which does not
import pygame
done = False
pygame.init()
screen_size = [320,240]
white = [255,255,255]
black = [0,0,0]
paddle_x = 0
paddle_y = 0
vel_x = 0
vel_y = 0
gutter = 10
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("mygame")
while not done:
screen.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if pygame.key.get_pressed()[pygame.K_DOWN]:
vel_y += 2
if pygame.key.get_pressed()[pygame.K_UP]:
vel_y -= 2
if pygame.key.get_pressed()[pygame.K_LEFT]:
vel_x -= 2
if pygame.key.get_pressed()[pygame.K_RIGHT]:
vel_x += 2
paddle_x += vel_x
paddle_y += vel_y
pygame.draw.line(screen,white,(gutter,0),(gutter,screen_size[1]))
pygame.draw.line(screen,white,(screen_size[0]-gutter,0),(screen_size[0]-gutter,screen_size[1]))
pygame.draw.rect(screen,white,[screen_size[0]/2,screen_size[1]/2,10,10],0)
pygame.draw.line(screen,white,[paddle_x+5,paddle_y],[paddle_x+5,paddle_y+30],gutter)
pygame.display.flip()
pygame.quit()
While these two do not do any thing harful I was just curious to what is causing all this
Try to remove the pygame.quit() in this block:
if event.type == pygame.QUIT:
done = True
pygame.quit()
The idea is that when pygame.quit() is called, the whole module is uninitialized and hence if more method calls of the module are found (like pygame.display.flip()) they will throw an error :)
If you wish to keep the pygame.quit() method call in the above conditional if statement, what you could do is import the sys module and below pygame.quit() add a sys.exit().
Both ways should work pretty well :)
Hope that helped,
Cheers! Alex

Resources