File: BouncingBall.py

package info (click to toggle)
wxpython4.0 4.2.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 221,752 kB
  • sloc: cpp: 962,555; python: 230,573; ansic: 170,731; makefile: 51,756; sh: 9,342; perl: 1,564; javascript: 584; php: 326; xml: 200
file content (213 lines) | stat: -rw-r--r-- 5,906 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env python

"""
A test of some simple animation

this is very old-style code: don't imitate it!

"""

import wx
import numpy as np

## import local version:
import sys

#ver = 'local'
ver = 'installed'

if ver == 'installed': ## import the installed version
    from wx.lib.floatcanvas import NavCanvas
    from wx.lib.floatcanvas import FloatCanvas
    print("using installed version:", wx.lib.floatcanvas.__version__)
elif ver == 'local':
    ## import a local version
    import sys
    sys.path.append("..")
    from floatcanvas import NavCanvas
    from floatcanvas import FloatCanvas

FC = FloatCanvas

class MovingObjectMixin: # Borrowed from MovingElements.py
    """
    Methods required for a Moving object

    """

    def GetOutlinePoints(self):
        BB = self.BoundingBox
        OutlinePoints = np.array( ( (BB[0,0], BB[0,1]),
                                    (BB[0,0], BB[1,1]),
                                    (BB[1,0], BB[1,1]),
                                    (BB[1,0], BB[0,1]),
                                 )
                               )

        return OutlinePoints


class Ball(MovingObjectMixin, FloatCanvas.Circle):
    def __init__(self, XY, Velocity, Radius=2.0, **kwargs):
        self.Velocity = np.asarray(Velocity, float).reshape((2,))
        self.Radius = Radius
        self.Moving = False
        FloatCanvas.Circle.__init__(self, XY, Diameter=Radius*2, FillColor="red", **kwargs)

class DrawFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        ## Set up the MenuBar

        MenuBar = wx.MenuBar()

        file_menu = wx.Menu()
        item = file_menu.Append(wx.ID_EXIT, "","Terminate the program")
        self.Bind(wx.EVT_MENU, self.OnQuit, item)
        MenuBar.Append(file_menu, "&File")


        self.SetMenuBar(MenuBar)

        self.CreateStatusBar()
        self.SetStatusText("")

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # Add the  buttons
        ResetButton = wx.Button(self, label="Reset")
        ResetButton.Bind(wx.EVT_BUTTON, self.OnReset)

        StartButton = wx.Button(self, label="Start")
        StartButton.Bind(wx.EVT_BUTTON, self.OnStart)

        StopButton = wx.Button(self, label="Stop")
        StopButton.Bind(wx.EVT_BUTTON, self.OnStop)

        butSizer = wx.BoxSizer(wx.HORIZONTAL)
        butSizer.Add(StartButton, 0, wx.RIGHT, 5 )
        butSizer.Add(ResetButton, 0, wx.RIGHT, 5)
        butSizer.Add(StopButton, 0, )
        # Add the Canvas
        NC = NavCanvas.NavCanvas(self, -1, (500,500),
                                      Debug = False,
                                      BackgroundColor = "BLUE")

        self.Canvas = NC.Canvas
        self.Initialize(None)

        # lay it out:
        S = wx.BoxSizer(wx.VERTICAL)
        S.Add(butSizer, 0, wx.ALIGN_CENTER | wx.ALL, 5)
        S.Add(NC, 1, wx.EXPAND)
        self.SetSizer(S)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.MoveBall, self.timer)

        self.Show(True)

    def OnQuit(self,event):
        self.timer.Stop()
        self.Close(True)

    def OnCloseWindow(self, event):
        self.Destroy()

    def Initialize(self, event=None):
        Canvas = self.Canvas

        #Add the floor
        Canvas.AddLine(( (0, 0), (100, 0) ), LineWidth=4, LineColor="Black")
        # add the wall:
        Canvas.AddRectangle( (0,0), (10,50), FillColor='green')

        # add the ball:
        self.Ball = Ball( (5, 52), (2, 0), InForeground=True )
        Canvas.AddObject( self.Ball )
        # to capture the mouse to move the ball
        self.Ball.Bind(FC.EVT_FC_LEFT_DOWN, self.BallHit)
        Canvas.Bind(FC.EVT_MOTION, self.OnMove )
        Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp )

        wx.CallAfter(Canvas.ZoomToBB)

    def BallHit(self, object):
        print("the ball was clicked")
        self.Ball.Moving = True

    def OnMove(self, event):
        """
        Updates the status bar with the world coordinates
        and moves the object it is clicked on

        """
        self.SetStatusText("%.4f, %.4f"%tuple(event.Coords))
        if self.Ball.Moving:
            self.Ball.SetPoint(event.Coords)
            self.Canvas.Draw(True)

    def OnLeftUp(self, event):
        self.Ball.Moving = False

    def OnReset(self, event=None):
        self.Ball.SetPoint( (5, 52) )
        self.Ball.Velocity = np.array((1.5, 0.0))
        self.Canvas.Draw(True)

    def OnStart(self, event=None):
        self.timer.Start(20)

    def OnStop(self, event=None):
        self.timer.Stop()

    def MoveBall(self, event=None):
        ball = self.Ball

        dt = .1
        g = 9.806
        m = 1
        A = np.pi*(ball.Radius/100)**2 # radius in cm
        Cd = 0.47
        rho = 1.3

        if not ball.Moving: # don't do this if the user is moving it
            vel = ball.Velocity
            pos = ball.XY

            # apply drag
            vel -= np.sign(vel) * ((0.5 * Cd * rho * A * vel**2) / m * dt)
            # apply gravity
            vel[1] -= g * dt
            # move the ball
            pos += dt * vel
            # check if it's on the wall
            if pos[1] <= 52. and pos[0] <= 10.:
                #reverse velocity
                vel[1] *= -1.0
                pos[1] = 52.
            # check if it's hit the floor
            elif pos[1] <= ball.Radius:
                #reverse velocity
                vel[1] *= -1.0
                pos[1] = ball.Radius

            self.Ball.SetPoint( pos )
            self.Canvas.Draw(True)
            wx.GetApp().Yield(onlyIfNeeded=True)

class DemoApp(wx.App):
    def OnInit(self):
        frame = DrawFrame(None, -1, "Simple Drawing Window",wx.DefaultPosition, (700,700) )

        self.SetTopWindow(frame)

        return True

if __name__ == "__main__":

    app = DemoApp(0)
    app.MainLoop()