Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e31fb40

Browse files
authored
Merge pull request #8685 from tacaswell/doc_pong_update
DOC: moderize pong demo
2 parents 2228b5e + add5a58 commit e31fb40

File tree

3 files changed

+107
-69
lines changed

3 files changed

+107
-69
lines changed

examples/event_handling/pipong.py

Lines changed: 53 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import numpy as np
1414
import matplotlib.pyplot as plt
1515
from numpy.random import randn, randint
16+
from matplotlib.font_manager import FontProperties
1617

1718
instructions = """
1819
Player A: Player B:
@@ -85,14 +86,11 @@ def update(self, pads):
8586
self.vy *= 1.2 * pad.signy
8687
fudge = .001
8788
# probably cleaner with something like...
88-
#if not self.field.contains(self.x, self.y):
8989
if self.x < fudge:
90-
#print("player A loses")
9190
pads[1].score += 1
9291
self._reset(pads[0])
9392
return True
9493
if self.x > 7 - fudge:
95-
#print("player B loses")
9694
pads[0].score += 1
9795
self._reset(pads[1])
9896
return True
@@ -127,20 +125,42 @@ class Game(object):
127125
def __init__(self, ax):
128126
# create the initial line
129127
self.ax = ax
130-
padAx = padBx = .50
128+
ax.set_ylim([-1, 1])
129+
ax.set_xlim([0, 7])
130+
padAx = 0
131+
padBx = .50
131132
padAy = padBy = .30
132133
padBx += 6.3
133-
pA, = self.ax.barh(padAy, .2, height=.3, color='k', alpha=.5, edgecolor='b', lw=2, label="Player B", animated=True)
134-
pB, = self.ax.barh(padBy, .2, height=.3, left=padBx, color='k', alpha=.5, edgecolor='r', lw=2, label="Player A", animated=True)
134+
135+
# pads
136+
pA, = self.ax.barh(padAy, .2,
137+
height=.3, color='k', alpha=.5, edgecolor='b',
138+
lw=2, label="Player B",
139+
animated=True)
140+
pB, = self.ax.barh(padBy, .2,
141+
height=.3, left=padBx, color='k', alpha=.5,
142+
edgecolor='r', lw=2, label="Player A",
143+
animated=True)
135144

136145
# distractors
137146
self.x = np.arange(0, 2.22*np.pi, 0.01)
138-
self.line, = self.ax.plot(self.x, np.sin(self.x), "r", animated=True, lw=4)
139-
self.line2, = self.ax.plot(self.x, np.cos(self.x), "g", animated=True, lw=4)
140-
self.line3, = self.ax.plot(self.x, np.cos(self.x), "g", animated=True, lw=4)
141-
self.line4, = self.ax.plot(self.x, np.cos(self.x), "r", animated=True, lw=4)
142-
self.centerline, = self.ax.plot([3.5, 3.5], [1, -1], 'k', alpha=.5, animated=True, lw=8)
143-
self.puckdisp = self.ax.scatter([1], [1], label='_nolegend_', s=200, c='g', alpha=.9, animated=True)
147+
self.line, = self.ax.plot(self.x, np.sin(self.x), "r",
148+
animated=True, lw=4)
149+
self.line2, = self.ax.plot(self.x, np.cos(self.x), "g",
150+
animated=True, lw=4)
151+
self.line3, = self.ax.plot(self.x, np.cos(self.x), "g",
152+
animated=True, lw=4)
153+
self.line4, = self.ax.plot(self.x, np.cos(self.x), "r",
154+
animated=True, lw=4)
155+
156+
# center line
157+
self.centerline, = self.ax.plot([3.5, 3.5], [1, -1], 'k',
158+
alpha=.5, animated=True, lw=8)
159+
160+
# puck (s)
161+
self.puckdisp = self.ax.scatter([1], [1], label='_nolegend_',
162+
s=200, c='g',
163+
alpha=.9, animated=True)
144164

145165
self.canvas = self.ax.figure.canvas
146166
self.background = None
@@ -151,15 +171,16 @@ def __init__(self, ax):
151171
self.inst = True # show instructions from the beginning
152172
self.background = None
153173
self.pads = []
154-
self.pads.append(Pad(pA, 0, padAy))
174+
self.pads.append(Pad(pA, padAx, padAy))
155175
self.pads.append(Pad(pB, padBx, padBy, 'r'))
156176
self.pucks = []
157177
self.i = self.ax.annotate(instructions, (.5, 0.5),
158178
name='monospace',
159179
verticalalignment='center',
160180
horizontalalignment='center',
161181
multialignment='left',
162-
textcoords='axes fraction', animated=True)
182+
textcoords='axes fraction',
183+
animated=False)
163184
self.canvas.mpl_connect('key_press_event', self.key_press)
164185

165186
def draw(self, evt):
@@ -181,10 +202,6 @@ def draw(self, evt):
181202
draw_artist(self.line3)
182203
draw_artist(self.line4)
183204

184-
# show the instructions - this is very slow
185-
if self.inst:
186-
self.ax.draw_artist(self.i)
187-
188205
# pucks and pads
189206
if self.on:
190207
self.ax.draw_artist(self.centerline)
@@ -196,23 +213,24 @@ def draw(self, evt):
196213
for puck in self.pucks:
197214
if puck.update(self.pads):
198215
# we only get here if someone scored
199-
self.pads[0].disp.set_label(" " + str(self.pads[0].score))
200-
self.pads[1].disp.set_label(" " + str(self.pads[1].score))
201-
self.ax.legend(loc='center')
202-
self.leg = self.ax.get_legend()
203-
#self.leg.draw_frame(False) #don't draw the legend border
204-
self.leg.get_frame().set_alpha(.2)
205-
plt.setp(self.leg.get_texts(), fontweight='bold', fontsize='xx-large')
206-
self.leg.get_frame().set_facecolor('0.2')
216+
self.pads[0].disp.set_label(
217+
" " + str(self.pads[0].score))
218+
self.pads[1].disp.set_label(
219+
" " + str(self.pads[1].score))
220+
self.ax.legend(loc='center', framealpha=.2,
221+
facecolor='0.5',
222+
prop=FontProperties(size='xx-large',
223+
weight='bold'))
224+
207225
self.background = None
208-
self.ax.figure.canvas.draw()
226+
self.ax.figure.canvas.draw_idle()
209227
return True
210-
puck.disp.set_offsets([puck.x, puck.y])
228+
puck.disp.set_offsets([[puck.x, puck.y]])
211229
self.ax.draw_artist(puck.disp)
212230

213231
# just redraw the axes rectangle
214232
self.canvas.blit(self.ax.bbox)
215-
233+
self.canvas.flush_events()
216234
if self.cnt == 50000:
217235
# just so we don't get carried away
218236
print("...and you've been playing for too long!!!")
@@ -246,7 +264,9 @@ def key_press(self, event):
246264
self.pads[1].y = -1
247265

248266
if event.key == 'a':
249-
self.pucks.append(Puck(self.puckdisp, self.pads[randint(2)], self.ax.bbox))
267+
self.pucks.append(Puck(self.puckdisp,
268+
self.pads[randint(2)],
269+
self.ax.bbox))
250270
if event.key == 'A' and len(self.pucks):
251271
self.pucks.pop()
252272
if event.key == ' ' and len(self.pucks):
@@ -262,10 +282,11 @@ def key_press(self, event):
262282
self.distract = not self.distract
263283

264284
if event.key == 'g':
265-
#self.ax.clear()
266285
self.on = not self.on
267286
if event.key == 't':
268287
self.inst = not self.inst
269-
self.i.set_visible(self.i.get_visible())
288+
self.i.set_visible(not self.i.get_visible())
289+
self.background = None
290+
self.canvas.draw_idle()
270291
if event.key == 'q':
271292
plt.close()

examples/event_handling/pong_gtk_sgskip.py

Lines changed: 0 additions & 37 deletions
This file was deleted.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
====
3+
Pong
4+
====
5+
6+
A small game demo using Matplotlib.
7+
8+
.. only:: builder_html
9+
10+
This example requires :download:`pipong.py <pipong.py>`
11+
12+
"""
13+
from __future__ import print_function, division
14+
import time
15+
16+
17+
import matplotlib.pyplot as plt
18+
import pipong
19+
20+
21+
fig, ax = plt.subplots()
22+
canvas = ax.figure.canvas
23+
animation = pipong.Game(ax)
24+
25+
# disable the default key bindings
26+
if fig.canvas.manager.key_press_handler_id is not None:
27+
canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)
28+
29+
30+
# reset the blitting background on redraw
31+
def handle_redraw(event):
32+
animation.background = None
33+
34+
35+
# bootstrap after the first draw
36+
def start_anim(event):
37+
canvas.mpl_disconnect(start_anim.cid)
38+
39+
def local_draw():
40+
if animation.ax._cachedRenderer:
41+
animation.draw(None)
42+
start_anim.timer.add_callback(local_draw)
43+
start_anim.timer.start()
44+
canvas.mpl_connect('draw_event', handle_redraw)
45+
46+
47+
start_anim.cid = canvas.mpl_connect('draw_event', start_anim)
48+
start_anim.timer = animation.canvas.new_timer()
49+
start_anim.timer.interval = 1
50+
51+
tstart = time.time()
52+
53+
plt.show()
54+
print('FPS: %f' % (animation.cnt/(time.time() - tstart)))

0 commit comments

Comments
 (0)