1

All

I am building a game with the PYGame library. I am struggeling with this piece of code, where I want to schow a button. The button is inherited from the pygame.sprite.Sprite class.

I have searched around but I could not find any example wiht a button generated from the pygame.sprite.Sprite class.

#!/usr/bin/env python

import os, sys
import pygame
import numpy

# initialize the pygame module
pygame.init();

if not pygame.font: logging.warning(' Fonts disabled');

class Button(pygame.sprite.Sprite):

  def __init__(self, gameplayCode, gameplayLbl, gameplaycolorRGB):
      # Call the parent class (Sprite) constructor
   super().__init__();

   self.gameplayCode = gameplayCode;
   self.gameplayLbl = gameplayLbl;
   self.gameplaycolorRGB = gameplaycolorRGB;
   self.buttondims = self.width, self.height = 190, 60;
   self.smallText = pygame.font.SysFont('comicsansms',15);
   # calculating a lichter color, needs to be used when hoovering over button
   self.color = numpy.array(gameplaycolorRGB);
   self.white = numpy.array(pygame.color.THECOLORS['white']);
   self.vector = self.white - self.color;
   self.gameplaycolorRGBFaded = self.color + self.vector *0.6;

 def setCords(self,x,y):
   self.textSurf = self.smallText.render(self.gameplayLbl, 1, 
   pygame.color.THECOLORS['black']);
   self.image = pygame.Surface((self.width, self.height));
   self.image.fill(self.gameplaycolorRGB);
   self.rect = self.image.get_rect();
   self.rect.topleft = x,y;
   self.rect.center = (x+(x/2),y+(y/2));

 def pressed(self,mouse):
    if mouse.get_pos()[0] > self.rect.topleft[0]:
        if mouse.get_pos()[1] > self.rect.topleft[1]:
            if mouse.get_pos()[0] < self.rect.bottomright[0]:
                if mouse.get_pos()[1] < self.rect.bottomright[1]:
                   if mouse.get_pressed()[0] == 1:
                      return True;
                   else:
                      return False;
                else:
                   return False;
            else:
               return False;
        else:
           return False;
    else:
       return False;

 def getGamePlayCode(self):
  return self.gameplayCode;

 def getGamePlayLbl(self):
  return self.gameplayLbl;

 def getGamePlayColorRGB(self):
  return self.gameplaycolorRGB;

 def getGamePlayColorRGBFaded(self):
  return self.gameplaycolorRGBFaded;

 def getButtonWidth(self):
  return self.buttondims[0];

 def getButtonHeight(self):
  return self.buttondims[1];

 def getButtonDims(self):
  return self.buttondims;

 button=Button('CODE','LABEL',pygame.color.THECOLORS['darkturquoise']);

os.environ['SDL_VIDEO_CENTERED'] = '1';
display_size = display_width, display_height = 1300,600;
gameDisplay = pygame.display.set_mode(display_size);
display_xcenter = gameDisplay.get_width()/2;
display_ycenter = gameDisplay.get_height()/2;

# create a background
background = pygame.display.get_surface();
background.fill(pygame.color.THECOLORS['white']);

# put background on the surface
backgroundPos = xcoord, ycoord = 0,0;
gameDisplay.blit(background, backgroundPos);
pygame.display.update();

title='Testing to show a button which is inherited form 
pygame.sprite.Sprite. When pressing the button code must react. When 
hoovering color must be brighter.';
textSurface = pygame.font.SysFont('comicsansms',15).render(title, True, 
pygame.color.THECOLORS['black']);
textRect = textSurface.get_rect();
gameDisplay.blit(textSurface, textRect);
pygame.display.update();

clock = pygame.time.Clock();
FPS = 60;

game_loop = True;

button.setCords(display_xcenter,display_ycenter);

while game_loop:
   mouse = pygame.mouse;

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        print('Quiting');
        game_loop = False;

    if button.pressed(mouse):
        print('Gameplay pressed');

pygame.display.update();
clock.tick(FPS);

# ending the pygame module
pygame.quit();

I want to blit the button, react on the pressed method, when hoovering over the button the color must be brighter.

Any input is highly appreciated.

In the beginning my game didnot had any classes. Now I am rebuilding the game with the use of classes.

Kind Regards Olivier -A Python beginner-

1 Answers1

0

Pygame sprites should usually be added to a sprite group (there are several different group types). Then you can update and draw all sprites in your main loop by calling group.update() and group.draw(gameDisplay).

# Create a sprite group and add the button.
buttons = pygame.sprite.Group(button)
# You could also add it afterwards.
# buttons.add(button)

while game_loop:
    mouse = pygame.mouse

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print('Quiting')
            game_loop = False
        if button.pressed(mouse):
            print('Gameplay pressed')

    # This will call the `update` methods of all sprites in
    # this group (not necessary here).
    buttons.update()
    # The display is usually filled each frame (or blit a background image).
    gameDisplay.fill(pygame.color.THECOLORS['white'])
    # This will draw each sprite `self.image` at the `self.rect` coords.
    buttons.draw(gameDisplay)
    pygame.display.update()
    clock.tick(FPS)
skrx
  • 19,980
  • 5
  • 34
  • 48
  • Here's a [sprite and sprite group tutorial](http://programarcadegames.com/index.php?chapter=introduction_to_sprites&lang=en#section_13). Also, your `pressed` method looks a bit complicated. Check out the [collision detection methods](https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint) of `pygame.Rect`s. And you can remove all the semicolons, since they are not necessary in Python and are just visual noise. – skrx Sep 21 '18 at 20:53
  • Thank you skrx for your answer. Together with your example and links I managed to create such button class. – Olivier De Groef Sep 25 '18 at 08:55