so I was trying to add blinking cursors for my text. I don't know why the cursor only appears at y=0, not at each text box. I was trynna add a cursor for each box when active and stop blitting when not active. I suspect it goes wrong because I got my declaration wrong or the blitting part. Can anyone point out where it goes wrong/ how to fix it? Thanks
import pygame
import datetime
import time
pygame.init()
clock = pygame.time.Clock()
pygame.font.init()
# Note
finish = 0
leftover = 0
# Font
numb_font = pygame.font.Font(Arial, 14)
text_font = pygame.font.Font(Arial, 16)
color = (233, 248, 215)
active = False
# screen resolution
Width = 800
Height = 600
#bg = pygame.image.load('opennote.png')
screen = pygame.display.set_mode((Width, Height))
# Time
time_box = pygame.Rect(250, 63, 50, 30)
date_box = pygame.Rect(221, 27, 50, 30)
# boxes numb
leftover_box = pygame.Rect(265, 105, 30, 30)
finish_box = pygame.Rect(325, 105, 30, 30)
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x, y, w, h)
self.color = color
self.text = text
self.txt_surface = text_font.render(text, True, self.color)
self.active = False
self.score = 1
# Cursor declare
self.txt_rect = self.txt_surface.get_rect()
self.cursor = pygame.Rect(self.txt_rect.topright, (3, self.txt_rect.height + 2))
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
# If the user clicked on the input_box rect.
if self.rect.collidepoint(event.pos):
# Toggle the active variable.
self.active = not self.active
else:
self.active = False
if event.type == pygame.KEYDOWN:
if self.active:
if event.key == pygame.K_RETURN:
print(self.text)
global leftover
leftover += self.score
self.score = 0
self.text = ''
self.active = False
elif event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode
# Cursor
self.txt_rect.size = self.txt_surface.get_size()
self.cursor.topleft = self.txt_rect.topright
# Limit characters -20 for border width
if self.txt_surface.get_width() > self.rect.w - 15:
self.text = self.text[:-1]
def draw(self, screen):
# Blit the text.
screen.blit(self.txt_surface, (self.rect.x + 5, self.rect.y + 10))
# Blit the rect.
pygame.draw.rect(screen, self.color, self.rect, 1)
# Blit the cursor
if time.time() % 1 > 0.5:
pygame.draw.rect(screen, self.color, self.cursor)
def update(self):
# Re-render the text.
self.txt_surface = text_font.render(self.text, True, self.color)
def main():
clock = pygame.time.Clock()
input_box1 = InputBox(115, 170, 250, 36)
input_box2 = InputBox(115, 224, 250, 36)
input_box3 = InputBox(115, 278, 250, 36)
input_box4 = InputBox(115, 333, 250, 36)
input_box5 = InputBox(115, 386, 250, 36)
input_box6 = InputBox(115, 440, 250, 36)
input_box7 = InputBox(115, 494, 250, 36)
input_box8 = InputBox(440, 170, 250, 36)
input_box9 = InputBox(440, 224, 250, 36)
input_box10 = InputBox(440, 278, 250, 36)
input_box11 = InputBox(440, 333, 250, 36)
input_box12 = InputBox(440, 386, 250, 36)
input_box13 = InputBox(440, 440, 250, 36)
input_box14 = InputBox(440, 494, 250, 36)
input_box15 = InputBox(440, 115, 250, 36)
input_box16 = InputBox(440, 61, 250, 36)
input_boxes = [input_box1, input_box2, input_box3, input_box4, input_box5, input_box6, input_box7, input_box8,
input_box9, input_box10, input_box11, input_box12, input_box13, input_box14, input_box15, input_box16]
done = False
while not done:
# Background
screen.fill((0, 0, 0))
#screen.blit(bg, (0, 0))
now = datetime.datetime.now()
date_now = now.strftime("%d/%m/%Y")
time_now = now.strftime("%H:%M:%S")
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
for box in input_boxes:
box.handle_event(event)
for box in input_boxes:
box.update()
for box in input_boxes:
box.draw(screen)
# Real Time
# Date
pygame.draw.rect(screen, 'white', date_box, -1)
datebox_surface = numb_font.render(date_now, True, color)
screen.blit(datebox_surface, (date_box.x + 5, date_box.y + 5))
# Time
pygame.draw.rect(screen, 'white', time_box, -1)
timebox_surface = numb_font.render(time_now, True, color)
screen.blit(timebox_surface, (time_box.x + 5, time_box.y + 5))
# finish &Leftover
# finish box
pygame.draw.rect(screen, 'white', finish_box, -1)
finishbox_surface = numb_font.render(str(finish), True, color)
screen.blit(finishbox_surface, finish_box)
# Leftover box
pygame.draw.rect(screen, 'white', leftover_box, -1)
leftover_box_surface = numb_font.render(str(leftover), True, color)
screen.blit(leftover_box_surface, leftover_box)
pygame.display.update()
clock.tick(120)
if __name__ == '__main__':
main()
pygame.quit()
All you need to do is to set the position of the cursor. Get the right center position of the bounding rectangle of the text and set the left center position of the cursor:
class InputBox:
# [...]
def draw(self, screen):
# Blit the text.
screen.blit(self.txt_surface, (self.rect.x + 5, self.rect.y + 10))
# Blit the rect.
pygame.draw.rect(screen, self.color, self.rect, 1)
# Blit the cursor
if time.time() % 1 > 0.5:
# bounding rectangle of the text
text_rect = self.txt_surface.get_rect(topleft = (self.rect.x + 5, self.rect.y + 10))
# set cursor position
self.cursor.midleft = text_rect.midright
pygame.draw.rect(screen, self.color, self.cursor)
I believe your problem is in the __init__() of your InputBox class.
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x, y, w, h)
self.color = color
self.text = text
self.txt_surface = text_font.render(text, True, self.color)
self.active = False
self.score = 1
# Cursor declare
self.txt_rect = self.txt_surface.get_rect()
self.cursor = pygame.Rect(self.txt_rect.topright, (3, self.txt_rect.height + 2))
self.text_surface is the result of a call to the .render method of a pygame.font.Font object. This method-call returns a pygame.Surface object. The Surface object returned, however, doesn't have a position yet. Therefore, in the line where you have self.txt_rect = self.txt_surface.get_rect(), the pygame.Rect object that is returned has by default its topleft coordinate at (0, 0) (see the documentation).
This is easily fixed. You just need to replace self.txt_rect = self.txt_surface.get_rect() with self.txt_rect = self.txt_surface.get_rect(topleft=(x, y)).
Related
I have many different classes including Main, Enemy and Tower, in these classes i have methods and such, and i am trying to run a for loop provided by someone else on stack overlow (Thank you so much if your reading this), and i keep getting the same error local variable tower refferenced before assignment and i dont understand it.
import sys
import pygame
from pygame.locals import *
from random import *
WIDTH = 800
HEIGHT = 600
RED = (150, 0, 0)
LRED = (255, 0, 0)
GREEN = (0, 150, 0)
LGREEN = (0, 255, 0)
BLUE = (0, 0, 150)
LBLUE = (0, 0, 255)
CYAN = (0, 225, 230)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
PURPLE = (150, 0, 150)
LPURPLE = (255, 0, 255)
COLORS = [RED, LRED, GREEN, LGREEN, BLUE, LBLUE, WHITE, PURPLE, LPURPLE]
pygame.init()
Mainclock = pygame.time.Clock()
light_image_map1 = pygame.image.load('Kami_lookout.png')
light_image_map1 = pygame.transform.scale(light_image_map1, (840, 630))
action_box_image = pygame.image.load('goku.png')
background_rectangle = pygame.Rect(0, 0, WIDTH, HEIGHT)
fantower_image = pygame.image.load('saibaman1.png')
fantower_image = pygame.transform.scale(fantower_image, (30, 40))
tower1 = pygame.image.load('goku.png')
def wave(quantity, size, distance):
global saiba
hh = True
for i in range(quantity):
saiba = Enemy(800 + (distance + size)*i, 100- size/2, size, size)
MainWindow.enemy.append(saiba)
def text_objects(text, font):
textSurface = font.render(text, True, WHITE)
return textSurface, textSurface.get_rect()
def button_text(msg, x, y, width, height, mouselse, mouseover, action = None, Text = True):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+width > mouse[0] > x and y+height > mouse[1] > y:
pygame.draw.rect(MainWindow.Gamewindow, mouseover,(x,y,width,height))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(MainWindow.Gamewindow, mouselse,(x,y,width,height))
smallText = pygame.font.Font("freesansbold.ttf", 20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x+(width/2)), (y+(height/2)))
MainWindow.Gamewindow.blit(textSurf, textRect)
def button_tower(x, y, width, height, mouse, click, image, action = None):
if x+width > mouse[0] > x and y+height > mouse[1] > y:
if click[0] == 1 and action != None:
MainWindow.action_box = action
def tower(width=30, height=30):
global goku
goku = Tower(MainWindow.mouse[0], MainWindow.mouse[1], width, height)
MainWindow.tower.append(goku)
class Main:
def __init__(self, width = WIDTH+100, height = HEIGHT + 100):
pygame.display.set_caption('DBZ Tower Defense')
self.startwave = False
self.width = width
self.height = height
self.Gamewindow = pygame.display.set_mode((self.width, self.height))
def wave(self):
self.startwave = True
def Intro(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.Gamewindow.fill(BLACK)
largeText = pygame.font.Font('freesansbold.ttf', 30)
TextSurf, TextRect = text_objects("simple tower defense game", largeText)
TextRect = (100, 100)
self.Gamewindow.blit(TextSurf, TextRect)
button_text("New game", 100, 200, 400, 50, GREEN, LGREEN, MainWindow.MainLoop)
button_text("Continue", 100, 300, 400, 50, RED, LRED)
button_text("Exit", 100, 400, 400, 50, BLUE, LBLUE, quit)
pygame.display.update()
def MainLoop(self):
self.enemy = []
self.tower = []
self.action_box = None
while True:
Mainclock.tick(60)
self.mouse = pygame.mouse.get_pos()
self.click = pygame.mouse.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == ord('t'):
tower()
if self.startwave == True and len(self.enemy)==0:
wave(10, 20, 8)
self.startwave = False
for index,ene in enumerate(self.enemy):
ene.update()
ene.move()
if ene.rect.left <= 0:
del self.enemy[index]
self.Gamewindow.fill(CYAN)
self.Gamewindow.blit(light_image_map1, background_rectangle)
button_tower(800, 0, 50, 50, self.mouse, self.click, fantower_image, tower)
if pygame.mouse.get_pressed()[0] == 1 and self.action_box != None:
rectangle30 = pygame.Rect(self.mouse[0]-15, self.mouse[1]-15, 30, 30)
self.Gamewindow.blit(action_box_image, rectangle30)
elif self.action_box != None:
self.action_box()
self.action_box = None
for object_enemy in self.enemy:
self.Gamewindow.blit(fantower_image, object_enemy.rect)
for object_tower in self.tower:
self.Gamewindow.blit(object_tower.image, object_tower.rect)
button_text("Start next wave", 0, 600, WIDTH, 100, PURPLE, LPURPLE, MainWindow.wave)
**#This is where the problem is**
**for tower in self.tower:
tower_rect = tower.get_rect()
for enemy in self.enemy:
if ( enemy.collidesWith( tower_rect ) ):
# Make enemy dead
enemy.die()**
**#There might be a problem here in future too**
**for i in range( len( self.enemy ) - 1, -1, -1): # note: loop backwards
if ( self.enemy[i].isDead() ):
del( self.enemy[i] )**
pygame.display.update()
class Enemy:
def __init__(self, x, y, width, height):
self.dead = False
self.rect = pygame.Rect(x, y, width, height)
self.dir = 4
self.movement = [(810, 100, 2), (810, 300, 4), (575, 300, 8), (575, 230, 4), (385, 230, 2), (385, 300, 4), (276, 300, 2), (276, 392, 4), (70, 392, 8), (70, 300, 4)]
def move(self):
if self.dir == 8:
self.rect.centery -= 1
if self.dir == 4:
self.rect.centerx -= 1
if self.dir == 6:
self.rect.centerx += 1
if self.dir == 2:
self.rect.centery += 1
def update(self):
for pos in self.movement:
if self.rect.center == (pos[0], pos[1]):
self.dir = pos[2]
def color(self, colorid):
return COLORS[colorid]
def die( self, action=True ):
self.dead = action
def isDead( self ):
return self.dead
def collidesWith( self, other_rect ):
""" Return true, if other_rect overlaps my rect """
result = self.rect.colliderect( other_rect )
def get_rect( self ):
""" Get a copy of the rect, in PyGame style """
return self.rect.copy()
class Tower:
def __init__(self, x, y, width, height):
self.rect = pygame.Rect(x-15, y-15, width, height)
self.image = pygame.transform.scale(tower1, (50, 50))
def colliderec(self):
if self.rect.collidedict(self.rect):
print("true")
#if Enemy.rect.collideRect(Tower.rect):
# print("true")
class GameInformation:
def __init__(self, money, health, x, y):
self.screen_X = x
self.screen_Y = y
self.money = money
self.health = health
def display_text(win, text, x, y):
pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 30)
textsurface = myfont.render(text, False, (0, 0, 0))
win.blit(textsurface, (x, y))
class Collide:
def __init__(self, pos_x, pos_y, size_x, size_y):
self.pos_x = pos_x
self.pos_y = pos_y
self.size_x = size_x
self.size_y = size_y
self.hitbox_rect = Rect(pos_x, pos_y, size_x, size_y) # rectangle hitbox
MainWindow = Main()
MainWindow.Intro()
There's some issues referencing which variable is from which object. And I think it's just a question-paste issue, but it's not clear if wave() belongs as a member of class Main or not. I assumed it was, and added some selfs where needed.
I hate the whole "idiomatic code" paradigm, but generally PyGame "sprite like" objects define an image and a rectangle. Most examples do it like this, and the Sprite Class uses it too. It's a simple but powerful method. The rectangle defines the position and bounds of the sprite, and the image what it looks like. I did modify the Tower and Enemy classes to use this idiom.
The code was mostly OK already. You need to be careful with referencing things inside the local class, Vs other classes. Inside the class for local members, it's always self.member_name. And don't forget the self as the first parameter on member functions.
Anyway I played with the code to the point where it works. You may want to compare this code with your own, with a comparison tool like Meld. There was nothing in particular that was broken, just a handful of little issues. I had to comment out some stuff that I didn't have access to, like the buttons, and substitute images.
import sys
import pygame
WIDTH = 800
HEIGHT= 800
CYAN=(0x00, 0xff, 0xff)
pygame.init()
Mainclock = pygame.time.Clock()
class Tower:
def __init__(self, x, y, width, height):
self.image = pygame.image.load( "tower2.png" ).convert_alpha()
self.image = pygame.transform.smoothscale( self.image, ( width, height ) )
self.rect = self.image.get_rect()
self.rect.center = ( x, y )
def get_rect( self ):
""" Get a copy of the rect, in PyGame style """
return self.rect.copy()
class Enemy:
def __init__(self, x, y, width, height):
self.dead = False
self.dir = 4
self.movement = [(810, 100, 2), (810, 300, 4), (575, 300, 8), (575, 230, 4), (385, 230, 2), (385, 300, 4), (276, 300, 2), (276, 392, 4), (70, 392, 8), (70, 300, 4)]
self.image = pygame.image.load( "monster.png" ).convert_alpha()
self.image = pygame.transform.smoothscale( self.image, ( width, height ) )
self.rect = self.image.get_rect()
self.rect.topleft = ( x, y )
def move(self):
if self.dir == 8:
self.rect.centery -= 1
if self.dir == 4:
self.rect.centerx -= 1
if self.dir == 6:
self.rect.centerx += 1
if self.dir == 2:
self.rect.centery += 1
def update(self):
for pos in self.movement:
if self.rect.center == (pos[0], pos[1]):
self.dir = pos[2]
def color(self, colorid):
return COLORS[colorid]
def die( self, action=True ):
self.dead = action
def isDead( self ):
return self.dead
def collidesWith( self, other_rect ):
""" Return true, if other_rect overlaps my rect """
return self.rect.colliderect( other_rect )
def get_rect( self ):
""" Get a copy of the rect, in PyGame style """
return self.rect.copy()
class Main:
def __init__(self, width = WIDTH+100, height = HEIGHT + 100):
pygame.display.set_caption('DBZ Tower Defense')
self.startwave = False
self.width = width
self.height = height
self.Gamewindow = pygame.display.set_mode((self.width, self.height))
# Load images
self.light_image_map1 = pygame.image.load( "background.png" ).convert_alpha()
self.light_image_map1 = pygame.transform.smoothscale( self.light_image_map1, ( width, height ) )
self.background_rectangle = self.light_image_map1.get_rect()
self.background_rectangle.topleft = (0,0)
def wave(self):
self.startwave = True
def Intro(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.Gamewindow.fill(BLACK)
largeText = pygame.font.Font('freesansbold.ttf', 30)
TextSurf, TextRect = text_objects("simple tower defense game", largeText)
TextRect = (100, 100)
self.Gamewindow.blit(TextSurf, TextRect)
button_text("New game", 100, 200, 400, 50, GREEN, LGREEN, MainWindow.MainLoop)
button_text("Continue", 100, 300, 400, 50, RED, LRED)
button_text("Exit", 100, 400, 400, 50, BLUE, LBLUE, quit)
pygame.display.update()
def MainLoop(self):
self.enemy = []
self.tower = []
self.action_box = None
self.startwave = True # Don't have button code, force start
while True:
Mainclock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif ( event.type == pygame.MOUSEBUTTONUP ):
# create a tower where the mouse was clicked
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
self.tower.append( Tower( mouse[0], mouse[1], 64, 64 ) )
if self.startwave == True and len(self.enemy)==0:
self.wave(10, 20, 8)
self.startwave = False
for i in range( len( self.enemy ) - 1, -1, -1): # note: loop backwards
self.enemy[i].update()
self.enemy[i].move()
if ( self.enemy[i].rect.left <= 0 ):
del( self.enemy[i] )
self.Gamewindow.fill(CYAN)
self.Gamewindow.blit(self.light_image_map1, self.background_rectangle)
#button_tower(800, 0, 50, 50, self.mouse, self.click, fantower_image, tower)
if pygame.mouse.get_pressed()[0] == 1 and self.action_box != None:
rectangle30 = pygame.Rect(self.mouse[0]-15, self.mouse[1]-15, 30, 30)
self.Gamewindow.blit(action_box_image, rectangle30)
elif self.action_box != None:
self.action_box()
self.action_box = None
for object_enemy in self.enemy:
self.Gamewindow.blit(object_enemy.image, object_enemy.rect)
for object_tower in self.tower:
self.Gamewindow.blit(object_tower.image, object_tower.rect)
#button_text("Start next wave", 0, 600, WIDTH, 100, PURPLE, LPURPLE, MainWindow.wave)
for tower in self.tower:
for enemy in self.enemy:
if ( enemy.collidesWith( tower.get_rect() ) ):
# Make enemy dead
print("COLLIDES WITH TOWER")
enemy.die()
for i in range( len( self.enemy ) - 1, -1, -1): # note: loop backwards
if ( self.enemy[i].isDead() ):
del( self.enemy[i] )
pygame.display.update()
def wave( self, quantity, size, distance): # <<-- Made member function of MainWindow
global saiba
hh = True
for i in range(quantity):
saiba = Enemy(800 + (distance + size)*i, 100- size/2, size, size)
self.enemy.append(saiba)
# MAIN
MainWindow = Main()
MainWindow.MainLoop()
I think when I see these types of errors it usually means that I'm trying to access an object that hasn't been declared yet. I'm sure you know what constructors are, therefore did you initialize a variable before getting into your main() loops?
Example:
# step 1: Declare class
class Dog:
pass
# step 2: Initialize a new Dog
my_dog = Dog() # Did you skip this?
my_dog.name = "scruffy"
# step 3: Driver code that gets work done
print(my_dog.name) # you are probably here and forgot step 2
The program consists in generating 2 random numbers, rendering them on screen (with the '+' symbol, because it's a sum) and expecting the user to put the result of the sum on the box entry. The code already has a function that generates 2 random numbers (x and y), and another one that renders them on screen (besides the score). Here is the code:
import pygame
import random
from InputBox import InputBox
pygame.init()
clock = pygame.time.Clock()
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Projecte MatZanfe")
font = pygame.font.SysFont('comicsans', 50)
base_font = pygame.font.Font(None, 32)
user_text = ''
color_active = pygame.Color('lightskyblue3')
running = True
points = 0
def start_the_game():
x = random.randint(0, 10)
y = random.randint(0, 10)
is_correct = False
return x, y
def display_the_game(x, y):
# Variables
z = x + y
surface.fill((255, 70, 90))
text = font.render(str(x) + "+" + str(y), True, (255, 255, 255))
text_surface = base_font.render(user_text, True, (255, 255, 255))
surface.blit(text, (260, 120))
input_box.draw(surface)
punts = font.render("PuntuaciĆ³: " + str(points),True, (255,255,255))
surface.blit(punts, (350,30))
x, y = start_the_game()
input_box = InputBox(190, 250, 200, 32)
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
result = input_box.handle_event(event)
if result != None:
if int(result) == int(x) + int(y):
# TODO: when the user is right
points = points + 5
start_the_game()
pygame.display.update()
display_the_game(x, y)
pygame.display.update()
else:
# TODO: when the user is wrong
start_the_game
pygame.display.update()
display_the_game(x, y)
pygame.display.update()
display_the_game(x, y)
pygame.display.update()
pygame.quit()
I need the program to generate two new random numbers if the result is right and render them, apart from adding 5 points to the "PuntuaciĆ³" that appears up to the right (done). If the user is wrong, it just needs to generate 2 new random numbers, and render them (the score doesn't have to change).
Here is the code from the imported InputBox.
import pygame
pygame.init()
surface = pygame.display.set_mode((600, 400))
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('dodgerblue2')
FONT = pygame.font.SysFont('comicsans', 32)
base_font = pygame.font.Font(None, 32)
color_active = pygame.Color('lightskyblue3')
user_text = ''
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x, y, w, h)
self.color = COLOR_INACTIVE
self.text = text
self.txt_surface = FONT.render(text, True, self.color)
self.active = False
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
# If the user clicked on the input_box rect.
if self.rect.collidepoint(event.pos):
# Toggle the active variable.
self.active = not self.active
else:
self.active = False
# Change the current color of the input box.
self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
if event.type == pygame.KEYDOWN:
if self.active:
if event.key == pygame.K_RETURN:
user_input = self.text
self.text = ''
self.txt_surface = FONT.render(self.text, True, self.color)
return user_input
elif event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode
# Re-render the text.
self.txt_surface = FONT.render(self.text, True, self.color)
def update(self):
# Resize the box if the text is too long.
width = max(200, self.txt_surface.get_width()+10)
self.rect.w = width
def draw(self, screen):
# Blit the text.
screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
# Blit the rect.
pygame.draw.rect(screen, self.color, self.rect, 2)
def main():
clock = pygame.time.Clock()
input_box2 = InputBox(190, 250, 200, 32)
input_boxes = [input_box2]
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
for box in input_boxes:
box.handle_event(event)
for box in input_boxes:
box.update()
surface.fill((255, 70, 90))
for box in input_boxes:
box.draw(surface)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pygame.quit()
All you have to do is to create new values for x and y and to reset the input box:
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
result = input_box.handle_event(event)
if result != None:
if int(result) == int(x) + int(y):
points = points + 5
# create new random numbers
x, y = start_the_game()
# reset input box (just create a new box)
input_box = InputBox(190, 250, 200, 32)
display_the_game(x, y)
pygame.display.update()
pygame.quit()
So i'm trying to set up this thing where a sound effect is made whenever the player "hovers" their mouse above a label.
This is the image: https://gyazo.com/ca251495b348ab8cd27f7328c84518e8
I've tried looking for solutions, I have found one previously but it did not work when adding sound to it.
import math, random, sys
import enum
import pygame, time
from pygame.locals import*
from sys import exit
from pygame import mixer
#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
mixer.init()
#define display
W, H = 1600,900
HW, HH = (W/2), (H/2)
AREA = W * H
#bsound effects
buttonsound1 = pygame.mixer.Sound("ButtonSound1.wav")
#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
FPS = 54
progress = 0
background = pygame.Surface(DS.get_size())
smallfont = pygame.font.SysFont("century gothic",25)
#background image
bg = pygame.image.load("Daytime.jpg").convert()
loadingimg = pygame.image.load("LoadingScreen.png").convert()
pause = pygame.image.load("Pause screen.png").convert()
gameover = pygame.image.load("Game Over.png").convert()
mainmenu = pygame.image.load("Main_Menu4.png").convert()
#mainmenu = pygame.transform.smoothscale(mainmenu, (W,H))
loadingimg = pygame.transform.smoothscale(loadingimg, (W,H))
#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)
walkLeft = [pygame.image.load('Moving1.png'), pygame.image.load('Moving2.png'), pygame.image.load('Moving3.png'), pygame.image.load('Moving4.png'), pygame.image.load('Moving5.png'), pygame.image.load('Moving6.png'), pygame.image.load('Moving7.png'), pygame.image.load('Moving8.png'), pygame.image.load('Moving9.png')]
walkRight = []
for i in walkLeft:
walkRight.append(pygame.transform.flip(i, True, False))
char = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.transform.flip(char2, True, False)
x = 0
y = 500
height = 40
width = 87
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0
run = True
# FUNCTIONS
def event_handler():
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(green)
self.image_hovered = pygame.Surface((width, height))
#buttonsound1.play()
self.image = self.image_normal
self.rect = self.image.get_rect()
font = pygame.font.Font('freesansbold.ttf', 15)
text_image = font.render(text, True, WHITE)
text_rect = text_image.get_rect(center = self.rect.center)
self.image_normal.blit(text_image, text_rect)
self.image_hovered.blit(text_image, text_rect)
# you can't use it before `blit`
self.rect.topleft = (x, y)
self.hovered = False
#self.clicked = False
def update(self):
if self.hovered:
buttonsound1.play()
else:
self.image = self.image_normal
def draw(self, surface):
surface.blit(self.image, self.rect)
def handle_event(self, event):
if event.type == pygame.MOUSEMOTION:
self.hovered = self.rect.collidepoint(event.pos)
buttonsound1.play()
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hovered:
buttonsound1.play()
print('Clicked:', self.text)
if self.command:
self.command()
class GameState( enum.Enum ):
Loading = 0
Menu = 1
Settings = 2
Playing = 3
GameOver = 4
#set the game state initially.
game_state = GameState.Loading
#LOADING
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
return textSurface, textSurface.get_rect()
def loading(progress):
if progress < 100:
text = smallfont.render("Loading: " + str(int(progress)) + "%", True, WHITE)
else:
text = smallfont.render("Loading: " + str(100) + "%", True, WHITE)
DS.blit(text, [50, 660])
def message_to_screen(msh, color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = HW, HH + y_displace
DS.blit(textSurf, textRect)
while (progress/4) < 100:
event_handler()
DS.blit(loadingimg, (0,0))
time_count = (random.randint(1,1))
increase = random.randint(1,20)
progress += increase
pygame.draw.rect(DS, green, [50, 700, 402, 29])
pygame.draw.rect(DS, grey, [50, 701, 401, 27])
if (progress/4) > 100:
pygame.draw.rect(DS, green, [50, 700, 401, 28])
else:
pygame.draw.rect(DS, green, [50, 700, progress, 28])
loading(progress/4)
pygame.display.flip()
time.sleep(time_count)
#changing to menu
game_state = GameState.Menu
Menumusic = pygame.mixer.music.load("MainMenu.mp3")
Menumusic = pygame.mixer.music.play(-1, 0.0)
def main_menu():
DS.blit(mainmenu, (0, 0))
pygame.display.update()
btn1 = Button('Hello', 812.5, 250, 100, 50)
btn2 = Button('World', 825, 325, 100, 50)
btn3 = Button('Hello', 825, 450, 100, 50)
btn4 = Button('World', 825, 575, 100, 50)
btn5 = Button('World', 825, 675, 100, 50)
btn6 = Button('Hello', 825, 790, 100, 50)
while run:
event_handler()
btn1.update()
btn2.update()
# --- draws ---
btn1.draw(DS)
btn2.draw(DS)
btn3.draw(DS)
btn4.draw(DS)
btn5.draw(DS)
btn6.draw(DS)
pygame.display.update()
main_menu()
What I'm expecting is a sound effect to be made whenever the mouse goes over a label, however, the output from the program is that nothing plays or happens.
I think the issue is the processing of the events in event_handler(), which consumes all the events. Then the Button class handle_event() function is starved of events (also this function is never called). It's a good idea to handle events in a single place in the code, and call out from there.
If the OP's code did work, it looks to be constantly re-playing the sounds too. The mouse-move generates a lot of events, so the triggering of playing the sound needs to only play on the initial entry into the button's rectangle. Whereas the mouse movement handler is re-playing on every event inside the button's rect.
Below is some example code where I took your buttons, and modified them to handle the hovering in a "edge-triggered" manner. This means it only triggers when the "hovered" state first becomes true, not while it's true (which would be "level-triggered")
Note: It does not actually play the sound, as I don't have a sound-file handy. It just does a print().
import pygame
#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
pygame.mixer.init()
#define display
W, H = 200, 200
HW, HH = (W/2), (H/2)
AREA = W * H
#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
#pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.display.set_mode((0, 0) )
FPS = 54
#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(green)
self.image_hovered = pygame.Surface((width, height))
self.image_hovered.fill(grey)
self.image = self.image_normal
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.hovered= False # is the mouse over this button?
def update(self):
pass
def handleMouseOver( self, mouse_position ):
""" If the given co-ordinate inside our rect,
Do all the mouse-hovering work """
# Check button position against mouse
# Change the state *once* on entry/exit
if ( self.mouseIsOver( mouse_position ) ):
if ( self.hovered == False ):
self.image = self.image_hovered
self.hovered = True # edge-triggered, not level triggered
# Do we want to check pygame.mixer.get_busy() ?
if ( pygame.mixer.get_busy() == False ):
print( self.text + " DO buttonsound1.play() ")
else:
if ( self.hovered == True ):
self.image = self.image_normal
self.hovered = False
def mouseIsOver( self, mouse_position ):
""" Is the given co-ordinate inside our rect """
return self.rect.collidepoint( mouse_position )
def draw(self, surface):
surface.blit(self.image, self.rect)
def main_menu():
run = True
btn1 = Button('Hello1', 50, 50, 40, 40)
btn2 = Button('World2', 100, 50, 40, 40)
btn3 = Button('Hello3', 50, 100, 40, 40)
btn4 = Button('World4', 100, 100, 40, 40)
# Put the buttons into a list so we can loop over them, simply
buttons = [ btn1, btn2, btn3, btn4 ]
while run:
# draw the buttons
for b in buttons:
b.draw( DS ) # --- draws ---
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEMOTION:
mouse_position = event.pos
for b in buttons:
b.handleMouseOver( mouse_position )
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_position = event.pos
for b in buttons:
if ( b.mouseIsOver( mouse_position ) ):
print('Clicked:', b.text)
#if b.command:
# b.command()
pygame.display.update()
main_menu()
pygame.quit()
So im setting up a main menu for the program I'm making and I was planning to have a beeping sound for whenever a mouse hovers above a button.
The thing is, I have the button labels on my image already, so i don't really know how i could incorporate this.
import math, random, sys
import enum
import pygame, time
from pygame.locals import*
from sys import exit
from pygame import mixer
#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
mixer.init()
#define display
W, H = 1600,900
HW, HH = (W/2), (H/2)
AREA = W * H
#bsound effects
buttonsound1 = pygame.mixer.Sound("ButtonSound1.wav")
#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
FPS = 54
progress = 0
background = pygame.Surface(DS.get_size())
smallfont = pygame.font.SysFont("century gothic",25)
#background image
bg = pygame.image.load("Daytime.jpg").convert()
loadingimg = pygame.image.load("LoadingScreen.png").convert()
pause = pygame.image.load("Pause screen.png").convert()
gameover = pygame.image.load("Game Over.png").convert()
mainmenu = pygame.image.load("Main_Menu4.png").convert()
#mainmenu = pygame.transform.smoothscale(mainmenu, (W,H))
loadingimg = pygame.transform.smoothscale(loadingimg, (W,H))
#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)
walkLeft = [pygame.image.load('Moving1.png'), pygame.image.load('Moving2.png'), pygame.image.load('Moving3.png'), pygame.image.load('Moving4.png'), pygame.image.load('Moving5.png'), pygame.image.load('Moving6.png'), pygame.image.load('Moving7.png'), pygame.image.load('Moving8.png'), pygame.image.load('Moving9.png')]
walkRight = []
for i in walkLeft:
walkRight.append(pygame.transform.flip(i, True, False))
char = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.transform.flip(char2, True, False)
x = 0
y = 500
height = 40
width = 87
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0
run = True
# FUNCTIONS
def event_handler():
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(green)
self.image_hovered = pygame.Surface((width, height))
#buttonsound1.play()
self.image = self.image_normal
self.rect = self.image.get_rect()
font = pygame.font.Font('freesansbold.ttf', 15)
text_image = font.render(text, True, WHITE)
text_rect = text_image.get_rect(center = self.rect.center)
self.image_normal.blit(text_image, text_rect)
self.image_hovered.blit(text_image, text_rect)
# you can't use it before `blit`
self.rect.topleft = (x, y)
self.hovered = False
#self.clicked = False
def update(self):
if self.hovered:
buttonsound1.play()
else:
self.image = self.image_normal
def draw(self, surface):
surface.blit(self.image, self.rect)
def handle_event(self, event):
if event.type == pygame.MOUSEMOTION:
self.hovered = self.rect.collidepoint(event.pos)
buttonsound1.play()
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hovered:
buttonsound1.play()
print('Clicked:', self.text)
if self.command:
self.command()
class GameState( enum.Enum ):
Loading = 0
Menu = 1
Settings = 2
Playing = 3
GameOver = 4
#set the game state initially.
game_state = GameState.Loading
#LOADING
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
return textSurface, textSurface.get_rect()
def loading(progress):
if progress < 100:
text = smallfont.render("Loading: " + str(int(progress)) + "%", True, WHITE)
else:
text = smallfont.render("Loading: " + str(100) + "%", True, WHITE)
DS.blit(text, [50, 660])
def message_to_screen(msh, color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = HW, HH + y_displace
DS.blit(textSurf, textRect)
while (progress/4) < 100:
event_handler()
DS.blit(loadingimg, (0,0))
time_count = (random.randint(1,1))
increase = random.randint(1,20)
progress += increase
pygame.draw.rect(DS, green, [50, 700, 402, 29])
pygame.draw.rect(DS, grey, [50, 701, 401, 27])
if (progress/4) > 100:
pygame.draw.rect(DS, green, [50, 700, 401, 28])
else:
pygame.draw.rect(DS, green, [50, 700, progress, 28])
loading(progress/4)
pygame.display.flip()
time.sleep(time_count)
#changing to menu
game_state = GameState.Menu
Menumusic = pygame.mixer.music.load("MainMenu.mp3")
Menumusic = pygame.mixer.music.play(-1, 0.0)
def main_menu():
DS.blit(mainmenu, (0, 0))
pygame.display.update()
btn1 = Button('Hello', 812.5, 250, 100, 50)
btn2 = Button('World', 825, 325, 100, 50)
btn3 = Button('Hello', 825, 450, 100, 50)
btn4 = Button('World', 825, 575, 100, 50)
btn5 = Button('World', 825, 675, 100, 50)
btn6 = Button('Hello', 825, 790, 100, 50)
while run:
event_handler()
btn1.update()
btn2.update()
# --- draws ---
btn1.draw(DS)
btn2.draw(DS)
btn3.draw(DS)
btn4.draw(DS)
btn5.draw(DS)
btn6.draw(DS)
pygame.display.update()
main_menu()
This is my whole code and I'm not sure what to do with adding buttons.
My image: https://gyazo.com/ca251495b348ab8cd27f7328c84518e8
It doesn't matter where you have button label - you need only its positon and size (x,y,width,height) or its pygame.Rect to compare with mouse position.
Rect has even function collidepoint to check collision with point and it can be mouse position.
if button_rect.collidepoint(mouse_position):
print("Mouse over button")
EDIT:
It is my code from GitHub with simple example with hovering button using class Button which changes color when mouse is over button (hover). It uses Rect.coolidepoint in Button.handle_event(). Maybe it can help you.
import pygame
# === CONSTANTS === (UPPER_CASE names)
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(GREEN)
self.image_hovered = pygame.Surface((width, height))
self.image_hovered.fill(RED)
self.image = self.image_normal
self.rect = self.image.get_rect()
font = pygame.font.Font('freesansbold.ttf', 15)
text_image = font.render(text, True, WHITE)
text_rect = text_image.get_rect(center = self.rect.center)
self.image_normal.blit(text_image, text_rect)
self.image_hovered.blit(text_image, text_rect)
# you can't use it before `blit`
self.rect.topleft = (x, y)
self.hovered = False
#self.clicked = False
def update(self):
if self.hovered:
self.image = self.image_hovered
else:
self.image = self.image_normal
def draw(self, surface):
surface.blit(self.image, self.rect)
def handle_event(self, event):
if event.type == pygame.MOUSEMOTION:
self.hovered = self.rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hovered:
print('Clicked:', self.text)
if self.command:
self.command()
# === FUNCTIONS === (lower_case names)
# empty
# === MAIN === (lower_case names)
def main():
# --- init ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
is_running = False
btn1 = Button('Hello', 200, 50, 100, 50)
btn2 = Button('World', 200, 150, 100, 50)
# --- mainloop --- (don't change it)
is_running = True
while is_running:
# --- events ---
for event in pygame.event.get():
# --- global events ---
if event.type == pygame.QUIT:
is_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
is_running = False
# --- objects events ---
btn1.handle_event(event)
btn2.handle_event(event)
# --- updates ---
btn1.update()
btn2.update()
# --- draws ---
screen.fill(BLACK)
btn1.draw(screen)
btn2.draw(screen)
pygame.display.update()
# --- FPS ---
clock.tick(25)
# --- the end ---
pygame.quit()
#----------------------------------------------------------------------
if __name__ == '__main__':
main()
EDIT: play sound only when mouse hovers over button
if event.type == pygame.MOUSEMOTION:
previous_value = self.hovered # remeber previus value
self.hovered = self.rect.collidepoint(event.pos) # get new value
# check both values
if previous_value is False and self.hovered is True:
buttonsound1.play()
# similar play sound when mouse unhovers button
#if previous_value is True and self.hovered is False:
# unhover_sound1.play()
My objective is to make a cannon fire a cannonball in a linear path. I have been playing around with some algorithms for quite a bit, but I cannot get one fluid motion, instead the position updates in chunks and I'm not sure how to evade this problem. Here is my code:
import pygame
from functools import partial
pygame.init()
display_width = 700
display_height = 500
display = pygame.display.set_mode((display_width,display_height))
cannonImg = 'C:/Users/student/Desktop/cannon.png'
skyImg = 'C:/Users/student/Desktop/sky.png'
cannonballImg = 'C:/Users/student/Desktop/cannonball.png'
cannon = pygame.image.load(cannonImg)
sky = pygame.image.load(skyImg)
cannonball = pygame.image.load(cannonballImg)
blue = (0,0,200)
light_blue = (0,0,255)
black = (0,0,0)
red = (200,0,0)
light_red = (255,0,0)
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("Algerian", 50)
largefont = pygame.font.SysFont("Algerian", 85)
altSmall = pygame.font.SysFont("Algerian",20)
altMed = pygame.font.SysFont("Algerian",30)
altLarge = pygame.font.SysFont("Algerian",75)
extrasmall = pygame.font.SysFont("comicsansms",15)
def text_objects(text, color,size = "small"):
if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)
if size == "altMed":
textSurface = altMed.render(text,True,color)
if size == "altSmall":
textSurface = altSmall.render(text,True,color)
if size == "medFont":
textSurface = medfont.render(text,True,color)
if size == "smallFont":
textSurface = smallfont.render(text,True,color)
if size == "extraSmall":
textSurface = extrasmall.render(text,True,color)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',200)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
class Button():
text = str()
x = int()
y = int()
width = int()
height = int()
inactive_color = None
active_color = None
action = str()
active = bool()
def __init__(self,text,x,y,width,height,inactive_color,active_color,action,text_color,text_size,active):
self.text = text
self.x = x
self.y = y
self.width = width
self.height = height
self.inactive_color = inactive_color
self.active_color = active_color
self.action = action
self.text_color = text_color
self.text_size = text_size
self.active = active
def nothing():
pass
def handle_event(self,event):
if self.is_hovered() and event.type == pygame.MOUSEBUTTONDOWN:
self.action()
def text_to_button(self,surface):
textSurf, textRect = text_objects(self.text,self.text_color,self.text_size)
textRect.center = ((self.x+(self.width/2)), self.y+(self.height/2))
surface.blit(textSurf, textRect)
def is_hovered(self):
cur = pygame.mouse.get_pos()
return self.x + self.width > cur[0] > self.x and self.y + self.height > cur[1] > self.y
def drawButton(self, surface):
if self.active:
pygame.draw.rect(surface,self.inactive_color,[self.x,self.y,self.width,self.height])
if self.is_hovered() and self.active:
pygame.draw.rect(surface, self.active_color,[self.x,self.y,self.width,self.height])
self.text_to_button(surface)
def nothing():
pass
class kinematic():
obj_x = 110
obj_y = 240
v = 0
t = 0
def __init__(self,v,t):
self.v = v
self.t = t
def addOneV(self):
self.v += 1
def addOneXI(self):
self.xi += 1
def addOneT(self):
self.t += 1
def reset(self):
self.v = 0
self.t = 0
self.obj_x = 125
self.obj_y = 240
def calculatePos(self):
n = 0
while n < self.t+1:
self.obj_x = self.t * 10
self.obj_y = self.v * n
n += 1
def programLoop():
object1 = kinematic(0,10)
reset = Button("Reset",400,25,100,75,red,light_red,object1.reset,black,"smallFont",True)
programExit = False
while not programExit:
addVelocity = Button("Velocity: %i " % object1.v + "m/s",50, 25,150,50,red,light_red,object1.addOneV,black,"extraSmall",True)
addTime = Button("Time: %i " % object1.t + "s",50, 75,150,50,red,light_red,object1.addOneT,black,"extraSmall",True)
fireCannon = Button("Fire",display_width/2 - 75,25,125,75,red,light_red,object1.calculatePos,black,"smallFont",True)
for evt in pygame.event.get():
fireCannon.handle_event(evt)
addVelocity.handle_event(evt)
addTime.handle_event(evt)
reset.handle_event(evt)
if evt.type == pygame.QUIT:
pygame.quit()
quit()
display.blit(sky,[0,0])
display.blit(cannon,[25,300])
fireCannon.drawButton(display)
addVelocity.drawButton(display)
addTime.drawButton(display)
reset.drawButton(display)
display.blit(cannonball,[object1.obj_x,object1.obj_y])
display.blit(cannonball,[object1.obj_x,object1.obj_y])
pygame.display.update()
programLoop()
Thanks! Any help is greatly appreciated.
You need to add the velocity of the object to its position in each frame in order to move it. I also pass the delta time to the update method and multiply it with the velocity to make the object move self.v pixels per second.
import pygame
pygame.init()
display_width = 700
display_height = 500
display = pygame.display.set_mode((display_width,display_height))
CANNONBALL = pygame.Surface((30, 30))
CANNONBALL.fill((90, 90, 90))
LIGHT_BLUE = (140,220,255)
BLACK = (0,0,0)
RED = (200,0,0)
LIGHT_RED = (255,0,0)
SMALLFONT = pygame.font.SysFont("comicsansms", 25)
def text_objects(text, color, font): # You can pass the font object.
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect()
class Button:
def __init__(self, text, x, y, width, height, inactive_color, active_color,
action, text_color, font, active):
self.text = text
# Create a rect instead of the separate x, y, w, h attributes.
self.rect = pygame.Rect(x, y, width, height)
self.inactive_color = inactive_color
self.active_color = active_color
self.action = action
self.text_color = text_color
self.font = font # The font is an attribute now.
self.active = active
def handle_event(self, event):
if self.is_hovered() and event.type == pygame.MOUSEBUTTONDOWN:
self.action()
def text_to_button(self, surface):
textSurf, textRect = text_objects(self.text, self.text_color, self.font)
textRect.center = self.rect.center
surface.blit(textSurf, textRect)
def is_hovered(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
def drawButton(self, surface):
if self.active:
pygame.draw.rect(surface, self.inactive_color, self.rect)
if self.is_hovered() and self.active:
pygame.draw.rect(surface, self.active_color, self.rect)
self.text_to_button(surface)
class Kinematic:
def __init__(self, v):
self.obj_x = 110
self.obj_y = 240
self.v = v
self.started = False
def reset(self):
self.started = False
self.v = 0
self.obj_x = 125
self.obj_y = 240
def start(self):
self.started = True
def update(self, dt):
if self.started:
# Just add the velocity to the position to
# move the object.
# Multiply the velocity by the delta time
# to move `self.v` pixels per second.
self.obj_x += self.v * dt
def programLoop():
clock = pygame.time.Clock()
object1 = Kinematic(0)
# Callback functions to modify the object and update the button texts.
def add_v():
object1.v += 10
addVelocity.text = f"Velocity: {object1.v} m/s"
def reset():
object1.reset()
addVelocity.text = f"Velocity: {object1.v} m/s"
reset = Button(
"Reset", 400, 25, 100, 75, RED, LIGHT_RED,
reset, BLACK, SMALLFONT, True)
addVelocity = Button(
f"Velocity: {object1.v} m/s", 50, 25, 150, 50,
RED, LIGHT_RED, add_v, BLACK, SMALLFONT, True)
fireCannon = Button(
"Fire", display_width/2 - 75, 25, 125, 75, RED, LIGHT_RED,
object1.start, BLACK, SMALLFONT, True)
# You can put all buttons into a list and use for loops to
# draw them and pass the events.
buttons = [reset, addVelocity, fireCannon]
dt = 0
programExit = False
while not programExit:
for evt in pygame.event.get():
for button in buttons:
button.handle_event(evt)
if evt.type == pygame.QUIT:
return
# Call the `update` method once per frame.
object1.update(dt) # Pass the delta time to the object.
display.fill(LIGHT_BLUE)
for button in buttons:
button.drawButton(display)
display.blit(CANNONBALL, [object1.obj_x, object1.obj_y])
pygame.display.update()
# dt is the time that has passed since the last clock.tick call.
dt = clock.tick(60) / 1000
programLoop()
pygame.quit()
I've also tried to improve and simplify a few more things. Take a look at the comments.