"video system not initialized" While closing pygame window - python-3.x

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

Related

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)

pipes spawning too fast in flappy bird pygame

Im working on this flappy bird pygame tutorial and when I tested the code the pipes spawned in too fast. I'm using a tutorial since I'm fairly new to python and would appreciate any help. Thanks. Here is the link to the tutorial website: https://github.com/clear-code- projects/FlappyBird_Python/blob/master/flappy.py
Here is the code I have so far.
import pygame
import sys
import os
from random import randint
def draw_floor():
screen.blit(floor_surface,(floor_x_pos,750))
screen.blit(floor_surface,(floor_x_pos + 576,750))
def create_pipe():
new_pipe = pipe_surface.get_rect(midtop = (288,375))
return new_pipe
def move_pipes(pipes):
for pipe in pipes:
pipe.centerx -= 5
return pipes
def draw_pipes(pipes):
for pipe in pipes:
if pipe.bottom >= 750:
screen.blit(pipe_surface,pipe)
pygame.init()
screen = pygame.display.set_mode((576,855))
clock = pygame.time.Clock()
# Game variables
gravity = 0.25
bird_movement = 0
bg_surface = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs','bg.png')).convert_alpha())
floor_surface = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs','base.png')).convert_alpha())
floor_x_pos = 0
bird_surface = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs','bird2.png')).convert_alpha())
bird_rect = bird_surface.get_rect(center = (100,427))
pipe_surface = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs','pipe.png')))
pipe_list = []
SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE,5000)
pipe_height = [300,500,700]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_movement = 0
bird_movement -= 12
if event.type == SPAWNPIPE:
pipe_list.extend(create_pipe())
# bird
screen.blit(bg_surface,(0,0))
bird_movement += gravity
bird_rect.centery += int(bird_movement)
screen.blit(bird_surface,bird_rect)
# pipes
pipe_list = move_pipes(pipe_list)
draw_pipes(pipe_list)
floor_x_pos -= 1
draw_floor()
if floor_x_pos <= -576:
floor_x_pos = 0
pygame.display.update()
clock.tick(120)`
Indent the SPAWNPIPE check:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_movement = 0
bird_movement -= 12
if event.type == SPAWNPIPE: # indent this
pipe_list.extend(create_pipe())
The issue is that once you get the first SPAWNPIPE event, the event.type condition for adding a new pipe becomes True.
However, due to improper indentation, that condition is repeatedly checked every frame until the next event is received. This means the code is continually spawning pipes every frame during this time.
Fix the indentation, to bring the pipe-event check back inside the event for-loop:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_movement = 0
bird_movement -= 12
if event.type == SPAWNPIPE: # <<-- HERE
pipe_list.extend(create_pipe()) # <<-- AND HERE
Which makes the SPAWNPIPE check be performed only when the event is actually received.

Can't import any pygame functions (E1101)

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)

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()

How can I detect if user has double-tapped spacebar key in pygame?

I am new to python and pygame. Can somebody help me in this please.
Thanks in advance
This uses tkinter, but you can try this:
from tkinter import *
tk = Tk()
def helloworld(event):
print('Hello world!')
tk.bind_all('<Double-Button-1>', helloworld)
Sorry this uses Left Click, but I hope it answers.
You can do any code in the function, just make sure you don't use parentheses.
This code worked for me.
global clock, double_click_event, timer
double_click_event = pygame.USEREVENT + 1
timer = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
if timer == 0:
pygame.time.set_timer(double_click_event, 500)
timerset = True
x, y = pyautogui.position()
pyautogui.click(x, y, button='left')
else:
if timer == 1:
pygame.time.set_timer(double_click_event, 0)
double_click()
timerset = False
if timerset:
timer = 1
else:
timer = 0

Resources