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()
Related
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)
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)
I have a function in pygame, which I have to run when the user presses space. However, the problem is that as soon as space is pressed, the function runs much more than once. I want it to run once, and if the user presses space again, I want the function to run again - once.
Some code below
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
God()
Now God() draws a bunch of shapes at the same time when I want it to draw one shape at a time, everytime the user presses space. God() is only called once. It picks a random number from 1 to 100 in order to make probabilities for each shape.
A Minimal, Complete and Verifiable Example is required for more specific assistance with your issue.
Below is an example that shows the following:
Holding down the Spacebar to continually add sprites (coloured rectangles). The key down events are repeated by calling pygame.key.set_repeat().
Holding down the Enter key will continually add sprites, but limited to once every five seconds
Pressing and releasing the Tab key will generate a single sprite.
Let me know if you have any questions.
import random
import pygame
import time
screen_width, screen_height = 640, 480
def get_random_position():
"""return a random (x,y) position in the screen"""
return (random.randint(0, screen_width - 1), #randint includes both endpoints.
random.randint(0, screen_height - 1))
def get_random_named_color(allow_grey=False):
"""return one of the builtin colors"""
if allow_grey:
return random.choice(all_colors)
else:
return random.choice(non_grey)
def non_grey(color):
"""Return true if the colour is not grey/gray"""
return "grey" not in color[0] and "gray" not in color[0]
all_colors = list(pygame.colordict.THECOLORS.items())
# convert color dictionary to a list for random selection once
non_grey = list(filter(non_grey, all_colors))
class PowerUp(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
width, height = 12, 10
self.color, color = get_random_named_color()
self.image = pygame.Surface([width, height])
self.image.fill(color)
# Fetch the rectangle object that has the dimensions of the image
# Update the position of this object by setting the values of rect.x and rect.y
self.rect = self.image.get_rect().move(*get_random_position())
def update(self):
#move to a random position
self.rect.center = get_random_position()
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Sprite Collision Demo')
clock = pygame.time.Clock() #for limiting FPS
FPS = 60
exit_demo = False
regulating = False
reg_start = 0
pygame.key.set_repeat(300, 200)
#pygame.mouse.set_cursor(*pygame.cursors.ball)
#create a sprite group to track the power ups.
power_ups = pygame.sprite.Group()
for _ in range(10):
power_ups.add(PowerUp()) # create a new power up and add it to the group.
# main loop
while not exit_demo:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_demo = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit_demo = True
elif event.key == pygame.K_SPACE:
power_ups.add(PowerUp())
#power_ups.update()
elif event.key == pygame.K_RETURN:
if not regulating:
reg_start = time.time()
power_ups.add(PowerUp())
regulating = True
else:
# limit to five seconds intervals
elapsed_ms = time.time() - reg_start
##print("Regulating", elapsed_ms)
if elapsed_ms > 5:
regulating = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_TAB:
power_ups.add(PowerUp())
elif event.type == pygame.MOUSEBUTTONUP:
for _ in range(10):
power_ups.add(PowerUp())
# check for collision
for p in power_ups:
if p.rect.collidepoint(pygame.mouse.get_pos()):
power_ups.remove(p)
print(f"Removed {p.color} power up")
# clear the screen with a black background
screen.fill(pygame.Color("black"))
# draw sprites
power_ups.draw(screen)
# update the surface
pygame.display.update()
# limit the frame rate
clock.tick(FPS)
pygame.quit()
quit()
I am quite new to Python and currently trying to make my first game with Pygame. I just started and got a problem. My screen is flickering white (fill colour) to black. I tried to lower the tick (even to 1), but it didn't help (actually, it was flickering less, but still visible a lot). I tried to find any help online, but everywhere "display.update / flip used more than once per cycle" was suggested as a problem and it didn't fix mine.
I am currently running a Fedora 20 box, with Nvidia graphic card (and nouveau drivers), if the issue is connected with this.
My code:
import pygame
from pygame.locals import *
class visualisation(object):
def __init__(self):
pygame.init()
pygame.time.Clock().tick()
self.window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 0)
pygame.mouse.set_visible(False)
pygame.display.set_caption('MY GAME')
self.background = pygame.Surface(self.window.get_size())
self.background = self.background.convert()
self.background.fill((250, 250, 250))
self.window.blit(self.background, (0, 0))
pygame.display.update()
if __name__ == '__main__':
running = True
while(running):
arcade = visualisation()
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
pygame.quit()
Thanks a lot in advance :)
You are calling the following functions in a loop:
pygame.init()
pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 0)
If I am not mistaken this creates a new screen variable which is very bad.
You probably wanted to create a new arcade at the start of the game, instead of on each frame.
Try moving it before the loop:
running = True
arcade = visualisation()
while(running):
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
Hello i'm trying to make a simple program to change the background colour on key press but it just crashes. It's to do with my loop but i don't really understand why it crashes.
thanks
import sys, pygame, random, time
from threading import Thread
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 100, 0)
red = (255, 0, 0)
Colour = (0,0,0)
size = width, height = 350, 350
screen = pygame.display.set_mode(size)
Running = True
while True:
key = pygame.key.get_pressed()
if key[pygame.K_ESCAPE]: # Escape key
Running = False
elif key[pygame.K_DOWN]: # down key
print("down")
Colour = red
elif key[pygame.K_UP]: # up key
print("h")
Colour = black
elif key[pygame.K_RIGHT]: # right key
Colour = green
print("h")
elif key[pygame.K_LEFT]: # left key
Colour = white
print("h")
pygame.draw.rect(screen, Colour, pygame.Rect(0, 0, width, height))
pygame.display.update()
pygame.display.flip()
You're missing a way for pygame to know if you want to quit the window. Instead of doing key = pygame.key.get_pressed() use:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit
if event.key == K_UP:
Colour = black
if event.key == K_DOWN:
Colour = red
if event.key == K_LEFT:
Colour = white
if event.key == K_RIGHT:
Colour = green
You also need a way for the program to handle time e.g. not run faster than you can see. You can do this by setting this variable at the top of your code:
clock = pygame.time.Clock()
and running this at the very end of your while loop:
clock.tick(FPS)
where you set the FPS as a number equal to the desired frames per second.
You can also remove your Running = True variable from the program. That should be all you need to get it running. Good luck! Ask questions below.
Two things:
You have a bug: the while loop while go forever because you are testing while True instead of while Running. You could change to while Running or after testing for escape key, you could break to exit the while loop.
Also, all pygame examples I have looked up just now have an event checker. Without that, pygame freezes. If you add it, everything is smooth.
Here are both of those corrected:
import sys, pygame, time
pygame.init()
size = 350, 350
screen = pygame.display.set_mode(size)
Running = True
while Running: # <----- changed this from True to Running
time.sleep(0.03) # avoid blasting the CPU. I think pygame.time.Clock also exists
# this makes pygame responsive
for event in pygame.event.get():
if event.type == pygame.QUIT:
Running = False # <---- or you could just break
# from here is as you originally wrote
key = pygame.key.get_pressed()
if key[pygame.K_ESCAPE]:
print('exit')
Running = False # <---- or you could just break
pygame.quit()
sys.exit()