Skip to content

Commit c41f75a

Browse files
authored
Merge pull request #2235 from JiffyRob/multiline_examples
Multiline examples
2 parents 2e864cd + a82b28f commit c41f75a

File tree

4 files changed

+90
-103
lines changed

4 files changed

+90
-103
lines changed

examples/dropevent.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@
1717

1818
def main():
1919
Running = True
20-
surf = pygame.display.set_mode((640, 480))
20+
screen_size = (640, 480)
21+
surf = pygame.display.set_mode(screen_size)
2122
font = pygame.font.SysFont("Arial", 24)
23+
font.align = pygame.FONT_CENTER
2224
clock = pygame.Clock()
2325

2426
spr_file_text = font.render("Feed me some file or image!", 1, (255, 255, 255))
@@ -40,12 +42,16 @@ def main():
4042
print("File drop complete!")
4143
elif ev.type == pygame.DROPTEXT:
4244
print(ev)
43-
spr_file_text = font.render(ev.text, 1, (255, 255, 255))
45+
spr_file_text = font.render(
46+
ev.text, 1, (255, 255, 255), wraplength=screen_size[0] - 10
47+
)
4448
spr_file_text_rect = spr_file_text.get_rect()
4549
spr_file_text_rect.center = surf.get_rect().center
4650
elif ev.type == pygame.DROPFILE:
4751
print(ev)
48-
spr_file_text = font.render(ev.file, 1, (255, 255, 255))
52+
spr_file_text = font.render(
53+
ev.file, 1, (255, 255, 255), None, screen_size[0] - 10
54+
)
4955
spr_file_text_rect = spr_file_text.get_rect()
5056
spr_file_text_rect.center = surf.get_rect().center
5157

examples/font_viewer.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,9 @@ def __init__(self):
4545

4646
# create a window that uses 80 percent of the screen
4747
info = pygame.display.Info()
48-
w = info.current_w
49-
h = info.current_h
50-
pygame.display.set_mode((int(w * 0.8), int(h * 0.8)))
51-
self.font_size = h // 20
48+
self.screen_size = (int(info.current_w * 0.8), int(info.current_h * 0.8))
49+
pygame.display.set_mode(self.screen_size)
50+
self.font_size = self.screen_size[1] // 16
5251

5352
self.clock = pygame.Clock()
5453
self.y_offset = 0
@@ -99,19 +98,23 @@ def render_fonts(self, text="A display of font &N"):
9998

10099
# display instructions at the top of the display
101100
font = pygame.font.SysFont(pygame.font.get_default_font(), font_size)
102-
lines = (
103-
"Use the scroll wheel or click and drag",
104-
"to scroll up and down.",
105-
"Fonts that don't use the Latin Alphabet",
106-
"might render incorrectly.",
107-
f"Here are your {len(fonts)} fonts",
108-
"",
101+
font.align = pygame.FONT_CENTER
102+
instructions = (
103+
"Use the scroll wheel or click and drag to scroll up "
104+
"and down. Fonts that don't use the Latin Alphabet "
105+
"might render incorrectly. Here are your "
106+
f"{len(fonts)} fonts"
109107
)
110-
for line in lines:
111-
surf = font.render(line, 1, instruction_color, self.back_color)
112-
font_surfaces.append((surf, total_height))
113-
total_height += surf.get_height()
114-
max_width = max(max_width, surf.get_width())
108+
surf = font.render(
109+
instructions,
110+
True,
111+
instruction_color,
112+
self.back_color,
113+
self.screen_size[0] - 20,
114+
)
115+
font_surfaces.append((surf, total_height))
116+
total_height += surf.get_height()
117+
max_width = max(max_width, surf.get_width())
115118

116119
# render all the fonts and store them with the total height
117120
for name in sorted(fonts):
@@ -121,7 +124,9 @@ def render_fonts(self, text="A display of font &N"):
121124
continue
122125
line = text.replace("&N", name)
123126
try:
124-
surf = font.render(line, 1, color, self.back_color)
127+
surf = font.render(
128+
line, 1, color, self.back_color, self.screen_size[0] - 20
129+
)
125130
except pygame.error as e:
126131
print(e)
127132
break
@@ -155,7 +160,7 @@ def display_fonts(self):
155160
bottom >= self.y_offset
156161
and top <= self.y_offset + display.get_height()
157162
):
158-
x = center - surface.get_width() // 2
163+
x = center - surface.get_width() / 2
159164
display.blit(surface, (x, top - self.y_offset))
160165
# get input and update the screen
161166
if not self.handle_events():

examples/joystick.py

Lines changed: 32 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3,41 +3,22 @@
33
pygame.init()
44

55

6-
# This is a simple class that will help us print to the screen.
7-
# It has nothing to do with the joysticks, just outputting the
8-
# information.
9-
class TextPrint:
10-
def __init__(self):
11-
self.reset()
12-
self.font = pygame.Font(None, 25)
13-
14-
def tprint(self, screen, text):
15-
text_bitmap = self.font.render(text, True, (0, 0, 0))
16-
screen.blit(text_bitmap, (self.x, self.y))
17-
self.y += self.line_height
18-
19-
def reset(self):
20-
self.x = 10
21-
self.y = 10
22-
self.line_height = 15
23-
24-
def indent(self):
25-
self.x += 10
26-
27-
def unindent(self):
28-
self.x -= 10
6+
def indent(text, indentation_level=0):
7+
return (" " * indentation_level) + text
298

309

3110
def main():
32-
# Set the width and height of the screen (width, height), and name the window.
33-
screen = pygame.display.set_mode((500, 700))
11+
# Set the size of the screen (width, height), and name the window.
12+
size = (500, 700)
13+
screen = pygame.display.set_mode(size)
3414
pygame.display.set_caption("Joystick example")
3515

3616
# Used to manage how fast the screen updates.
3717
clock = pygame.Clock()
3818

3919
# Get ready to print.
40-
text_print = TextPrint()
20+
font = pygame.font.SysFont(None, 25)
21+
wraplength = size[0] - 20
4122

4223
# This dict can be left as-is, since pygame-ce will generate a
4324
# pygame.JOYDEVICEADDED event for every joystick connected
@@ -79,63 +60,66 @@ def main():
7960
# First, clear the screen to white. Don't put other drawing commands
8061
# above this, or they will be erased with this command.
8162
screen.fill((255, 255, 255))
82-
text_print.reset()
63+
indentation = 0
64+
lines = []
8365

8466
# Get count of joysticks.
8567
joystick_count = pygame.joystick.get_count()
86-
87-
text_print.tprint(screen, f"Number of joysticks: {joystick_count}")
88-
text_print.indent()
68+
lines.append(indent("Number of joysticks: {joystick_count}", indentation))
69+
indentation += 1
8970

9071
# For each joystick:
9172
for joystick in joysticks.values():
9273
jid = joystick.get_instance_id()
9374

94-
text_print.tprint(screen, f"Joystick {jid}")
95-
text_print.indent()
75+
lines.append(indent(f"Joystick {jid}", indentation))
76+
indentation += 1
9677

9778
# Get the name from the OS for the controller/joystick.
9879
name = joystick.get_name()
99-
text_print.tprint(screen, f"Joystick name: {name}")
80+
lines.append(indent(f"Joystick name: {name}", indentation))
10081

10182
guid = joystick.get_guid()
102-
text_print.tprint(screen, f"GUID: {guid}")
83+
lines.append(indent(f"GUID: {guid}", indentation))
10384

10485
power_level = joystick.get_power_level()
105-
text_print.tprint(screen, f"Joystick's power level: {power_level}")
86+
lines.append(indent(f"Joystick's power level: {power_level}", indentation))
10687

10788
# Usually axis run in pairs, up/down for one, and left/right for
10889
# the other. Triggers count as axes.
10990
axes = joystick.get_numaxes()
110-
text_print.tprint(screen, f"Number of axes: {axes}")
111-
text_print.indent()
91+
lines.append(indent(f"Number of axes: {axes}", indentation))
92+
indentation += 1
11293

11394
for i in range(axes):
11495
axis = joystick.get_axis(i)
115-
text_print.tprint(screen, f"Axis {i} value: {axis:>6.3f}")
116-
text_print.unindent()
96+
lines.append(indent(f"Axis {i} value: {axis:>6.3f}", indentation))
97+
indentation -= 1
11798

11899
buttons = joystick.get_numbuttons()
119-
text_print.tprint(screen, f"Number of buttons: {buttons}")
120-
text_print.indent()
100+
lines.append(indent(f"Number of buttons: {buttons}", indentation))
101+
indentation += 1
121102

122103
for i in range(buttons):
123104
button = joystick.get_button(i)
124-
text_print.tprint(screen, f"Button {i:>2} value: {button}")
125-
text_print.unindent()
105+
lines.append(indent(f"Button {i:>2} value: {button}", indentation))
106+
indentation -= 1
126107

127108
hats = joystick.get_numhats()
128-
text_print.tprint(screen, f"Number of hats: {hats}")
129-
text_print.indent()
109+
lines.append(indent(f"Number of hats: {hats}", indentation))
110+
indentation += 1
130111

131112
# Hat position. All or nothing for direction, not a float like
132113
# get_axis(). Position is a tuple of int values (x, y).
133114
for i in range(hats):
134115
hat = joystick.get_hat(i)
135-
text_print.tprint(screen, f"Hat {i} value: {str(hat)}")
136-
text_print.unindent()
116+
lines.append(indent(f"Hat {i} value: {str(hat)}", indentation))
117+
indentation -= 2
137118

138-
text_print.unindent()
119+
# draw the accumulated text
120+
screen.blit(
121+
font.render("\n".join(lines), True, "black", "white", wraplength), (10, 10)
122+
)
139123

140124
# Go ahead and update the screen with what we've drawn.
141125
pygame.display.flip()

examples/music_drop_fade.py

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,18 @@
1919
import os, sys
2020

2121
VOLUME_CHANGE_AMOUNT = 0.02 # how fast should up and down arrows change the volume?
22+
SCREEN_SIZE = (640, 480)
23+
24+
MUSIC_DONE = pygame.event.custom_type() # event to be set as mixer.music.set_endevent()
25+
main_dir = os.path.split(os.path.abspath(__file__))[0]
26+
data_dir = os.path.join(main_dir, "data")
27+
28+
starting_pos = 0 # needed to fast forward and rewind
29+
volume = 0.75
30+
music_file_list = []
31+
music_file_types = ("mp3", "ogg", "mid", "mod", "it", "xm", "wav")
32+
music_can_seek = ("mp3", "ogg", "mod", "it", "xm")
33+
screen = None
2234

2335

2436
def add_file(filename):
@@ -108,20 +120,6 @@ def play_next():
108120
starting_pos = -1
109121

110122

111-
def draw_text_line(text, y=0):
112-
"""
113-
Draws a line of text onto the display surface
114-
The text will be centered horizontally at the given y position
115-
The text's height is added to y and returned to the caller
116-
"""
117-
screen = pygame.display.get_surface()
118-
surf = font.render(text, 1, (255, 255, 255))
119-
y += surf.get_height()
120-
x = (screen.get_width() - surf.get_width()) / 2
121-
screen.blit(surf, (x, y))
122-
return y
123-
124-
125123
def change_music_position(amount):
126124
"""
127125
Changes current playback position by amount seconds.
@@ -140,20 +138,10 @@ def change_music_position(amount):
140138
print(f"jumped from {old_pos} to {starting_pos}")
141139

142140

143-
MUSIC_DONE = pygame.event.custom_type() # event to be set as mixer.music.set_endevent()
144-
main_dir = os.path.split(os.path.abspath(__file__))[0]
145-
data_dir = os.path.join(main_dir, "data")
146-
147-
starting_pos = 0 # needed to fast forward and rewind
148-
volume = 0.75
149-
music_file_list = []
150-
music_file_types = ("mp3", "ogg", "mid", "mod", "it", "xm", "wav")
151-
music_can_seek = ("mp3", "ogg", "mod", "it", "xm")
152-
153-
154141
def main():
155142
global font # this will be used by the draw_text_line function
156143
global volume, starting_pos
144+
global screen
157145
running = True
158146
paused = False
159147

@@ -163,8 +151,9 @@ def main():
163151
change_volume = 0
164152

165153
pygame.init()
166-
pygame.display.set_mode((640, 480))
154+
screen = pygame.display.set_mode(SCREEN_SIZE)
167155
font = pygame.font.SysFont("Arial", 24)
156+
font.align = pygame.FONT_CENTER
168157
clock = pygame.Clock()
169158

170159
clipped = ""
@@ -177,14 +166,17 @@ def main():
177166
play_file("house_lo.ogg") # play default music included with pygame
178167

179168
# draw instructions on screen
180-
y = draw_text_line("Drop music files or path names onto this window", 20)
181-
y = draw_text_line("Copy file names into the clipboard", y)
182-
y = draw_text_line("Or feed them from the command line", y)
183-
y = draw_text_line("If it's music it will play!", y)
184-
y = draw_text_line("SPACE to pause or UP/DOWN to change volume", y)
185-
y = draw_text_line("LEFT and RIGHT will skip around the track", y)
186-
draw_text_line("Other keys will start the next track", y)
187-
169+
text = """
170+
Drop music files or path names onto this window
171+
Copy file names into the clipboard
172+
Or feed them from the command line
173+
If it's music it will play!
174+
175+
LEFT and RIGHT will skip around the track
176+
UP and DOWN will change volume
177+
ENTER or SPACE will pause/unpause the track
178+
Other keys will start the next track"""
179+
screen.blit(font.render(text, True, "white", "black", SCREEN_SIZE[0] - 20), (10, 5))
188180
"""
189181
This is the main loop
190182
It will respond to drag and drop, clipboard changes, and key presses

0 commit comments

Comments
 (0)