as a premice i would like to say that i'm totally new to programming and i'm not a computer science student so i'm sorry if my code makes you cringe, i recently had some python classes and enjoyed them so i wanted to deepen a little so i figured that a simple chess game would be fun to do.
As you can imagine i am using pygame.
As for now i "drew" a chessboard and i blitted the pieces in place, my idea is that i would get the coordinates of every click, if the coordinates are the same (or in range) of the blitted image the variable would update with the second click, how can i make it so that the system recognizes a "first" and "second" click.
import pygame as pg
import sys
pg.init()
schermo = pg.display.set_mode((640,540))
def coordinate():
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
if event.type == pg.MOUSEBUTTONUP:
mx1, my1 = pg.mouse.get_pos()
print (mx1,my1)
return mx1,my1
pg.display.update()
this is how i get the coords
ctorrensx = (53,53)
[...omissis]
def move():
result = coordinate()
global ctorrensx
if result == ctorrensx:
ctorrensx = (200,200)
this was my first idea for the moving function, ctorrensx is an example i wanted to try on, they are the coords of the left black rook, once i would click on it i wanted it to move to the coords (200,200) but it's not happening.
this is my first time using stack overflow so i hope that i didn't create too much confusion on my question.
thank you all.
You can set a flag to determine whether the click is a first or second.
For example:
firstClick = True
while True:
for event in pg.event.get():
if event.type == pg.MOUSEBUTTONDOWN:
if(firstClick):
firstClick = False
#Code for first click
else:
#code for second click
firstClick = True #resets the flag
i am trying to detect which button is being pressed from my controller and when it is released.
This is how far i have managed to get.
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("x")
elif j.get_button(2):
print("a")
elif event.type == pygame.JOYBUTTONUP:
print("button released")
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
i am new to programming and i dont entirely understand this piece of code.
this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released.
Thanks for reading!
pygame.event.get() returns a list of events(events are a type of structure/object of pygame generated when the user does something moves mouse / presses buttons e.t.c.).then for each of those events you check if the they are the event you want(pygame.JOYBUTTONDOWN or event.type,pygame.JOYBUTTONUP).
you can only check if a button is pressed and then see which button is pressed.
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("x")
elif j.get_button(2):
print("a")
to see when buttons get released best way i can think off is having a list of Button Status .When the status for a button changes you do something .
ButtonStatus[2];
ButtonStatus[0]=get_button(1);#a
ButtonStatus[1]=get_button(2);#x
if event.type == pygame.JOYBUTTONUP:
if ButtonStatus[0]!=get_button(1)
#status changed do yr code for button release a
pass;
if ButtonStatus[1]!=get_button(2)
#status changed do yr code for button release b
pass;
above code is a sample not actually compiled . general idea is to check when a button is released,check which button changes status and execute code accordingly.
So, i coded what i needed with the help of the other answers!
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
r = 2
t = 5
b = 1
x = 3
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("B")
b = 2
elif j.get_button(2):
print("X")
x = 5
elif event.type == pygame.JOYBUTTONUP:
if b == r :
print("b2")
b = 1
if x == t:
print("x2")
x = 3
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
This isn't robust in any way. You need to make new strings for every button you need.
You do that by copying the button with the biggest variables and just adding 3 to every variable in the code you coppied. Please answer the original post if you can give a better answer (which probably exists).Also, when u press multiple buttons at the same time and u release atleast one it thinks you have realeased all of them.
I'm writing pygame-based code for two players / two PS3 controllers.
My problem is that the button numbering appears to be inconsistent between controllers when using two at the same time.
(Pressing the yellow button on one controller may give me a button number of 4, but 0 for the other controller).
Is this normal behaviour or is my code erroneous?
import pygame
pygame.init()
clock = pygame.time.Clock()
# Get the number of joysticks attached
joystick_count = pygame.joystick.get_count()
# Check for events
while True:
for event in pygame.event.get():
if event.type == pygame.JOYBUTTONDOWN:
print("Joystick button pressed.")
if event.type == pygame.JOYBUTTONUP:
print("Joystick button released.")
# For each joystick:
for j in range(joystick_count):
joystick = pygame.joystick.Joystick(j)
joystick.init()
buttons = joystick.get_numbuttons()
for i in range( buttons ):
button = joystick.get_button( i )
if button != 0:
print("Joystick {:1} Button {:>2} value: {}".format(j,i,button) )
clock.tick(20)
One controller was set to DirectInput (which works well with my pygame), whereas the other was set to Xinput.
When they are both set to DirectInput, button mapping is always consistent!
I want to start off by saying that I am new to Python so I am sorry if this question is going to sound stupid to you.
I am just looking for an easy way to trigger a function whenever I press the left click of my mouse.
Could anyone illustrate me how to achieve this? Examples are greatly appreciated.
My code now:
import win32api
import win32con
import time
from random import randint
import pythoncom, pyHook
def OnMouseEvent(event): #triggers mouseClick function
mouseClick(event)
return True
def mouseClick(event):
if event.MessageName == "mouse left up": # makes sure that's the event I'm looking for
a = True # disables hm.MouseAll
return a
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
time.sleep(0.005)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
time.sleep(0.01)
a = False # enables hm.MouseAll back
return a
a = False
# create a hook manager
hm = pyHook.HookManager()
# set the hook
hm.HookMouse()
# wait forever
pythoncom.PumpMessages()
# watch for all mouse events
while True:
if a == False:
hm.MouseAll = OnMouseEvent # Triggers OnMouseEvent function
else:
pass
What I understand is that you already have a function ready. I would use Pygame package for this.
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
nameoffunction()
changing the number 1 in event.button == 1: will change that what mouse button is clicked.
EDIT 1
run = 1
while run == 1:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
print("Message")
PyGame requires a window so if you just want to test a click I would then use...
EDIT 2
if win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0):
print("Message")
x,y = x and y starting coordinates for box corner
0,0 = Other corner for box (i think)
know if mouse is inside of the "box" and you click it should work
(I haven't got win32api installed so haven't ran any tests with this)
I have created some sort of menu navigation system in my game. All the screens are blitted in. The "Play" and "Quit" and "Controls" button works just fine but when I try to press menu from the controls screen, nothing happens. On the controls screen, you can faintly see the first menu screen from before. That might be the problem. I think that as the return to menu button is over the previous controls page button, it somehow is pressing the controls button from before. The button and menu segment of my code will be pasted here and the full thing will be pasted in a pastebin.
def text_to_button(msg,color,buttonx,buttony,buttonwidth,buttonheight,size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx + buttonwidth/2)), buttony+(buttonheight/2)
gameDisplay.blit(textSurf, textRect)
def button(text,x,y,width,height,inactive_color,active_color,size = "small",action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color,(x,y,width,height))
if click[0] == 1 and action != None:
if action == "quit":
pygame.quit()
quit()
if action == "controls":
game_controls()
if action == "play":
gameLoop()
if action == "main":
game_intro()
else:
pygame.draw.rect(gameDisplay, inactive_color,(x,y,width,height))
text_to_button(text,black,x,y,width,height,size)
def game_controls():
gcont = True
while gcont:
gameDisplay.blit(cont,(0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play",150,500,100,50,white,gray,"small",action = "play")
button("Main Menu",320,500,150,50,white,gray,"tiny", action = "main")
button("Quit",550,500,100,50,white,gray,"small", action = "quit")
pygame.display.update()
clock.tick(15)
def game_intro():
intro = True
while intro:
gameDisplay.blit(imggg,(0,0))
button("Play",150,500,100,50,white,gray,"small",action = "play")
button("ControLs",320,500,150,50,white,gray,"tiny", action = "controls")
button("Quit",550,500,100,50,white,gray,"small", action = "quit")
pygame.display.update()
clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
intro = False
Full Code: https://pastebin.com/jrd82gkJ
You will have very hard time to debug your code in order to achieve the behavior you want for one simple reason:
The logic you use to switch between different screens providing different functionality is causing much trouble you can't directly see if you only run the game.
So you think: "oh ... how come the button doesn't work, there must be an issue with the button".
You are probably not aware of the fact that using functions having own while loops you go deeper and deeper into recursive calls with increasing recursion depth with each switch from one view to another - it is not how pygame is thought to be programmed.
I suggest you add some print() commands into your code to see in the console output that the code doesn't really do what you expect even if it appears to be OK at the first glance because it works.
Then I suggest you REWRITE your entire code so that you have one main while notGameExit: loop, and don't use any other looping in the helper functions. If you want use looping in your helper functions at least don't call from the helper functions another functions with own loops (and so on), but RETURN from them with an explicit return to avoid recursion.
If you leave the in the main loop called function with return your main loop will continue running and depending on some switches you can display in it different things on the screen and react differently to user actions.
Maybe looking at a minimal working pygame script showing "action" without usage of a loop you will gain better understanding and some deep "enlightenment" about how pygame works and then start a total rewrite of your game using another approach as this one you have used in the current code? Then come back with what you have achieved if you have further questions, but you won't probably have any, because it would be much easier to debug it yourself if the code will become more straightforward.
import pygame
pygame.init() # start PyGame (necessary because 'import pygame' doesn't start PyGame)
winDisplay = pygame.display.set_mode((1024, 768)) # set PyGame window size to 1024x768 pixel
pygame.display.set_caption("Minimal PyGame Test Script")
# Time in pygame is measured in milliseconds (1/1000 seconds) (defined by TIMER_RESOLUTION constant):
pygame.TIMER_RESOLUTION = 1000 # assure 1000 explicit, don't relay on default value
colorWhite = (255, 255, 255) # RGB color in Pygame format (valueRed=255, valueGreen=255, valueBlue=255)
colorRed = (255, 0, 0)
colorGreen = ( 0, 255, 0)
colorBlue = ( 0, 0, 255)
winDisplay.fill(colorWhite)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorRed)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorGreen)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorBlue)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds
winDisplay.fill(colorWhite)
pygame.display.update()
pygame.time.wait(3000) # show the Pygame window for 3 seconds