Reputation: 220
class menu:
hover = False
def __init__(self, text, pos):
self.text = text
self.pos = pos
self.set_rect()
self.draw()
def draw(self):
self.set_render()
screen.blit(self.render, self.rect)
def set_render(self):
self.render = subFont.render(self.text, True, self.get_color())
def get_color(self):
if self.hover:
return (BLACK)
else:
return (GREEN)
def set_rect(self):
self.set_render()
self.rect = self.render.get_rect()
self.rect.topleft = self.pos
select = [menu("Computer Virus", (100, 200)),
menu("Computer Crime", (100, 300)),
menu("QUIT", (100, 400))]
running = True
while running:
for evnt in event.get():
if evnt.type == QUIT:
running = False
screen.fill(WHITE)
title()
for menu in select:
if menu.rect.collidepoint(mouse.get_pos()):
menu.hover = True
else:
menu.hover = False
menu.draw()
pointer()
display.update()
This is my game menu where hovering over will allow you it to change colour Im planning to make it so the that when you click on one of the options, it would bring you elsewhere. How do I find the position of the rect and with which text it the mouse collides with?
Upvotes: 0
Views: 104
Reputation: 7886
This code does what you want:
class menu:
hover = False
def __init__(self, text, pos, callback):
self.text = text
self.pos = pos
self.callback = callback # so we now what function to call
self.set_rect()
self.draw()
# the rest of your code
def quit_loop():
global running
running = False
select = [menu("Computer Virus", (100, 200), lambda: print("Computer Virus")), # Add a callback
menu("Computer Crime", (100, 300), lambda: print("Computer Crime")),
menu("QUIT", (100, 400), quit_loop)]
running = True
while running:
for evnt in event.get():
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN: # if a mousebutton got pressed
if evnt.button == 1: # if the first button got pressed
for menu in select:
if menu.rect.collidepoint(evnt.pos): # does this one collide
menu.callback() # call the callback
Upvotes: 1