sâmbătă, 7 septembrie 2013

PyGame - first interface - part 6 .

I will show you how to make a menu with buttons using pygame module.

The example is simple but you can update with new features.

I will make some buttons : Start game, Options and Exit game.

The pygame come with rect function to draw rectangles.

I start with one python class named my_button.

Like any graphic interface is need to make visual elements and link with actions.

For each button I draw one rectangle with text and functions to check mouse.

The functions of my_button are:

label - will add some text;

color - change color when button is hovering:

draw - will deal with drawing the button ,color and mouse...;

check_hover - return boolean value based on mouse over my_button;

import pygame


class my_button:
   def __init__(self, text):
      self.text = text
      self.is_hover = False
      self.default_color = (100,100,100)
      self.hover_color = (0,255,25)
      self.font_color = (0,0,255)
      self.obj = None
   def label(self):
      font = pygame.font.Font(None, 22)
      return font.render(self.text, 1, self.font_color)
   def color(self):
      if self.is_hover:
         return self.hover_color
         return self.default_color
   def draw(self, screen, mouse, rect_coord, label_coord):
      self.obj  = pygame.draw.rect(screen, self.color(), rect_coord)
      screen.blit(self.label(), label_coord)
   def check_hover(self, mouse):
      if self.obj.collidepoint(mouse):
         self.is_hover = True 
         self.is_hover = False
if __name__ == '__main__':

   start = my_button('Start game')
   option = my_button('Option')
   exit = my_button('Exit game')
   screen = pygame.display.set_mode((400,350))
   clock = pygame.time.Clock()

   run = True
   while run:
      mouse = pygame.mouse.get_pos()
      for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         elif event.type == pygame.MOUSEBUTTONDOWN:
            if my_button_.obj.collidepoint(mouse):
               print('my_button start clicked')
            elif my_button_2.obj.collidepoint(mouse):
               print('my_button option clicked')
            elif my_button_3.obj.collidepoint(mouse):
               print('my_button exit clicked')
      start.draw(screen, mouse, (100,100,120,22), (125,103))
      option.draw(screen, mouse, (100,130,120,22), (125,133))
      exit.draw(screen, mouse, (100,160,120,22), (125,163))

... and this is result of the pygame script.

Niciun comentariu:

Trimiteți un comentariu