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)
Related
I'm creating a simple pygame program (PyGame 1.9.6 on Python 3.7), but some of the code inside my while loop doesn't seem to work. When I run the program, the window opens, but the screen doesn't fill with black, nor does the window close when I press "x"
import pygame
# pygame setup
pygame.init()
# Open a window on the screen
width, height = 600, 600
screen = pygame.display.set_mode((width, height))
def main():
running = True
clock = pygame.time.Clock()
BLACK = (0,0,0)
while running:
clock.tick(5) # number of loops per second
print("tick")
screen.fill(BLACK)
for event in pygame.event.get():
print("event detected")
if event == pygame.QUIT:
running = False
pygame.display.update()
main()
In the console, "tick" appears like normal and "event detected" appears after pressing any keys or mouse click. I don't get any errors when I run it.
If event == pygame.QUIT: should be if event.type == pygame.QUIT:
I usually use that event like this:
if event.type == pygame.QUIT:
pygame.quit()
quit()
Just as #Telan said
if event==pygame.QUIT:
should be
if event.type==pygame.QUIT:
However to properly shutdown pygame, pygame.quit() is important to shutdown pygame modules which is the reverse of pygame.init()
While sys.exit() is used to properly shutdown the main python program.
from sys import exit
import pygame
if event.type == pygame.QUIT:
pygame.quit()
exit()
Full code is shown below. Enjoy!
import pygame
from sys import exit
# pygame setup
pygame.init()
# Open a window on the screen
width, height = 600, 600
screen = pygame.display.set_mode((width, height))
def main():
clock = pygame.time.Clock()
BLACK = (0, 0, 0)
while True:
clock.tick(5) # number of loops per second
print("tick")
screen.fill(BLACK)
for event in pygame.event.get():
print("event detected")
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.update()
if __name__ == "__main__":
main()
I was practicing using the pygame package in python by making a graphics oriented game and in my game, I want to switch between multiple backgrounds as the user progresses through it. For the example I am posting, the first background will be a black screen with 5 statements on it and my second background will be a room. However, I am unable to figure this out because whenever I try to run the code, the game window doesn't show anything. I can post my code for the while loop below for further clarification.
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
first_line()
second_line()
third_line_1()
third_line_2()
fourth_line()
fifth_line()
sleep(10)
screen.blit(background_room, (0, 0))
pygame.display.update()
The way I would probably do it is something like
import pygame
from pygame.locals import *
class Backround:
FIVE_STATEMENTS = 0
ROOM = 1
viewport_size = (800, 600)
def main():
pygame.init()
screen = pygame.display.set_mode(viewport_size)
backround_room = pygame.Surface(viewport_size)
# load the image...
backround_statements = pygame.Surface(viewport_size)
backround_statements.fill((0, 0, 0))
# blit the five statements onto here
backround_to_render = Backround.FIVE_STATEMENTS
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if backround_to_render == Backround.FIVE_STATEMENTS:
# if the statements ever change, probably want to fill() and re-blit them on
screen.blit(backround_statements, (0,0))
elif backround_to_render == Backround.ROOM:
screen.blit(backround_room, (0,0))
else:
print("Oh no!!!!!!!")
pygame.display.flip()
if __name__ == "__main__":
main()
I'm using this bit of code in pycharm, but none of the print for events works(the quit, mouse button click or key pressing on keyboard)
Although I see the pygame window but the events doesn't work.
I also used the get() instead of wait() but still no luck.
any ideas?
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
while True:
event = pygame.event.wait()
if event.type == pygame.QUIT:
print('Quit')
if event.type == pygame.KEYDOWN:
print('Key Down')
print(event.key)
print(event.unicode)
if event.type == pygame.KEYUP:
print('Key Up')
print(event.key)
if event.type == pygame.MOUSEBUTTONDOWN:
print('Mouse Button Down')
print(event.pos)
print(event.button == pygame.BUTTON_RIGHT)
print(event.button == pygame.BUTTON_LEFT)
if event.type == pygame.MOUSEBUTTONUP:
print('Mouse Button Up')
print(event.pos)
print(event.button == pygame.BUTTON_RIGHT)
print(event.button == pygame.BUTTON_LEFT)
if event.type == pygame.MOUSEMOTION:
print('Mouse Motion')
print(event.pos)
print(event.rel)
UPDATE
I found out that it's a problem with pycharm.
when I run any code with pygame just a black pygame windows pop up, it doesn't run any other code(events, filling window with color ,...). Even the pygame window is not in dimensions that I've given.
Here another code example.
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
red = (255, 0, 0)
screen.fill(red)
pygame.display.update()
pygame.time.delay(10000)
when I run it in VS code:
Vs code pygame test
and when I run it in pycharm :( :
Pycharm pygame test
also I'm defining the same Interpreter for both VS code and pycharm and I've already reinstalled pygame package.
You can try to use a full game loop, as this would update the window repeatedly.
Try:
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
red = (255, 0, 0)
running = True
while running:
screen.fill(red)
pygame.display.flip()
for event in pygame.event.get():
if event.type = pygame.QUIT:
running = False
pygame.quit()
i was using pycharm but all the code did not wok so i right clicked it with the mouse and selected run in python cnsole.
OR ::::::::::::
SHIFT + ALT + E
This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
What all things happens inside pygame when I press a key? When to use pygame.event==KEYDOWN
(1 answer)
Closed 2 years ago.
I have installed vs code and added pygame snippets to use pygame library. My big problem is, every time I try to use any key option of pygame, like pygame.KEYDOWN or pygame.QUIT it tells me that QUIT is not a function of pygame. Can someone help me?
Everything else seems to work, like display or surface
even pygame.key.get_pressed() don’t make problems.
import pygame, random, sys
from pygame.locals import *
from pygame.key import *
def set_Background():
screen = pygame.display.set_mode((500,500))
surface = pygame.image.load('Background.png')
surface = pygame.transform.scale(surface, (500, 500))
screen.blit(surface, (0,0))
pygame.display.update()
return screen
def set_Enemy():
enemy = pygame.image.load('Enemy.png')
enemy = pygame.transform.scale(enemy, (50, 50))
return enemy
def set_Player():
player = pygame.image.load('Player.png')
player = pygame.transform.scale(player, (70, 70))
return player
RUNNING = True
while RUNNING:
background = set_Background()
enemy = set_Enemy()
player = set_Player()
enemy_rect = enemy.get_rect()
player_rect = player.get_rect()
e_x = random.randint(10,450)
e_y = random.randint(10,450)
background.blit(enemy, (e_x, e_y))
pygame.display.update()
for event in pygame.event.get():
key = pygame.key.get_pressed()
if event.type == key[pygame.K_ESCAPE]:
#module pygame has no K_ESCAPE member
sys.exit()
if event.type == pygame.QUIT:
#says module pygame has no QUIT member
sys.exit()
pygame.key.get_pressed() shouldn't be in the event loop, but in the main while loop. In the event loop you need to check if the event type is pygame.QUIT and then set the running flag to False.
Here's a fixed version:
import pygame
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
running = True # Uppercase names are for constants not variables.
while running:
# The event loop.
for event in pygame.event.get():
# If a pygame.QUIT event is in the queue.
if event.type == pygame.QUIT:
running = False
# To check if it was a `KEYDOWN` event.
elif event.type == pygame.KEYDOWN:
# If the escape key was pressed.
if event.key == pygame.K_ESCAPE:
running = False
# Use pygame.key.get_pressed to see if a key is held down.
# This should not be in the event loop.
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
print('up arrow pressed')
screen.fill((30, 30, 30))
pygame.display.flip()
clock.tick(60)
Add from pygame.locals import * at the top of your code.
You are mixing two types of key presses in one go. You should instead either
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SOMEKEY:
do_something()
or
keys = pygame.key.get_pressed()
if keys[pygame.K_somekey]:
do_something()
so the code above with the pygame.key.get_pressed() should not be in the event loop
This may seem like a really easy question to answer, but I'm just a beginner in need of quick help.
I'm trying to create a program that when you click somewhere on the pyGame window, it'll print out that you hit it with the left button on the mouse, and also print out co-ordinates of where it was pressed. I've got this already. I'm having problems with making it plot the pixel on the pyGame window. Basically, I want it to draw a pixel where I pressed down on the pyGame window.
#!/usr/bin/env python
#import the module for use
import pygame
#setting up some variables
running = 1
LEFT = 1
#Set up the graphics area/screen
screen=pygame.display.set_mode((640,400))
#continuous loop to keep the graphics running
while running==1:
event=pygame.event.poll()
if event.type==pygame.QUIT:
running=0
pygame.quit()
elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
print "You pressed the left mouse button at (%d,%d)" %event.pos
elif event.type==pygame.MOUSEBUTTONUP and event.button==LEFT:
print "You released the left mouse button at (%d,%d)" %event.pos
Try setting the color of each pixel when you receive the mouse down event.
elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
print "You pressed the left mouse button at (%d,%d)" %event.pos
screen.set_at((event.pos.x, event.pos.y), pygame.Color(255,0,0,255))
Note that this will temporarily lock and unlock the Surface as needed.
I edited Aesthete's code to a working standalone example:
Depending what you are doing, get/setting individual pixels can be slow. ( There is Surfarray and Pixelarray if you need to. )
import pygame
from pygame.locals import *
class Game(object):
done = False
def __init__(self, width=640, height=480):
pygame.init()
self.width, self.height = width, height
self.screen = pygame.display.set_mode((width, height))
# start with empty screen, since we modify it every mouseclick
self.screen.fill(Color("gray50"))
def main_loop(self):
while not self.done:
# events
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: self.done = True
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
elif event.type == MOUSEMOTION:
pass
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
print "Click: ({})".format(event.pos)
self.screen.set_at(event.pos, Color("white"))
# draw
pygame.display.flip()
if __name__ == "__main__":
g = Game()
g.main_loop()