How to clear up all the text on my display - python

I’m the first time to ask on stack overflow! I’m a 12-year-old boy who living in Hong Kong, so if my English was wrong, please tell me and please don’t keep in mind. Apart from that, I’m a newer of Python. I don’t know that the meaning of the code. Can everyone making a # to tell me the meaning? Thank you!!
I am doing a project that use Python. Also, for the display, I use Pygame too. But there have some problem with the displays.
Here is my testing code:
# install pygame
import pygame
from pygame import *
pygame.init()
# play music
mixer.init()
mixer.music.load("game_music.mp3")
mixer.music.play()
# colour
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
grass_green = (112, 173, 71)
white = (255, 255, 255)
black = (0, 0, 0)
# screen settings
window = pygame.display.set_mode((640, 600))
window.fill(grass_green)
pygame.display.set_caption("What's Your Number?")
# fonts settings
default_font = pygame.font.get_default_font()
font_a = pygame.font.Font(default_font, 57)
font_b = pygame.font.Font(default_font, 30)
font_c = pygame.font.Font(default_font, 18)
# text
title = font_a.render("What's Your Number?", 1, white)
enter_to_start = font_b.render("Press the Enter to start", 1, white)
random_mode = font_a.render("Random Mode", 1, black)
your_mode = font_a.render("Your Mode", 1, black)
des_random_1 = font_c.render("The PC choose a random number for you to", 1, black)
des_random_2 = font_c.render("guess! Can you guess it correct?", 1, black)
des_your = font_c.render("Pick a number and let you friends to guess!", 1, black)
random_control = font_b.render("Press the up arrow", 1, black)
your_control = font_b.render("Press the down arrow", 1, black)
# image
up_arrow = pygame.image.load("up_arrow_new.png")
down_arrow = pygame.image.load("down_arrow_new.png")
def blit_img(img, x, y):
window.blit(img, (x, y))
# game
game = False
temp = True
while not game:
if temp:
window.blit(title, (10, 150))
window.blit(enter_to_start, (160, 350))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER:
temp = False
window.fill(grass_green)
pygame.draw.rect(window, red, [50, 50, 540, 225])
pygame.draw.rect(window, blue, [50, 325, 540, 225])
window.blit(random_mode, (55, 65))
window.blit(des_random_1, (55, 150))
window.blit(des_random_2, (55, 200))
window.blit(random_control, (55, 240))
blit_img(up_arrow, 450, 150)
window.blit(your_mode, (55, 335))
window.blit(des_your, (55, 425))
window.blit(your_control, (55, 515))
blit_img(down_arrow, 450, 425)
pygame.display.flip()
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
if temp == False:
temp = True
window.fill(grass_green)
pygame.display.flip()
if event.key == pygame.K_ESCAPE:
game = True
if event.type == pygame.QUIT:
game = True
I want to make it just like a book or a PowerPoint to have pages. In this code, my problem is that the text which displayed cannot erase and blit the new text on it. Can someone help me? Thank you very much!!

I'd fill the window every frame and then render and blit the current text. The texts can be stored in a list and the current text can be accessed with an index variable that you increment in the event loop.
import pygame
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
window = pygame.display.set_mode((640, 600))
clock = pygame.time.Clock() # A clock to limit the frame rate.
font = pygame.font.Font(None, 57) # Use the default font.
texts = ['Hello', "what's", 'up?']
text_index = 0
done = False
while not done:
# Handle events.
for event in pygame.event.get():
# Allow the user to quit by clicking on the 'X' button.
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_KP_ENTER, pygame.K_RETURN):
# Make sure that we don't get an IndexError.
if text_index < len(texts)-1:
# Increment the index.
text_index += 1
# Insert additional game logic here.
# Finally draw everything.
window.fill(white) # Use fill to clear the window.
what_I_say = font.render(texts[text_index], True, black)
window.blit(what_I_say, (10, 150))
pygame.display.flip()
clock.tick(30) # Limit the frame rate to 30 FPS.
If you really only need to update the window when the user wants to switch to the next page (an event occurs), you could also use pygame.event.wait instead of pygame.event.get.

The way to remove previous stuff in pygame is to draw the background and everything you want to keep over it. In this case, you want to remove the Hello, so you will have to stop pygame from drawing it, and then draw the background over it
It should look like this:
import pygame
pygame.init()
#colour settings
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
#making a screen(display)
window = pygame.display.set_mode((640, 600))
window.fill(green)
# fonts settings
default_font = pygame.font.get_default_font()
font = pygame.font.Font(default_font, 57)
temp = True
#the things I want to display
while True:
if temp:
what_I_say = font.render("Hello", 1, white)
window.blit(what_I_say, (10, 150))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
temp = False
window.fill(green)
pygame.draw.rect(window, red, [50, 50, 540, 500])
The boolean temp marks whether to draw Hello. On pressing return (my keyboard doesn't have keypad enter), temp is set to false (so it will stop drawing Hello), the window is refilled with green (to cover the previous hello), and then a red rectangle is drawn.

Related

Questions regarding the pygame.mask function

So I read the documentation of pygame but I could not understand it clearly. I recently asked a question about bitmap fonts and I got some code as my answer; here is the code:
import pygame
pygame.init()
win = pygame.display.set_mode((800, 600))
font = pygame.font.Font("freesansbold.ttf", 32)
i = 0
text = "hello how are you?"
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
letter = text[i]
text_1 = font.render(letter, True, (255, 255, 255))
bw, bh = font.size(letter)
glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects()
# print(glyph_rect)
if glyph_rect:
gh = glyph_rect[0].height
print(f'letter {letter} bitmap height: {bh} glyph height: {gh}')
win.fill((0, 0, 0))
win.blit(text_1, (0, 0))
pygame.display.update()
i += 1
run = i < len(text)
pygame.quit()
So, my questions are on the line glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects().
What does the pygame.mask.from_surface() function do?
What does the line glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects() do?
What arguments does the variable glyph_rect return, and what is the meaning of those arguments?
pygame.mask.from_surface creates a pygame.mask.Mask object form a pygame.Surface.
A Surface is bitmap. A Mask is an 2 dimensional array with Boolean values. The Mask created is the size of the _Surface. A field is True if the corresponding pixel in the surface is not transparent, and False if it is transparent.
pygame.mask.Mask.get_bounding_rects creates a list of pygame.Rect objects. Each rectangle describes a bounding area of connected pixles.
If the Surface contains exactly 1 connected image, you will get exactly 1 rectangle surrounding the image.
See the example. The black rectangle is the Surface rectangle and the red rectangle is the bound rectangle of the connected component:
repl.it/#Rabbid76/ImageHitbox
import pygame
def getMaskRect(surf, top = 0, left = 0):
surf_mask = pygame.mask.from_surface(surf)
rect_list = surf_mask.get_bounding_rects()
surf_mask_rect = rect_list[0].unionall(rect_list)
surf_mask_rect.move_ip(top, left)
return surf_mask_rect
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
try:
my_image = pygame.image.load('Bomb-256.png')
except:
my_image = pygame.Surface((200, 200), pygame.SRCALPHA)
pygame.draw.circle(my_image, (0, 128, 0), (60, 60), 40)
pygame.draw.circle(my_image, (0, 0, 128), (100, 150), 40)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pos = window.get_rect().center
my_image_rect = my_image.get_rect(center = pos)
my_image_mask_rect = getMaskRect(my_image, *my_image_rect.topleft)
window.fill((255, 255, 255))
window.blit(my_image, my_image_rect)
pygame.draw.rect(window, (0, 0, 0), my_image_rect, 3)
pygame.draw.rect(window, (255, 0, 0), my_image_mask_rect, 3)
pygame.display.flip()
pygame.quit()
exit()

Clicking recs in Pygame

I am currently starting on python3 in the past few days and started in developing minor projects, but i'm having some trouble, so sorry if i cant use top notch proffessional coders language.
How can I make a pygame.draw.rect rectangle become clickable?
I know about the pygame.mouse. ones, but there might be something wrong in the code.
I want it so that when i press the red rect it will decreese i health and will add a "burn" stat (its just text for now).
Here's the code:
import pygame
import random
import sys
pygame.init()
#Screen Size
screen_width = 600
screen_height = 600
#Screen Settings
screen = pygame.display.set_mode((screen_width, screen_height))
br_color = (0, 0, 0)
pygame.display.set_caption("Type Effect Beta 0.0.1")
#Game Over Bullian
game_over = False
#Other Defenitions
clock = pygame.time.Clock()
myFont = pygame.font.SysFont("arial", 20)
#Basic Recources
health = 50
score = 0
status = "none"
#Colors for the Text
white = (255, 255, 255)
red = (255, 0, 0)
#Mouse Things
mouse_location = pygame.mouse.get_pos()
print(mouse_location)
#Status Text Helpers
burning = "Burning"
#Cards
card_size_x = 45
card_size_y = 60
fire_car_color = (255, 0 ,0)
fire_card_posx = 300
fire_card_posy = 300
card_button_fire = pygame.Rect(fire_card_posx, fire_card_posy, card_size_x, card_size_y)
#Functions
def health_decrease_burn(health, status):
health -= 1
status = "burning"
return health and status
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if pygame.mouse.get_pressed()[0] and card_button_fire.collidepoint(mouse_location):
health_decrease_burn()
if health_decrease_burn(health, status) and health <= 0:
game_over = True
text = "Score:" + str(score)
lable = myFont.render(text, 1, white)
screen.blit(lable, (10, 10))
text = "Health:" + str(health)
lable = myFont.render(text, 1, red)
screen.blit(lable, (10, 30))
text = "Status:" + str(status)
lable = myFont.render(text, 1, white)
screen.blit(lable, (10, 50))
pygame.draw.rect(screen, fire_car_color, (fire_card_posx, fire_card_posy, card_size_x, card_size_y))
clock.tick(30)
pygame.display.update()
You need to grab the mouse_location every iteration of your main loop, as the mouse position/state is constantly changing. The current code is only fetching the mouse position once, on start.
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP: # if mouse button clicked
mouse_location = pygame.mouse.get_pos() # <-- HERE
if pygame.mouse.get_pressed()[0] and card_button_fire.collidepoint(mouse_location):
health_decrease_burn()
#[...etc ]

I want to blit an image on key press in pygame

I am trying to create a Tic tac toe game in pygame. I want to display an image on screen when a key is pressed. Pressing the escape key allows me to quit game however when I press key 1 to blit the image nothing happens. Here is the code
import pygame
from pygame.locals import (
K_1,
K_2,
K_3,
K_4,
K_5,
K_6,
K_7,
K_8,
K_9,
K_ESCAPE,
K_UP,
KEYDOWN,
QUIT
)
clock = pygame.time.Clock()
pygame.init()
# Constants
display_width = 300
display_height = 300
white = (255, 255, 255)
black = (0, 0, 0)
run = True
# Creating game screen
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("Tic Tac Toe Game")
display.fill(white)
# importing images to pygame
circle_image = pygame.image.load("resizedimage1.png")
cross_image = pygame.image.load("resizedimage2.png")
# main game loop
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
elif event.key == K_1:
display.blit(cross_image, (10, 10))
clock.tick(30)
display.fill(white)
pygame.draw.line(display, black, (100, 0), (100, 300))
pygame.draw.line(display, black, (200, 0), (200, 300))
pygame.draw.line(display, black, (0, 100), (300, 100))
pygame.draw.line(display, black, (0, 200), (300, 200))
pygame.display.update()
pygame.quit()
You have to put the line
display.fill(white)
at the top of your while run. Because now you are rendering the picture and in the next frame you paint everything white. So you are not able to see the image.
You also should use the event KEYUP. Because KEYDOWN will be fired multiple times, so it will lead to flickering effects.
Of course you have to draw an blit all the objects after display.fill(), because pygame.Surface.fill fill the Surface with a solid color.
Anyway, I recommend to create a list of images for the nine fields of the game. Init the list by None:
field = [None] * 9
Set the corresponding filed in the list if a button is pressed. Note list indices start at 0:
elif event.key == K_1:
field[0] = cross_image
Draw the fields of the list in a loop. Use enumerate() to iterate through the list. The row of a field can be computed by the // (floor division) operator and the column by the % (modulo) operator (see Binary arithmetic operations):
for i, img in enumerate(field):
if img:
column = i % 3
row = i // 3
display.blit(img, (column * 100 + 10, row * 100 + 10))
Example code:
import pygame
from pygame.locals import (
K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9,
K_ESCAPE, K_UP, KEYDOWN,
QUIT
)
clock = pygame.time.Clock()
pygame.init()
# Constants
display_width = 300
display_height = 300
white = (255, 255, 255)
black = (0, 0, 0)
run = True
# Creating game screen
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("Tic Tac Toe Game")
display.fill(white)
# importing images to pygame
circle_image = pygame.image.load("resizedimage1.png")
cross_image = pygame.image.load("resizedimage2.png")
field = [None] * 9
# main game loop
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
elif event.key == K_1:
field[0] = cross_image
display.fill(white)
pygame.draw.line(display, black, (100, 0), (100, 300))
pygame.draw.line(display, black, (200, 0), (200, 300))
pygame.draw.line(display, black, (0, 100), (300, 100))
pygame.draw.line(display, black, (0, 200), (300, 200))
for i, img in enumerate(field):
if img:
column = i % 3
row = i // 3
display.blit(img, (column * 100 + 10, row * 100 + 10))
pygame.display.update()
pygame.quit()

Creating a Python 3/Pygame "Press Any Key to Continue" Start Page

I know I'm probably making a very basic mistake here, I have been learning python for about a week and change, and I am trying to create a start screen for a text adventure game that allows the user to press any key to continue to the next screen which is expressed as a function, only it is not working despite attempting many permutations.
'''
import time
import pygame
import os
from pygame.locals import
pygame.init()
pygame.display.init()
pygame.mixer.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.display.set_caption("GK-Sierra\'s Text Adventure - Comic by Tom Siddell")
screen = pygame.display.set_mode((1800, 1000))
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
FUCHSIA = (255, 0, 255)
GRAY = (128, 128, 128)
LIME = (0, 128, 0)
MAROON = (128, 0, 0)
NAVYBLUE = (0, 0, 128)
OLIVE = (128, 128, 0)
PURPLE = (128, 0, 128)
TEAL = (0, 128, 128)
def title_screen():
title_screen_display = True
while title_screen_display:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
title_screen_display = False
font = pygame.font.Font('spiritmedium.ttf', 40)
logo_image = pygame.image.load('logo.jpg')
title_screen_image = pygame.image.load('tictoc.jpg')
title_screen_image2 = pygame.image.load('firehand.jpg')
title_screen_soundtrack = 'bythewall.mp3'
screen.fill(BLACK)
screen.blit(title_screen_image, (520, 100))
screen.blit(title_screen_image2, (0, 600))
screen.blit(logo_image, (600, 0))
text = font.render('Press Any Key To Continue', True, PURPLE, BLACK)
textrect = text.get_rect()
textrect.center = (900, 950)
screen.blit(text, textrect)
pygame.display.update()
pygame.mixer.music.load(title_screen_soundtrack)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
def input_screen():
input_screen_display = True
input = ""
font = pygame.font.Font('spiritmedium.ttf', 50)
while input_screen_display:
for evt in pygame.event.get():
if evt.type == KEYDOWN:
if evt.unicode.isalpha():
input += evt.unicode
elif evt.key == K_SPACE:
input = input + " "
elif evt.key == K_BACKSPACE:
input = input[:-1]
elif evt.key == K_RETURN:
input = ""
elif evt.type == QUIT:
return
screen.fill((0, 0, 0))
block = font.render(input, True, PURPLE)
rect = block.get_rect()
rect.center = screen.get_rect().center
screen.blit(block, rect)
pygame.display.flip()
if __name__ == "__main__":
name()
pygame.quit()
time.sleep(7)
quit()
title_screen()
input_screen()
'''
I had the same issue and believe me when I say I couldn't hold a shout in... because I couldn't.
Establish a variable
window = 0
if window == 0:
(Title screen)
if window > 0:
(Rest of windows, to avoid each click setting the window value to 1)
elif event.type == pygame.KEYDOWN:
window == 1

Black screen when trying to create a menu

I have a problem. I have made a menu for a game I am making with python (it is more of a start screen). However, when I run the code, I see a windows titled appropriately, but the screen itself is black. What am I doing wrong?
#importing the libraries
import pygame
import sys
import os
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
#colour R G B
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
DARKGREEN = ( 0, 155, 0)
DARKGREY = ( 40, 40, 40)
BGCOLOR = BLACK
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.init()
#Drawing the message
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render("Press a key to play...", True, DARKGREY)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
#Showing the start screen
def showStartScreen():
titleFont = pygame.font.Font(None, 100)
titleMain = titleFont.render('Badger Defense', True, WHITE, BGCOLOR)
titleSecond = titleFont.render("Don't get your family killed!", True, GREEN)
while True:
drawPressKeyMsg()
#Main function
def main():
global DISPLAYSURF, BASICFONT
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.Font(None, 18)
pygame.display.set_caption('Badger Defense - Aplha(0.0.1)')
showStartScreen()
#Drawing the screen
DISPLAYSURF.fill(BGCOLOR)
pygame.display.update()
#Reaction to the message
def checkForKeyPress():
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
os.system('python game.py')
if __name__ == "__main__":
main()
I am using Sublime and am running Ubuntu 12.04. I have the game and all its resources in the same folder as the menu, and I have a __init__.py file there as well.
Use pygame.display.update() to update the screen.

Categories