Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
detecting mouse not working
#1
import pygame
from pygame.locals import *
import os

pygame.init()

def keyhandler(screenxsize, screenysize, mouseclicked):
    keycombo = False
    running = True
    keypressed = False
    key = []
    keysheld = pygame.key.get_pressed()
    mousestate = pygame.mouse.get_pressed()
    mouseheld = mousestate[0]
    opressed = False
    mpos = pygame.mouse.get_pos()
    bob = 0

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            print("Quitting")
        if event.type == pygame.KEYDOWN:
            keypressed = True
            if keysheld[K_LSHIFT]:
                caps = True
            else:
                caps = False
            print("keypressed")
            if event.key == pygame.K_a:
                if caps == True:
                    key.append("A")
                else:
                    key.append("a")
            if event.key == pygame.K_b:
                if caps == True:
                    key.append("B")
                else:
                    key.append("b")
            if event.key == pygame.K_c:
                if caps == True:
                    key.append("C")
                else:
                    key.append("c")
            if event.key == pygame.K_d:
                if caps == True:
                    key.append("D")
                else:
                    key.append("d")
            if event.key == pygame.K_e:
                if caps == True:
                    key.append("E")
                else:
                    key.append("e")
            if event.key == pygame.K_f:
                if caps == True:
                    key.append("F")
                else:
                    key.append("f")
            if event.key == pygame.K_g:
                if caps == True:
                    key.append("G")
                else:
                    key.append("g")
            if event.key == pygame.K_h:
                if caps == True:
                    key.append("H")
                else:
                    key.append("h")
            if event.key == pygame.K_i:
                if caps == True:
                    key.append("I")
                else:
                    key.append("i")
            if event.key == pygame.K_j:
                if caps == True:
                    key.append("J")
                else:
                    key.append("j")
            if event.key == pygame.K_k:
                if caps == True:
                    key.append("K")
                else:
                    key.append("k")
            if event.key == pygame.K_l:
                if caps == True:
                    key.append("L")
                else:
                    key.append("l")
            if event.key == pygame.K_m:
                if caps == True:
                    key.append("M")
                else:
                    key.append("m")
            if event.key == pygame.K_n:
                if caps == True:
                    key.append("N")
                else:
                    key.append("n")
            if event.key == pygame.K_o:
                if caps == True:
                    key.append("O")
                else:
                    key.append("o")
                    opressed = True
                    if keysheld[K_p]:
                        keycombo = "op"
            else:
                keycombo = []
            if event.key == pygame.K_p:
                if caps == True:
                    key.append("P")
                else:
                    key.append("p")
                    if opressed == True:
                        keycombo = "op"
                    if keysheld[K_o]:
                        keycombo = "op"
            else:
                keycombo = []
            if event.key == pygame.K_q:
                if caps == True:
                    key.append("Q")
                else:
                    key.append("q")
            if event.key == pygame.K_r:
                if caps == True:
                    key.append("R")
                else:
                    key.append("r")
            if event.key == pygame.K_s:
                if caps == True:
                    key.append("S")
                else:
                    key.append("s")
            if event.key == pygame.K_t:
                if caps == True:
                    key.append("T")
                else:
                    key.append("t")
            if event.key == pygame.K_u:
                if caps == True:
                    key.append("U")
                else:
                    key.append("u")
            if event.key == pygame.K_v:
                if caps == True:
                    key.append("V")
                else:
                    key.append("v")
            if event.key == pygame.K_w:
                if caps == True:
                    key.append("W")
                else:
                    key.append("w")
            if event.key == pygame.K_x:
                if caps == True:
                    key.append("X")
                else:
                    key.append("x")
            if event.key == pygame.K_y:
                if caps == True:
                    key.append("Y")
                else:
                    key.append("y")
            if event.key == pygame.K_z:
                if caps == True:
                    key.append("Z")
                else:
                    key.append("z")
            if event.key == pygame.K_LSHIFT:
                key.append("LShift")
        if event.type == pygame.KEYUP:
            keypressed = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouseclicked = True
            print("THIS IS DETECTING!")
        else:
            mouseclicked = False
        if event.type == pygame.MOUSEBUTTONUP:
            mouseclicked = False
        if event.type == pygame.VIDEORESIZE:
            print("Resizing")
            screenxsize = event.w
            screenysize = event.h
    key = ''.join(key)
    print(mouseclicked)   # THIS IS NOT DETECTING THE PRESS DESPITE THE FACT THAT IT SHOULD HAVE BEEN SET TO TRUE< AS DEMONSTRATED BY THE LINE 
                        #PRINTING A FEW LINES ABOVE!
    return running, key, keypressed, keysheld, keycombo, mouseclicked, mouseheld, mpos, screenxsize, screenysize
import pygame
from pygame.locals import *
import os
import Keyhandler
import Menues

x, y = 0, 0
position = (0, 30)
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
os.environ['SDL_VIDEO_WINDOW_POS'] = str(position[0]) + "," + str(position[1])

infoObject = pygame.display.Info()
screenxsize, screenysize = infoObject.current_w, (infoObject.current_h - 30)
running, time, leftmousepress, mouseclicked,  mouselefthold, keypressed, screenresizedyet, keycombopressed, helptext, pressed, clickedon, menuenum = True, 0, False, False, False, False, False, False, " ", False, False, "Start"
mpos, mouseheld, key = (0,0), False, []
font = pygame.font.SysFont('Comic Sans MS', 10)

pygame.init()
pygame.font.init()

screen = pygame.display.set_mode([(int(screenxsize)), (int(screenysize))], RESIZABLE)
pygame.display.set_caption('Dnd reimagined')






while running:
    time = time + 1
    running, key, keypressed, keysheld, keycombo, mouseclicked, mouseheld, mpos, screenxsize, screenysize = Keyhandler.keyhandler(screenxsize, screenysize, mouseclicked)
    menuenum = Menues.drawmenues(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld, menuenum)


    Menues.drawmenues(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld, menuenum)

    if len(key) > 0:
        print(key)
    if mouseclicked == True:
        print("True")
    if mouseheld == True:
        print("boobs")
    print("do")



    pygame.display.update()
import pygame
from pygame.locals import *

font = pygame.font.SysFont('Comic Sans MS', 10)
mpos, mouseheld = False, False
menuenum = "Start"


pygame.init()

def drawbutton(screen, mpos, held, clickedon, posx, posy, buttonwidth, buttonheight, text):
    if held == True:
        pygame.draw.rect(screen, (100, 10, 100),  (posx, posy, buttonwidth, buttonheight))
        pygame.draw.rect(screen, (100, 100, 100), (posx + (buttonwidth * .1), posy + (buttonheight * .1), (buttonwidth * .8), (buttonheight * .8)))
    else:
        pygame.draw.rect(screen, (100, 100, 100), (posx, posy, buttonwidth, buttonheight))
        pygame.draw.rect(screen, (100, 10, 100), (posx + (buttonwidth * .1), posy + (buttonheight * .1), (buttonwidth * .8), (buttonheight * .8)))
    buttontext = font.render(text, False, (255, 255, 255))
    screen.blit(buttontext, (posx, posy))


def drawanddetect(screen, mpos, mouseclicked, mouseheld, posx, posy, buttonwidth, buttonheight, text):
    clickedon = False
    held = False
    if ((posx < mpos[0] < (posx + buttonwidth)) & (posy < mpos[1] < (posy + buttonheight))):
        if mouseheld == True:
            held = True
        else:
            held = False
        if mouseclicked == True:
            clickedon = True
        else:
            clickedon = False
    drawbutton(screen, mpos, held, clickedon, posx, posy, buttonwidth, buttonheight, text)
    if mouseclicked == True:
        print("True")
    return clickedon

def startmenue(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld):
    Startscreen = pygame.image.load('Dnd.png')
    screen.blit(pygame.transform.scale(Startscreen, (screenxsize, screenysize)), (0, 0))
    menuenum = "Start"
    buttonwidth = screenxsize // 20
    buttonheight = screenysize // 20
    posx = (screenxsize // 2) - buttonwidth
    posy = (screenysize // 2) - buttonheight
    text = "Start"

    drawanddetect(screen, mpos, mouseclicked, mouseheld, posx, posy, buttonwidth, buttonheight, text)
    clickedon = drawanddetect(screen, mpos, mouseclicked, mouseheld, posx, posy, buttonwidth, buttonheight, text)
    if clickedon == True:
        menuenum = "Charactorcreatior"
    if mouseclicked == True:
        print("True")

    buttonwidth = screenxsize // 20
    buttonheight = screenysize // 20
    posx = (screenxsize) - buttonwidth
    posy = (screenysize) - buttonheight
    text = "Help"

    drawanddetect(screen, mpos, mouseclicked, mouseheld, posx, posy, buttonwidth, buttonheight, text)
    clickedon = drawanddetect(screen, mpos, mouseclicked, mouseheld, posx, posy, buttonwidth, buttonheight, text)
    if clickedon == True:
        menuenum = "help"
    if mouseclicked == True:
        print("True")

    return menuenum



def helpmenue(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld):
    screen.fill((0, 0, 0))
    menuenum = "help"
    buttonwidth = screenxsize // 20
    buttonheight = screenysize // 20
    posx = (screenxsize // 2) - buttonwidth
    posy = (screenysize // 2) - buttonheight
    text = "Back"

    drawanddetect(screen, mpos, mouseclicked, mouseheld, posx, posy, buttonwidth, buttonheight, text)
    clickedon = drawanddetect(screen, mpos, mouseclicked, mouseheld, posx, posy, buttonwidth, buttonheight, text)
    if clickedon == True:
        menuenum = "Start"
    if mouseclicked == True:
        print("True")
    return menuenum



def drawmenues(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld, menuenum):

    if menuenum == "Start":
        startmenue(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld)
        menuenum = startmenue(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld)
    if menuenum == "help":
        menuenum = helpmenue(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld)
        helpmenue(screen, screenxsize, screenysize, mpos, mouseclicked, mouseheld)
    if mouseclicked == True:
        print("True")



    return menuenum
ok, this is upsetting me. my keyhandler should be detecting mousepresses, and it is, but only if i hold it down for a half second. The annoying thing is that if i tell my program to print a line at the code that detects the press, IT WILL PRINT, yet apparently will only print and will not set the value of mouseclicked to true unless i hold it down. is this a bug? this has to be a bug? how do i fix this? if i run this, it outputs the line "THIS IS DETECTING!", so logically mouseclicked should be set to true, but it is not. This is weires and contrary to the way programs are supposed to work. help would be very appreciated.
Reply
#2
Without trying to parse this too much, I can tell you unequivocally that 99% of that key handler function is not necessary. You do not need to check seperate events for each possible ascii char. You can just use the unicode attribute.

For example here is the event handler on a text input box:
    def get_event(self,event):
        if event.type == pg.KEYDOWN and self.active:
            if event.key in (pg.K_RETURN,pg.K_KP_ENTER):
                self.execute()
            elif event.key == pg.K_BACKSPACE:
                if self.buffer:
                    self.buffer.pop()
            elif event.unicode in ACCEPTED:
                self.buffer.append(event.unicode)
        elif event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
            self.active = self.rect.collidepoint(event.pos)
You can find the whole input box and working example here if interested:
https://github.com/Mekire/pygame-textbox

As for the mouse, again I haven't debugged your program but in general the event loop is for checking mouse clicks. It isn't for getting mouse state.

Use the function pygame.mouse.get_pressed() if you are interested in the continuous state of the mouse.
Same with the keyboard: if you are more interested in a key being held rather than when it is pressed, use pygame.key.get_pressed().
Reply
#3
To clarify a bit more, I think this is the crux of the issue:

Take the following snippet:
for event in pg.event.get():
    if event.type == pg.MOUSEBUTTONDOWN:
        mouse_clicked = True
    elif event.type == pg.MOUSEBUTTONUP:
        mouse_clicked = False

if mouse_clicked:
    run_on_click()
You seem to be assuming that if the mouse is clicked, the function at the bottom will always run. This isn't the case. The event queue can potentially have both a MOUSEBUTTONDOWN and MOUSEBUTTONUP event in it at the same time. This means that by the time your event loop is finished your mouse_clicked variable could have been set to True and then back to False before reaching the end of the code and running the function in the conditional.

If you want something to fire immediately on an event you will need it to, well, fire immediately on that event:
for event in pg.event.get():
    if event.type == pg.MOUSEBUTTONDOWN:
        run_on_click()
Again as I said previously this comes down to the fact that the way you are trying to design the key handler is currently not ideal.
Reply
#4
The bug is in your code.
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouseclicked = True
            print("THIS IS DETECTING!")
        else:
            mouseclicked = False
It will be set to True. Soon as the next event happens it turns False.
This is why you have to hold it. When no other event occur after it.
Then it stays True.
99 percent of computer problems exists between chair and keyboard.
Reply
#5
okay, first, i figured out the problem. whenever i call keyhandler, it checks the events, not just once, but for every event that has happened. as such, the odds of Mouse key down being the only event is rather slim, because every event is going to return a new value for mouseclicked, and most of the time mouse key down is not going to win the lottery, so it only detects if it has enough chances to. I solved this by making the events return an array, one for each event. if one of these events is true, then i set mouseclicked to true and reset the array, kinda like how i did with the key variable. I am new at this, how might i make my keyhandler method better?




edit: yes, that is the reason. Thank you. For the record, i typed this reply before i saw the above reply.
Reply
#6
(Aug-23-2018, 01:23 AM)TheNumericDolfin Wrote: I am new at this, how might i make my keyhandler method better?
I don't really think you should have this kind of universal key handler at all is the thing. This gets into being more object oriented in general though which will involve you becoming comfortable with writing and using classes. The idea is you have your event loop and you have your objects that care about events. Every object that cares about events needs its own function with the same name. I use get_event generally. Then your event loop processes events that affect the entire program, and then passes the events off to each other object that cares about events.

So for example going back to the input box example. The event loop looks like this:
    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            self.input.get_event(event)
So, the program will always set done on a QUIT event. Events are then sent to the input box to see if it needs to do something.

If you have a bunch of things that care about events you could call get_event on all of them.

    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            for listener in self.listeners:
                listener.get_event(event)
Even though all the listener objects might be completely different types of things, since they all have an implemented get_event function they can all be called together like this; polymorphism.
Reply
#7
You could just track mouseclicked once.
Set it to false before the event.
mouseclicked = False 
for event in pygame.event.get()
    if event.type == pygame.MOUSEBUTTONDOWN:
        mouseclicked = True
99 percent of computer problems exists between chair and keyboard.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  iterating and detecting the last Skaperen 3 1,067 Oct-01-2022, 05:23 AM
Last Post: Gribouillis
  Detecting float or int in a string Clunk_Head 15 4,470 May-26-2022, 11:39 PM
Last Post: Pedroski55
  module detecting if imported vs not Skaperen 1 1,669 Nov-19-2021, 07:43 AM
Last Post: Yoriz
  detecting a generstor passed to a funtion Skaperen 9 3,570 Sep-23-2021, 01:29 AM
Last Post: Skaperen
  Python BLE Scanner not detecting device alexanderDennisEnviro500 0 2,002 Aug-01-2021, 02:29 AM
Last Post: alexanderDennisEnviro500
  Detecting power plug Narayan 2 2,701 Aug-01-2020, 04:29 AM
Last Post: bowlofred
  Detecting USB Device Insertion on Windows 10 Atalanttore 0 2,377 Jan-17-2020, 02:46 PM
Last Post: Atalanttore
  mouse 0.7.0 - mouse polling hate 125-1000hz penahuse 1 2,512 Dec-06-2019, 09:51 PM
Last Post: Larz60+
  Detecting windows shutdown event riccardoob 4 5,701 Nov-12-2019, 04:51 PM
Last Post: Aurthor_King_of_the_Brittons
  Why is left mouse click not working? yeto 3 6,160 Jul-15-2019, 05:23 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020