Pygame Text Button Gone wrong - pygame

So I'm making an rpg project in Pygame and I need a button class that has text. This is my Code so far. I tried to use some code examples online and on this site but I couldn't make them work in the way I wanted. ;-;
What I want is a button that can drawn to my GameWindow that includes text. I'll figure out the event handling later on.
It would be greatly appreciated if someone could give me an explanation of how a button class that utilises text would work in pygame and explain it in a way I could implement in my Button Class. Previously I have tried simply placing text in the centre of the screen by dividing the width and height by two and placing coloured rects adjacent to the text to try and label the rects so I could use them as buttons. However I realised this wasn't a practical solution, as I would be needing many buttons throughout my game and this method took up large portions of my screen.
I do not understand how to blit a message onto a rect using a class. The Button class below is where I attempted to place text onto top of a rect but I found this very hard.
Ideally my goal here is to be able to call an instance of my button class which I can use as a button.
BTW asking here was a last resort. I spent almost three hours trying to figure this out and its bad for me to stare at a screen for that long.
import pygame, random, sys, math, time
from pygame.locals import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
GameWindow = pygame.display.set_mode((650,520))
#Variables
Blue = (0,0,255)
Green = (0,255,0)
Red = (255,0,0)
White = (255,255,255)
Black = (0,0,0)
def Button():
def__init__(self, surface, x, y, width, height, colour, message, action=None)
self.x = x
self.y = y
self.width = width
self.height = height
self.font = pygame.font.Font(None, 20)
self.message = message
background_image = pygame.image.load('map.JPG')
title_image = pygame.image.load('title.PNG')
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
GameWindow.blit(background_image, [0,0])
GameWindow.blit(title_image, [100,0])
pygame.display.flip()
fpsClock.tick(FPS)

Here is a button class:
class Button(object):
global screen_width,screen_height,screen
def __init__(self,x,y,width,height,text_color,background_color,text):
self.rect=pygame.Rect(x,y,width,height)
self.x=x
self.y=y
self.width=width
self.height=height
self.text=text
self.text_color=text_color
self.background_color=background_color
self.angle=0
def check(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
def draw(self):
pygame.draw.rect(screen, self.background_color,(self.rect),0)
drawTextcenter(self.text,font,screen,self.x+self.width/2,self.y+self.height/2,self.text_color)
pygame.draw.rect(screen,self.text_color,self.rect,3)
Use the check function to see if your button is clicked on, and the draw function to draw your button.
Implemented into your main loop:
button=Button(x,y,width,height,text_color,background_color,text)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type==pygame.MOUSEBUTTONDOWN:
if button.check()==True:
#do what you want to do when button is pressed
GameWindow.blit(background_image, [0,0])
GameWindow.blit(title_image, [100,0])
pygame.display.flip()
fpsClock.tick(FPS)
I also recommend using these functions to draw text:
def drawTextcenter(text,font,screen,x,y,color):
textobj=font.render(text,True,color)
textrect=textobj.get_rect(center=(x,y))
screen.blit(textobj,textrect)
def drawText(text, font, surface, x, y,color):
textobj=font.render(text, 1, color)
textrect=textobj.get_rect()
textrect.topleft=(x, y)
surface.blit(textobj, textrect)

While you're question is still a bit confusing, I can tell you how you blit your text near or in your button. So what you just do is just place the location of the text near the button, basing the texts x and y variables on the buttons x and y variable.
Copied from your code:
def Button():
def__init__(self, surface, x, y, width, height, colour, message, action=None)
self.x = x
self.y = y
self.width = width
self.height = height
self.font = pygame.font.Font(None, 20)
self.message = message
self.font = pygame.font.SysFont('Comic Sans MS', 30) #Example Font
def draw_button(self):
pygame.draw.rect(GameWindow, Red, (self.x, self.y, self.width, self.height))
self.text = myfont.render(message, False, (0, 0, 0))
GameWindow.blit(self.text, (self.x + self.width/2, self.y + self.height/2)) #Displays text at coordinates at middle of the button.
This draws the button (it still doesn't do anything), but also displays the text in the button. HOWEVER, since the text is displayed at the top-left corner of the surface it is on, it will not be exactly in the middle, and will look odd. You can modify the exact location if you want.
I hope this answers your question.

Related

Move a sprite, but cannot delete the precedent image of it [duplicate]

I'm building a pong game trying to get better at programming but Im having trouble moving the ball. When the move_right method is called the ellipse stretches to the right instead of moving to the right. I've tried putting the ball variable in the init method but that just makes it not move at all even though the variables should be changing on account of the move_right method. I have also tried setting the x and y positions as parameters in the Ball class,but that just stretches it also.
I don't understand why when I run the following code the ball I'm trying to move stretches to the right instead of moves to the right. Can someone explain why this is happening? I have tried everything I can think of but i can't get it to do what I want.
import pygame,sys
import random
class Ball:
def __init__(self):
self.size = 30
self.color = light_grey
self.x_pos = width/2 -15
self.y_pos = height/2 -15
self.speed = 1
#self.ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
def draw_ball(self):
ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
pygame.draw.ellipse(screen,self.color,ball)
def move_right(self):
self.x_pos += self.speed
class Player:
def __init__(self,x_pos,y_pos,width,height):
self.x_pos = x_pos
self.y_pos = y_pos
self.width = width
self.height = height
self.color = light_grey
def draw_player(self):
player = pygame.Rect(self.x_pos,self.y_pos,self.width,self.height)
pygame.draw.rect(screen,self.color,player)
class Main:
def __init__(self):
self.ball=Ball()
self.player=Player(width-20,height/2 -70,10,140)
self.opponent= Player(10,height/2-70,10,140)
def draw_elements(self):
self.ball.draw_ball()
self.player.draw_player()
self.opponent.draw_player()
def move_ball(self):
self.ball.move_right()
pygame.init()
size = 30
clock = pygame.time.Clock()
pygame.display.set_caption("Pong")
width = 1000
height = 600
screen = pygame.display.set_mode((width,height))
bg_color = pygame.Color('grey12')
light_grey = (200,200,200)
main = Main()
#ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
#player = pygame.Rect(width-20,height/2 -70,10,140)
#opponent = pygame.Rect(10,height/2-70,10,140)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
#pygame.draw.rect(screen,light_grey,player)
#pygame.draw.rect(screen,light_grey,opponent)
#pygame.draw.ellipse(screen,light_grey,ball)
main.draw_elements()
main.move_ball()
main.ball.x_pos += main.ball.speed
pygame.display.flip()
clock.tick(60)
You have to clear the display in every frame with pygame.Surface.fill:
while True:
# [...]
screen.fill(0) # <---
main.draw_elements()
main.move_ball()
main.ball.x_pos += main.ball.speed
pygame.display.flip()
# [...]
Everything that is drawn is drawn on the target surface. The entire scene is redraw in each frame. Therefore the display needs to be cleared at the begin of every frame in the application loop. The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()

Pygame, my circle turns to a rect after I stored it in a variable, how do I prevent that from happening

I need to store a Circle in a variable but after I've done that it has turned into a rect
circle_1 = pygame.draw.circle(screen, (0, 0, 0), (300, 300), 30)
Print(circle_1)
the print returns
<rect(270, 270, 60, 60)>
but I can't work with that.
My circle is predefined but it won't show it on the canvas, here is an example of the problem
> import pygame, sys
>
>
> pygame.init() screen = pygame.display.set_mode((600, 600))
> predefined_circle = pygame.draw.circle(screen,(0, 0, 0),(300, 300), 30)
>
> def update():
> screen.fill((200, 0, 0))
> while 1:
> for event in pygame.event.get():
> if event.type == pygame.QUIT: sys.exit()
> # It shows my circle if I dirctly tip pygame.draw.circle(screen,(0, 0, 0),(300, 300), 30) into it
> predefined_circle
> pygame.display.update()
>
> update()
So that you can better relate to what I'm trying to achieve here is the code of what I'm doing but it is not necessary to read as I've already tried to explain it as best as I can above.
Please note the comments should explain everything that the block of code below it is doing.
# Creating the canvas which can paint any wanted Object from another class
class Canvas:
# Initialising the screen and setting all needed variables
def __init__(self, painting):
pygame.init()
self.screen_size = (600, 600)
self.background = (25, 255, 255)
self.screen = pygame.display.set_mode(self.screen_size)
self.paint = painting
# Let the user set the name of the canvas
def set_screen_name(self):
return self.screen
# Draw the everything you want to
def update(self):
# Paint the canvas
self.screen.fill(self.background)
# Make the game be quittable
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# Draw the defined Circle and then update the Canvas
# it only draws a circle if directly tip pygame.draw.circle(surface, color, position, radius)
self.paint
pygame.display.update()
# Draw any circle you like
class Cir:
# Get all the required Information's to Draw a circle
def __init__(self, canvas, what_color, position, radius, line=0):
self.can = canvas
self.color = what_color
self.pos = position
self.r = radius
self.line = line
self.cir = None
# Create the circle with the acquired Information's
def create(self):
self.cir = pygame.draw.circle(self.can, self.color, self.pos, self.r, self.line)
return self.cir
# So far there is no Surface for the Cir class
# And there is no Object that cloud be painted for the Canvas class
# I initialise a canvas instance without anything that needs to be painted
get_surface = Canvas(None)
# Now I can access set_screen_name from the Canvas class and give the surface a name
# Which the Cir class can now use as a surface
screen = get_surface.set_screen_name()
c1 = pygame.draw.circle(screen, (0,0,0), (300, 300), 30)
print(c1)
# I'm initialising a circle
init_circle = Cir(screen, (0, 255, 0), (300, 300), 30)
# Create the initialised circle
circle_1 = init_circle.create()
# Give the Canvas class the created circle
paint = Canvas(circle_1)
# Draw the circle
paint.update()
My circle turns to a rect.
Actually, no, it doesn't. As per the documentation for those drawing functions, the intent of the calls is to draw something immediately, not to give you an object you can draw later:
Draw several simple shapes to a Surface.
From analysis of your question, it sounds like you believe that you are storing the act of drawing the circle so that it can be done later. That is not the case. Instead, what you are doing is actually drawing the circle and saving the result of that drawing action - evaluating the result later on will not actually draw, or redraw, the circle.
So, if the draw function is not returning something for later drawing, what is it returning? That can also be found in the above-mentioned documentation:
The functions return a rectangle representing the bounding area of changed pixels.
In other words, it's telling you the smallest rectangle that was changed by the drawing action - this will be a square with sides the same length as the diameter and centered around the same point.
Obviously, the authors of PyGame thought this information may be handy for some purpose, just not the purpose of redrawing the circle :-)
One way to do what you're trying to achieve would be to simply have a function to draw the "predefined" circle and call that instead of trying to evaluate the rectangle returned from a previous call.

Pygame blit part of an image(background image)

I have a pygame menu where i have drawn some buttons, which represent the level difficulty of my game. For user convenience, i have made a sprite which indicates which level-button is selected(think of it as a light green frame around the button). Now, if i have a solid color as my background, i can just fill the frame with the bg color. But i wanna have a custom image. However i am not sure how to do the deleting stuff with this image. I dont want to have to do a surface.blit(bgImage, surface.get_rect())
in every while-loop. Is there any way to tell pygame to blit just part of the image? So the end-result is still fine-looking. Here is my code when i have a color as the background
(please note that my question does not apply only to this scenario, its more of a general way as to blitting part of an image, without having to rely on cropping the image using 3rd party software like paint(net), photoshop etc.):
#class for the highlight sprite that appears when a level button is clicked
class HighLightImage(Sprite):
def __init__(self, spriteX, spriteY, width = 180, height = 60):
Sprite.__init__(self)
self.rect = pygame.Rect(spriteX, spriteY, width, height)
self.image = pygame.image.load("highlight.png")
#function to draw the highlight sprite, after deleting its older position.
def draw(self, newSpriteX, newSpriteY):
#due to technical issues the following method is using 4 dirty sprite deletions.
surface.fill(bgCol, (self.rect.x, self.rect.y, self.rect.width, 10))
surface.fill(bgCol, (self.rect.x, self.rect.y + self.rect.height-10, self.rect.width, 10))
surface.fill(bgCol, (self.rect.x, self.rect.y, 10, self.rect.height))
surface.fill(bgCol, ( self.rect.x + self.rect.width-10, self.rect.y, 10, self.rect.height))
self.rect.x = newSpriteX
self.rect.y = newSpriteY
surface.blit(self.image, self.rect)
And here is the main while-loop
def mainIntro():
#snake image
snakeImg = pygame.image.load("snakeB.png")
snakeImg = pygame.transform.scale(snakeImg, (150,200))
#highlight obj
hlObj = HighLightImage(0, 0)
#starting level = 1
levels = 1
#initial fill
surface.fill(bgCol)
intro = True
#start button
startButton = StartButton(WIDTH/2-330, HEIGHT - 150)
startButton.draw("Start")
#Exit button
exitButton = ExitButton(WIDTH/2+110, HEIGHT - 150)
exitButton.draw("Exit")
#level buttons
easyLvl = EasyLevelButton( 65, HEIGHT/2 )
easyLvl.draw("Easy")
midLvl = MediumLevelButton( 320, HEIGHT/2 )
midLvl.draw("Medium")
hardLvl = HardLevelButton( 570, HEIGHT/2 )
hardLvl.draw("Hard")
instructions()
surface.blit(snakeImg, (WIDTH/2-75, HEIGHT - 250))
while intro:
for ev in pygame.event.get():
# X exit event
if ev.type == QUIT:
pygame.quit()
sys.exit()
if ev.type == MOUSEMOTION:
startButton.hover()
exitButton.hover()
easyLvl.hover()
midLvl.hover()
hardLvl.hover()
if ev.type == MOUSEBUTTONDOWN:
if easyLvl.clicked():
levels = 1
if midLvl.clicked():
levels = 2
if hardLvl.clicked():
levels = 4
#button exit event
elif exitButton.clicked():
pygame.quit()
sys.exit()
elif startButton.clicked():
intro = False
#highlight frame, according to level-button chosen
if levels == 1:
hlObj.draw(easyLvl.x-10, easyLvl.y-10)
elif levels == 2:
hlObj.draw(midLvl.x-10, midLvl.y-10)
elif levels == 4:
hlObj.draw(hardLvl.x-10, hardLvl.y-10)
update()
return levels
Finally here is an image of the end result :
P.s In the above code snippets i have not included the button classes, and the global variables like colors, width, height etc., since i dont think they are relevant with what i want to accomplice. Feel free to correct my code, and/or suggest improvements.
As #cmd said above, the area param would be a good option, but for more information, try the pygame docs or have a look at this question or try pygame.transform.chop()
Try the code below:
pygame.init()
size = width, height = 1200, 800
screen = pygame.display.set_mode(size)
image = pygame.image.load("example.png")
rect = image.get_rect()
cropx,cropy = 100,10 #Change value to crop different rect areas
cropRect = (cropx, cropy, rect.w,rect.h)
while(True):
for event in pygame.event.get():
if(event.type == pygame.QUIT):
pygame.quit()
sys.exit()
screen.blit(image,cropRect,cropRect)
pygame.display.update()

pygame and sprite blur movement

I am struggling to move the sprite correctly. Instead of smooth move I can see blur move and I do not know how to solve it.
Is there any chance you can point what I do incorrectly ?
My target with it to drop the pizza so it hits the bottom and bounce back and bounc back if it hits the top and again the bottom -> bounce -> top -> bounce etc. etc.
import pygame
gravity = 0.5
class PizzaSprite:
def __init__(self, image, spritepos):
self.image = image
self.spos = spritepos
(x, y) = spritepos
self.posx = x
self.posy = y
self.xvel = 1
self.yvel = 1
print "x ", x
print "y ", y
def draw(self, target_surface):
target_surface.blit(self.image, self.spos)
def update(self):
self.posy -= self.yvel
self.spos = (self.posx, self.posy)
return
def main():
pygame.init()
screen_width = 800
screen_height = 600
x = screen_width
y = screen_height
screen = pygame.display.set_mode((screen_width, screen_height))
wall_image = pygame.image.load("wall.png")
sky_image = pygame.image.load("sky.png")
pizza_image = pygame.image.load("pizza.png")
screen.blit(wall_image,(0,200))
screen.blit(sky_image,(0,0))
all_sprites = []
pizza1 = PizzaSprite(pizza_image, (x/2, y/2))
all_sprites.append(pizza1)
while True:
ev = pygame.event.poll()
if ev.type == pygame.QUIT:
break
for sprite in all_sprites:
sprite.update()
for sprite in all_sprites:
sprite.draw(screen)
pygame.display.flip()
pygame.quit()
main()
in the beginning of your main game while loop add
white = (255,255,255)
screen.fill(white)
let me give you a small analogy of what is happening now,
you have paper and a lot of pizza stickers with the intent to make a flip book. To make the illusion of movement on each piece of paper you place a sticker a little bit lower. The screen.fill command essentially clears the screen with the rgb color value you give it. When you dont fill the screen essentially what you are doing is trying to make that flipbook on one piece of paper. You just keep placing more and more stickers a little bit lower making a blur when what you want is one on each page.
and place
pygame.init()
screen_width = 800
screen_height = 600
x = screen_width
y = screen_height
screen = pygame.display.set_mode((screen_width, screen_height))
wall_image = pygame.image.load("wall.png")
sky_image = pygame.image.load("sky.png")
all outside of your main game loop assuming you wont be making changes to these variables ever in your program it is tedious and inefficient to redefine screen,,x,y,and your two images over and over again if they dont change.
so to sum it all up:
use the screen.fill(white) command to reset the color of your screen
You only need to import pngs and define variables once if they are never going to change and don't need them in your main loop
hope this helps clear things up.

Pygame - Limiting instances of sprites

I'm using an example regarding sprite generation for a space scroller shootup that I'm developing. By slowly trying to understand how it works, I've managed to get multiple sprites to transverse across the screen. However, there are many sprites that are generated.
So what I'm having trouble with is limiting the initial number of sprites instead of the multitude that the code produces. I thought of using if sprites.__len__ < 10: sprites.add(drone) but when I tried that, it didn't work.
My thinking was that each time it looped, it would check the number of sprites in the group and if it was less then 10, add a sprite to the group until it hit 10. That way if it went off screen or is destroyed, then it would keep doing the check and keeping it constant.
This is the player class:
class Player(pygame.sprite.Sprite):
def __init__(self, *groups):
super(Player, self).__init__(*groups)
self.image = pygame.image.load('player.png')
self.rect = pygame.rect.Rect((screen_width, (random.randrange(0,screen_height))), self.image.get_size())
self.dx = -10
self.pos = random.randrange(0,screen_height)
def update(self):
self.rect.centerx += self.dx
if self.rect.right < 0:
self.kill()
and this is the section regarding the adding of the sprite.
sprites.update()
screen.fill((200, 200, 200))
sprites.draw(screen)
drone = Player()
self.y = random.randrange(0,screen_height)
sprites.add(drone)
pygame.display.flip()
It's probably obvious, but I'm still learning so guidance would be great.
Second question - More of a confirmation of thought. If I don't want the sprite to be half drawn on the bottom of the screen. Do I basically say that if self.rect.bottom > screen_height, then position the sprite # screen_height
Full source: http://pastebin.com/PLRVHtxz
EDIT - I think I've solved it, just need to make the sprites run smoother.
while 1:
clock.tick(40)
numberAlien = 5
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
sprites.update()
screen.fill((200, 200, 200))
sprites.draw(screen)
drone = Player()
if sprites.__len__() < numberAlien:
self.y = random.randrange(0,screen_height)
sprites.add(drone)
pygame.display.flip()
You could subclass SpriteGroup, add a new field of the total number of sprites, and check in the add method to see if it can be added.
You shouldn't test check any variables with __.
As for the movement, i believe, you do not see a smooth movement because of clock.tick(40).
It waits for 40ms until it resumes running. You could reduce tick to 10, and tune the dx you change for the sprites, or try a more universal approach.
A call to clock.tick() returns amount of ms since the last call. This will be your time delta. You can then have a global SPEED. The amount of pixels to be moved would be calculated from SPEED * delta.