Jul-09-2018, 09:21 AM
Hello,
I found a piece of code on the internet which creates an interactive menu. I modified it to use classes to make it more modular. It works, but the way it works isn't very Pythonic.
I have searched for a way to write this where I don't have to pass the instances through as parameters, but I haven't found a way.
Thanks!
I found a piece of code on the internet which creates an interactive menu. I modified it to use classes to make it more modular. It works, but the way it works isn't very Pythonic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
import pygame as pg class Control(): def __init__( self , size = ( 480 , 320 ),caption = ""): pg.init() self .size = size self .caption = caption self .screen = pg.display.set_mode( self .size) pg.display.set_caption( self .caption) self .clicked = False self .main_menu = Menu( self ,[ "NEW GAME" , "LOAD GAME" , "OPTIONS" ]) self .main() def main( self ): while True : pg.event.pump() self .screen.fill(( 0 , 0 , 0 )) self .clicked = False for event in pg.event.get(): if event. type = = pg.MOUSEBUTTONUP: self .clicked = True elif event. type = = pg.QUIT: pg.quit sys.exit() self .main_menu.update() pg.display.update() class Menu(Control): def __init__( self ,window,labels,font = None ): self .font = pg.font.Font(font, 40 ) self .options = [] self .window = window self .screen = window.screen self .labels = labels self .startypos = self .window.size[ 1 ] / / ( len (labels) + 1 ) self .middle = self .window.size[ 0 ] / / 2 count = self .startypos for label in labels: self .options.append(Option( self ,label,( self .middle,count))) count + = self .startypos def update( self ): for option in self .options: if option.rect.collidepoint(pg.mouse.get_pos()): option.hovered = True if self .window.clicked: option.clicked() else : option.hovered = False option.draw() class Option(Menu): def __init__( self ,menu,text,pos): self .hovered = False self .menu = menu self .font = self .menu.font self .screen = self .menu.screen self .text = text self .pos = pos self .set_rect() self .draw() def draw( self ): self .set_rend() self .screen.blit( self .rend, self .rect) def set_rend( self ): self .rend = self .font.render( self .text, True , self .get_colour()) def get_colour( self ): if self .hovered: return ( 255 , 255 , 255 ) else : return ( 100 , 100 , 100 ) def set_rect( self ): self .set_rend() self .rect = self .rend.get_rect() self .rect.center = self .pos def clicked( self ): print ( self .text) app = Control() |
Thanks!