Text doesn't display on the title screen button - pygame

I've been having trouble trying to display the title menu text when making a game. I'm trying to display the font on the button so that when I hover my mouse over the button, the font stays on the screen.
import pygame
pygame.init()
background_colour = (33, 37, 49)
screen = pygame.display.set_mode((1000, 600))
pygame.display.set_caption('A Game')
screen.fill(background_colour)
game_font = pygame.font.Font('JetBrainsMono-Regular.ttf', 50)
game_name = game_font.render('a game', True, (255, 255, 255))
game_name = pygame.transform.scale2x(game_name)
game_name_rect = game_name.get_rect(center=(500, 300))
pygame.draw.rect(screen, (38, 44, 60), game_name_rect)
running = True
title_screen = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if title_screen is True:
screen.blit(game_name, game_name_rect)
if not game_name_rect.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen, (38, 44, 60), game_name_rect)
if game_name_rect.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen, (58, 64, 80), game_name_rect)
pygame.display.update()

You need to draw the text after the rectangle:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if title_screen is True:
color = (38, 44, 60)
if game_name_rect.collidepoint(pygame.mouse.get_pos()):
color = (58, 64, 80)
pygame.draw.rect(screen, color, game_name_rect)
screen.blit(game_name, game_name_rect)
pygame.display.update()

Related

How come when I use if .collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0] for a button, it only stays there while I hold it? [duplicate]

I was wondering how to write code that would detect the mouse clicking on a sprite. For example:
if #Function that checks for mouse clicked on Sprite:
print ("You have opened a chest!")
I assume your game has a main loop, and all your sprites are in a list called sprites.
In your main loop, get all events, and check for the MOUSEBUTTONDOWN or MOUSEBUTTONUP event.
while ... # your main loop
# get all events
ev = pygame.event.get()
# proceed events
for event in ev:
# handle MOUSEBUTTONUP
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
# get a list of all sprites that are under the mouse cursor
clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
# do something with the clicked sprites...
So basically you have to check for a click on a sprite yourself every iteration of the mainloop. You'll want to use mouse.get_pos() and rect.collidepoint().
Pygame does not offer event driven programming, as e.g. cocos2d does.
Another way would be to check the position of the mouse cursor and the state of the pressed buttons, but this approach has some issues.
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
print ("You have opened a chest!")
You'll have to introduce some kind of flag if you handled this case, since otherwise this code will print "You have opened a chest!" every iteration of the main loop.
handled = False
while ... // your loop
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
print ("You have opened a chest!")
handled = pygame.mouse.get_pressed()[0]
Of course you can subclass Sprite and add a method called is_clicked like this:
class MySprite(Sprite):
...
def is_clicked(self):
return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())
So, it's better to use the first approach IMHO.
The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.
Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked.
Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/#Rabbid76/PyGame-MouseClick
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.click_image, color, (25, 25), 25)
pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.clicked = False
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.clicked = not self.clicked
self.image = self.click_image if self.clicked else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
See further Creating multiple sprites with different update()'s from the same sprite class in Pygame
The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ​​that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.
Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
if self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/#Rabbid76/PyGame-MouseHover
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.hover_image, color, (25, 25), 25)
pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.hover = False
def update(self):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
#self.hover = self.rect.collidepoint(mouse_pos)
self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)
self.image = self.hover_image if self.hover else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update()
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
The pygame documentation for mouse events is here.
You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed).
Remember to use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.
EDIT:
To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.
I was looking for the same answer to this question and after much head scratching this is the answer I came up with:
# Python 3.4.3 with Pygame
from sys import exit
import pygame
pygame.init()
WIDTH = HEIGHT = 300
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Crash!')
# Draw Once
rectangle = pygame.draw.rect(window, (255, 0, 0), (100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
# Mouse position and button clicking
pos = pygame.mouse.get_pos()
pressed1 = pygame.mouse.get_pressed()[0]
# Check if rectangle collided with pos and if the left mouse button was pressed
if rectangle.collidepoint(pos) and pressed1:
print("You have opened a chest!")
# Quit pygame
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()

User input recorded from multiple text boxes and put into MySQL

I'm running into a brick wall and have spent multiple hours trying to research how to do this and I'm at the point I'm not sure if I'm asking the right question.
I have a page for recording user input in multiple boxes. I've made a separate file for my text box function which feeds into the main page. I want to be able to click next and record all the use input from the text boxes into a MySQL database.
The problem I'm running into seems to be that the main page doesn't know there's user input just that there is a text box, so I can't record anything, while if I change the text input file it defeats the purpose of creating one so that I can use text boxes anywhere.
Main page
import pygame
import Test
import button
import sys
import mysql.connector
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Main Page")
icon = pygame.image.load('icons8-robber-32.png')
pygame.display.set_icon(icon)
colour_active = pygame.Color('orange')
colour_inactive = pygame.Color('Yellow')
font = pygame.font.Font(None, 32)
start_image = pygame.image.load('play.png').convert_alpha()
exit_image = pygame.image.load('exit.png').convert_alpha()
menu_image = pygame.image.load('menu.png').convert_alpha()
back_image = pygame.image.load('back.png').convert_alpha()
next_image = pygame.image.load('next.png').convert_alpha()
def register():
input_box1 = Test.inputBox(210, 105, 140, 32, "First Name: ")
input_box2 = Test.inputBox(210, 160, 140, 32)
input_boxes = [input_box1, input_box2]
back_button = button.Button(100, 450, back_image, 0.2)
next_button = button.Button(450, 450, next_image, 0.2)
done = False
while not done:
for event in pygame.event.get():
for box in input_boxes:
box.handle_event(event)
for box in input_boxes:
box.update()
screen.fill((30, 30, 30))
for box in input_boxes:
box.draw(screen)
if back_button.draw(screen):
print("no")
if next_button.draw(screen):
sys.exit()
pygame.display.update()
start_button = button.Button(100, 150, start_image, 0.2)
exit_button = button.Button(250, 150, exit_image, 0.2)
menu_button = button.Button(400, 150, menu_image, 0.2)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((150, 255, 100))
if start_button.draw(screen):
print("no")
if exit_button.draw(screen):
sys.exit()
if menu_button.draw(screen):
register()
pygame.display.update()
pygame.QUIT()
sys.exit()
Text box file
import pygame
pygame.init()
colour_active = pygame.Color('orange')
colour_inactive = pygame.Color('Yellow')
font = pygame.font.Font(None, 32)
class inputBox():
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x,y,w,h)
self.color = colour_inactive
self.text = text
self.text_surface = font.render(text, True, self.color)
self.active = False
def handle_event(self,event):
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.active = not self.active
else:
self.active = False
self.color = colour_active if self.active else colour_inactive
if event.type == pygame.KEYDOWN:
if self.active:
if event.key == pygame.K_RETURN:
print(self.text)
elif event.key == pygame.K_BACKSPACE:
self.text = self.text [:-1]
else:
self.text += event.unicode
self.text_surface = font.render(self.text, True, self.color)
def update(self):
self.rect.w = max(100, self.text_surface.get_width() + 10)
def draw(self, screen):
screen.blit(self.text_surface, (self.rect.x+5, self.rect.y+5))
pygame.draw.rect(screen, self.color, self.rect, 2)
You do not need the self.text file in the main code. So instead of writing input_box1.self.text, it was just input_box1.text.

I am trying to make a program in pygame on how to draw a star using a set of points which are variables

1.Question:
I want to learn how to make a star using multiple coordinates as variables and using lines to draw them, what I have done so far is correct but if someone could help me with the other variables and apply them to my code that would be great :D
2 code:
import pygame
from pygame.locals import *
pygame.init
white = (255,255,255)
coordinate2 = 250
coordinate1 = 0
coordinate4 = 500
coordinate3 = 250
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("AppliedShapes")
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit
exit()
pygame.draw.line(screen,white,(coordinate2,coordinate1),(coordinate4,coordinate3),5)
pygame.display.update()
3 request:
This is what I have so far and it is correct but I want to make more variables and make more lines to make a star. Sooooo if someone could tell me the variables and apply them that would be great!
You can continue like you have, simply defining more coordinateX variables. However, this will eventually become a problem. Imagine having hundreds of separate variables!
A nicer way would be to use a Python list to hold all the co-ordinates:
point_list = [ (250, 0), (500, 250) ]
(There's lots of online tutorials about Python lists.)
Each element can be accessed (or assigned) by using square-bracket notation with an index-number (starting at zero), so point_list[0] is (250, 0); and point_list[1] is (500, 250). To get the individual x,y parts of each co-ordinate, you can add another pair of square brackets, or get all the parts at once:
first_x = points_list[0][0] # 250
first_y = points_list[0][1] # 0
first_x, first_y = points_list[0] # 250, 0
Lists can hold huge amounts of points, for example, a simple 3-point star:
point_list = [ (148, 170), (200, 20), (252, 170), (356, 290), (200, 260), (44, 290) ]
The other nice thing about keeping them in a list is that you can use the PyGame function pygame.draw.polygon() to simply draw them to the screen.
pygame.draw.polygon( window, YELLOW, point_list, 1 )
Or you can "iterate" through the list, drawing the lines:
for i in range( len( points_list ) - 1 ):
pygame.draw.line( screen, white, points_list[i], points_list[i+1], 5 )
Note that I looped with the length-of-list len() minus one, so we didn't go over the end of the list when referencing [i+1].
Here's a quick example I wrote using the above ideas:
Code:
import pygame
# Window size
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
DARK_BLUE = ( 3, 5, 54)
STARRY = ( 230, 255, 80 )
### initialisation
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Star")
# Define a star
centre_coord = ( WINDOW_WIDTH//2, WINDOW_HEIGHT//2 )
star_points = [ (165, 151), (200, 20), (235, 151), (371, 144), (257, 219),
(306, 346), (200, 260), (94, 346), (143, 219), (29, 144) ]
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
# Re-draw the window
window.fill( DARK_BLUE ) # background fill
pygame.draw.polygon( window, STARRY, star_points ) # Draw the star
pygame.display.flip() # Update the display
# Clamp FPS
clock.tick_busy_loop(60)
pygame.quit()
Or perhaps a 16-point star of 32 co-ordinates:
point_list = [ (173, 63), (200, 20), (227, 63), (269, 34), (278, 84),
(327, 73), (316, 122), (366, 131), (337, 173), (380, 200),
(337, 227), (366, 269), (316, 278), (327, 327), (278, 316),
(269, 366), (227, 337), (200, 380), (173, 337), (131, 366),
(122, 316), (73, 327), (84, 278), (34, 269), (63, 227),
(20, 200), (63, 173), (34, 131), (84, 122), (73, 73),
(122, 84), (131, 34) ]

pygame, getting a sprite to move to cursor position on click

I was trying to make a tower defense sort of game in pygame. When I click on the screen, I want it to be able to move the tower sprite to the position. Currently, when I run the program, it moves the sprite to the cursor with out clicking, then does not let me move it again.
import pygame
import time
pygame.init()
WINDOWWIDTH = 1800
WINDOWHEIGHT = 1800
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
background_colour = (188,69,80)
GAMETITLE = "Tower Defence"
def main():
pygame.display.set_caption(GAMETITLE)
clock = pygame.time.Clock()
spritegroup =pygame.sprite.Group()
sprite =pygame.sprite.Sprite()
tower = sprite.image = pygame.image.load("tower.png")
sprite.image = tower
sprite.rect = sprite.image.get_rect()
sprite.rect.x = 10
sprite.rect.y = 10
sprite.add(spritegroup)
while True:
screen.fill(background_colour)
pygame.draw.rect(screen, (255,255,255), ((0, 100), (1100, 90)))
pygame.draw.rect(screen, (255, 255,255), ((1010, 100), (100, 600)))
pygame.draw.rect(screen, (255,255,255), ((1010, 700), (2400, 90)))
spritegroup.draw(screen)
pygame.display.update()
clock.tick(30)
if pygame.mouse.get_pressed():
cursorPos = pygame.mouse.get_pos()
sprite.rect.x = cursorPos[0]
sprite.rect.y = cursorPos[1]
main()
what is happening is that pygame.mouse.get_pressed() returns a tuple. if statements return true if they are not null. this means that regardless if it is pressed it will return True. then the pygame event queue will fill with mouse events and never get processed. your event loop should look something like:
for event in pygame.event.get():
if event.type == pygame.event.QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
#stuff to do on click

How can I make the triangle in this program rotate?

Please be very specific , because it`s my first time working in pygame :D
#!/usr/bin/env python
import pygame
pygame.init()
#colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
PI = 3.141592653
size = (400, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Professor Craven's Cool Game")
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
pygame.draw.polygon(screen, BLACK, [[100, 100], [0, 200], [200, 200]], 5)
font = pygame.font.SysFont('Calibri', 25, True, False)
text = font.render("Text", True, BLACK)
screen.blit(text, [250, 250])
pygame.display.flip()
Yes , if I have an error in this code also please tell me . I am open to learn new things about pygame .
clock.tick(60)
pygame.quit()
Try: pygame.transform.rotate() to rotate a pygame.Surface