Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/physics.py
diff options
context:
space:
mode:
authorBrian Jordan <brian@laptop.org>2008-07-07 16:40:44 (GMT)
committer Brian Jordan <brian@laptop.org>2008-07-07 16:40:44 (GMT)
commit9f566a7d67303242c83d3061f91f695fcee8c344 (patch)
treef411e042f34c90fdbb0e4d493729010136397629 /physics.py
parent9a93e926548be7b15704a4fad2b6c92446e2c375 (diff)
parentf1964d893bf93e5621ff3133abf863876381de5d (diff)
Merge branch 'Alex' of git://dev.laptop.org/activities/physics
Epic merge Conflicts: physics.py
Diffstat (limited to 'physics.py')
-rw-r--r--[-rwxr-xr-x]physics.py438
1 files changed, 313 insertions, 125 deletions
diff --git a/physics.py b/physics.py
index 1cff1e9..958d4c1 100755..100644
--- a/physics.py
+++ b/physics.py
@@ -1,146 +1,334 @@
-# Physics.activity
-# Go eat an apple, Newton!
-#
-# Brian Jordan
-# Modified from Alex Levenson's testbed
-# Modified from Elements demos
+#==================================================================
+# Physics.activity
+# An attempt at a Phun / Crayon Physics style physics game
+# By Alex Levenson and Brian Jordan
+#==================================================================
+import sys
+import math
import pygame
from pygame.locals import *
from pygame.color import *
-
+from sugar.activity import activity
import elements
from elements import Elements
+from elements.menu import *
+from tools import *
-def main():
- # set up pygame
- pygame.init()
- size = (1200,900) # A - Any way of getting a lower resolution? Changing size?
- #size = (1024, 768)
- screen = pygame.display.set_mode(size)
- clock = pygame.time.Clock()
-
- # set up the world
- world = elements.Elements((400,400)) # A - here?
- world.renderer.set_surface(screen)
+# =======================================Classes==================================
+# tools that can be used superlcass
+class Tool(object):
+ def __init__(self):
+ # default tool name
+ self.name = "Tool"
+ def handleEvents(self,event):
+ # default event handling
+ if event.type == MOUSEBUTTONDOWN:
+ if menu.click(event.pos): return True
+ if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
+ # bye bye! Hope you had fun!
+ sys.exit()
+ elif event.type == KEYDOWN:
+ if event.key == K_SPACE:
+ #space pauses
+ world.run_physics = not world.run_physics
+ else:
+ # let the subclasses know that no events were handled yet
+ return False
+ return True
+ def draw(self):
+ # default drawing method is don't draw anything
+ pass
+ def cancel(self):
+ # default cancel doesn't do anything
+ pass
- # set up enviornment
- world.add.ground()
- world.add.wall((100, 100), (300, 300), 5)
- body=world.add.rect((900,300),width=300,height=25)
- world.add.joint(body)
+# The circle creation tool
+class CircleTool(Tool):
+ def __init__(self):
+ self.name = "Circle"
+ self.pt1 = None
+ self.radius = None
+ def handleEvents(self,event):
+ #look for default events, and if none are handled then try the custom events
+ if not super(CircleTool,self).handleEvents(event):
+ if event.type == MOUSEBUTTONDOWN:
+ if event.button == 1:
+ self.pt1 = pygame.mouse.get_pos()
+ elif event.type == MOUSEBUTTONUP:
+ if event.button == 1:
+ if self.radius > 1: # elements doesn't like tiny shapes :(
+ world.add.ball(self.pt1,self.radius, dynamic=True, density=1.0, restitution=0.16, friction=0.5)
+ self.pt1 = None
+ self.radius = None
+ def draw(self):
+ # draw a circle from pt1 to mouse
+ if self.pt1 != None:
+ self.radius = distance(self.pt1,pygame.mouse.get_pos())
+ if self.radius > 3:
+ thick = 3
+ else:
+ thick = 0
+ pygame.draw.circle(screen, (100,180,255),self.pt1,self.radius,thick)
+ pygame.draw.line(screen,(100,180,255),self.pt1,pygame.mouse.get_pos(),1)
+ def cancel(self):
+ self.pt1 = None
+ self.radius = None
+
+# The box creation tool
+class BoxTool(Tool):
+ def __init__(self):
+ self.name = "Box"
+ self.pt1 = None
+ self.rect = None
+ def handleEvents(self,event):
+ #look for default events, and if none are handled then try the custom events
+ if not super(BoxTool,self).handleEvents(event):
+ if event.type == MOUSEBUTTONDOWN:
+ if event.button == 1:
+ self.pt1 = pygame.mouse.get_pos()
+ elif event.type == MOUSEBUTTONUP:
+ if event.button == 1 and self.pt1!=None:
+ if self.rect.width > 10 and self.rect.height > 10: # elements doesn't like small shapes :(
+ world.add.rect(self.rect.center, self.rect.width/2, self.rect.height/2, dynamic=True, density=1.0, restitution=0.16, friction=0.5)
+ self.pt1 = None
+
+ def draw(self):
+ # draw a box from pt1 to mouse
+ if self.pt1 != None:
+ width = pygame.mouse.get_pos()[0] - self.pt1[0]
+ height = pygame.mouse.get_pos()[1] - self.pt1[1]
+ self.rect = pygame.Rect(self.pt1, (width, height))
+ self.rect.normalize()
+ pygame.draw.rect(screen, (100,180,255),self.rect,3)
+ def cancel(self):
+ self.pt1 = None
+ self.rect = None
+
+# The triangle creation tool
+class TriangleTool(Tool):
+ def __init__(self):
+ self.name = "Triangle"
+ self.pt1 = None
+ self.vertices = None
+ def handleEvents(self,event):
+ #look for default events, and if none are handled then try the custom events
+ if not super(TriangleTool,self).handleEvents(event):
+ if event.type == MOUSEBUTTONDOWN:
+ if event.button == 1:
+ self.pt1 = pygame.mouse.get_pos()
+ elif event.type == MOUSEBUTTONUP:
+ if event.button == 1 and self.pt1!= None:
+ if distance(self.pt1,pygame.mouse.get_pos()) > 15: # elements doesn't like tiny shapes :(
+ world.add.convexPoly(self.vertices, dynamic=True, density=1.0, restitution=0.16, friction=0.5)
+ self.pt1 = None
+ self.vertices = None
+ def draw(self):
+ # draw a triangle from pt1 to mouse
+ if self.pt1 != None:
+ self.vertices = constructTriangleFromLine(self.pt1,pygame.mouse.get_pos())
+ pygame.draw.polygon(screen, (100,180,255),self.vertices, 3)
+ pygame.draw.line(screen,(100,180,255),self.pt1,pygame.mouse.get_pos(),1)
+
+ def cancel(self):
+ self.pt1 = None
+ self.vertices = None
- # loop control
- go = True
+# The Polygon creation tool
+class PolygonTool(Tool):
+ def __init__(self):
+ self.name = "Polygon"
+ self.vertices = None
+ def handleEvents(self,event):
+ #look for default events, and if none are handled then try the custom events
+ if not super(PolygonTool,self).handleEvents(event):
+ if event.type == MOUSEBUTTONDOWN:
+ if event.button == 1:
+ if not self.vertices:
+ self.vertices=[event.pos]
+ elif distance(event.pos,self.vertices[0]) < 15:
+ self.vertices.append(self.vertices[0]) #connect the polygon
+ world.add.complexPoly(self.vertices, dynamic=True, density=1.0, restitution=0.16, friction=0.5)
+ self.vertices = None
+ else:
+ self.vertices.append(event.pos)
+ if event.button == 3:
+ if self.vertices:
+ self.vertices.append(event.pos)
+ world.add.complexPoly(self.vertices, dynamic=True, density=1.0, restitution=0.16, friction=0.5)
+ self.vertices = None
+
+ def draw(self):
+ # draw the poly being created
+ if self.vertices:
+ for i in range(len(self.vertices)-1):
+ pygame.draw.line(screen,(100,180,255),self.vertices[i],self.vertices[i+1],3)
+ pygame.draw.line(screen,(100,180,255),self.vertices[-1],pygame.mouse.get_pos(),3)
+ pygame.draw.circle(screen,(100,180,255),self.vertices[0],15,3)
- a = 0
- jb1=jb2=jb1pos=jb2pos=None
+ def cancel(self):
+ self.vertices = None
+
+# The magic pen tool
+class MagicPenTool(Tool):
+ def __init__(self):
+ self.name = "Magic Pen"
+ self.vertices = None
+ def handleEvents(self,event):
+ #look for default events, and if none are handled then try the custom events
+ if not super(MagicPenTool,self).handleEvents(event):
+ if event.type == MOUSEBUTTONDOWN:
+ if event.button == 1:
+ if not self.vertices:
+ self.vertices=[event.pos]
+ elif distance(event.pos,self.vertices[0]) < 15:
+ self.vertices.append(self.vertices[0]) #connect the polygon
+ world.add.complexPoly(self.vertices, dynamic=True, density=1.0, restitution=0.16, friction=0.5)
+ self.vertices = None
+ else:
+ self.vertices.append(event.pos)
+ elif event.type == MOUSEBUTTONUP:
+ if event.button == 1:
+ if self.vertices:
+ world.add.complexPoly(self.vertices, dynamic=True, density=1.0, restitution=0.16, friction=0.5)
+ self.vertices = None
+ elif event.type == MOUSEMOTION:
+ if self.vertices:
+ self.vertices.append(event.pos)
+
+ def draw(self):
+ # draw the poly being created
+ if self.vertices:
+ for i in range(len(self.vertices)-1):
+ pygame.draw.line(screen,(100,180,255),self.vertices[i],self.vertices[i+1],3)
+ pygame.draw.line(screen,(100,180,255),self.vertices[-1],pygame.mouse.get_pos(),3)
+ pygame.draw.circle(screen,(100,180,255),self.vertices[0],15,3)
- # Main Loop: - processes key and mouse events, world update and draw
- while go:
- for event in pygame.event.get():
- if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
- # Quit the application -- bye bye!
- go = False
-
- elif event.type == KEYDOWN and event.key == K_SPACE:
- # Pause with SPACE
- world.run_physics = not world.run_physics
-
- # Adds Mouse-->Object joints for grabbing/throwing objects
- elif event.type == MOUSEBUTTONDOWN and event.button == 1:
- # Add Mouse-->Object Joint if at an Object
- bodylist = world.get_bodies_at_pos(event.pos, include_static=False)
- if bodylist and len(bodylist) > 0:
- world.add.mouseJoint(bodylist[0], event.pos)
- elif event.type == MOUSEBUTTONUP and event.button == 1:
- # Delete Mouse-->Object Joint
- world.add.remove_mouseJoint()
+ def cancel(self):
+ self.vertices = None
- # Uses Box2D mouse movement
+# The grab tool
+class GrabTool(Tool):
+ def __init__(self):
+ self.name = "Grab"
+ def handleEvents(self,event):
+ #look for default events, and if none are handled then try the custom events
+ if not super(GrabTool,self).handleEvents(event):
+ if event.type == MOUSEBUTTONDOWN:
+ if event.button == 1:
+ # grab the first object at the mouse pointer
+ bodylist = world.get_bodies_at_pos(event.pos, include_static=False)
+ if bodylist and len(bodylist) > 0:
+ world.add.mouseJoint(bodylist[0], event.pos)
+ elif event.type == MOUSEBUTTONUP:
+ # let it go
+ if event.button == 1:
+ world.add.remove_mouseJoint()
+ # use box2D mouse motion
elif event.type == MOUSEMOTION and event.buttons[0]:
world.mouse_move(event.pos)
- # Adds Object-->Object joints for connecting objects
- elif event.type == MOUSEBUTTONDOWN and event.button == 3:
- # Connect bodies
- jb1pos = event.pos
- jb1 = world.get_bodies_at_pos(event.pos)
- jb2 = None
- jb2pos = None
- elif event.type == MOUSEBUTTONUP and event.button == 3:
- jb2 = world.get_bodies_at_pos(event.pos)
- jb2pos = event.pos
- if jb1 and jb2 and str(jb1) != str(jb2):
- world.add.joint(jb1[0],jb2[0],jb1pos,jb2pos)
- jb1 = jb2 = jb1pos = jb2pos = None
-
- # UI design --
- # We want to allow for the creation of different shapes
- # UI mockups for these (to be followed along with in this section)
- # are available at http://wiki.laptop.org/go/Physics
- # The important ingredients here are (1) storing the X,Y mouse coordinates
- # and (2) on-line resizing or visual drawing of the shapes (via
- # any of Elements, pyBox2D (elements.world), pyGame, GTK?)
- # We are going to use pygame.draw for this, then upon release (and
- # checking for bad cases, draw the objects. Portions of these functions
- # should be added to Elements
+ def cancel(self):
+ world.add.remove_mouseJoint()
+
+# The joint tool
+class JointTool(Tool):
+ def __init__(self):
+ self.name = "Joint"
+ self.jb1 = self.jb2 = self.jb1pos = self.jb2pos = None
+ def handleEvents(self,event):
+ #look for default events, and if none are handled then try the custom events
+ if not super(JointTool,self).handleEvents(event):
+ if event.type == MOUSEBUTTONDOWN:
+ if event.button == 1:
+ # grab the first body
+ self.jb1pos = event.pos
+ self.jb1 = world.get_bodies_at_pos(event.pos)
+ self.jb2 = self.jb2pos = None
+ elif event.type == MOUSEBUTTONUP:
+ if event.button == 1:
+ # grab the second body
+ self.jb2pos = event.pos
+ self.jb2 = world.get_bodies_at_pos(event.pos)
+ # if we have two distinct bodies, add a joint!
+ if self.jb1 and self.jb2 and str(self.jb1) != str(self.jb2):
+ world.add.joint(self.jb1[0],self.jb2[0],self.jb1pos,self.jb2pos)
+ # regardless, clean everything up
+ self.jb1 = self.jb2 = self.jb1pos = self.jb2pos = None
+ def draw(self):
+ if self.jb1:
+ pygame.draw.line(screen,(100,180,255),self.jb1pos,pygame.mouse.get_pos(),3)
+
+ def cancel(self):
+ self.jb1 = self.jb2 = self.jb1pos = self.jb2pos = None
- elif event.type == KEYDOWN:
- if event.key == K_1: # Add triangle at mouse
- x,y = pygame.mouse.get_pos()
- world.add.triangle((0,0),sidelength=40)
- world.add.ball((x,y), radius=20)
- elif event.key == K_2: # Add circle at mouse
- x,y = pygame.mouse.get_pos()
- world.add.ball((100,0),radius=20)
- elif event.key == K_3:
- x,y = pygame.mouse.get_pos()
- world.add.ball((200,0),radius=20)
- elif event.key == K_4:
- x,y = pygame.mouse.get_pos()
- world.add.ball((300,0),radius=30)
- elif event.key == K_5:
- x,y = pygame.mouse.get_pos()
- world.add.ball((400,0),radius=40)
- elif event.key == K_6:
- x,y = pygame.mouse.get_pos()
- world.add.ball((500,0),radius=50)
- elif event.key == K_7:
- x,y = pygame.mouse.get_pos()
- world.add.ball((x,y),radius=60)
- elif event.key == K_8: # Add 20 high drop boxes
- x,y = pygame.mouse.get_pos()
- i = 0
- for j in range(20):
- world.add.rect((x-i,y-(j*500)),width=20,height=10,angle=a)
- elif event.key == K_9: # Add many triangles
- x, y = pygame.mouse.get_pos()
- for i in range(5):
- for j in range(5):
- world.add.triangle((x-i,y-j), sidelength=20)
- elif event.key == K_k:
- world.add.rect()
+# set up pygame
+pygame.init()
+size = (900,700)
+screen = pygame.display.set_mode(size)
+clock = pygame.time.Clock()
+font = pygame.font.Font(None, 24) # font object
- # Clear Display
- screen.fill((255,255,255))
+# setup tools
+tools = {
+ "Triangle": TriangleTool(),
+ "Box": BoxTool(),
+ "Circle": CircleTool(),
+ "Polygon": PolygonTool(),
+ "Magic Pen": MagicPenTool(),
+ "Joint": JointTool(),
+ "Grab": GrabTool()
+}
+currentTool = tools["Triangle"]
- # Update & Draw World
- world.update()
- world.draw()
+def setTool(tool,discard=None):
+ global currentTool
+ currentTool.cancel()
+ currentTool = tools[tool]
- if jb1pos:
- pygame.draw.line(screen,THECOLORS["red"],jb1pos,pygame.mouse.get_pos(),3)
+# setup the menus
+menu = MenuClass()
+menu.set_width(size[0])
+menu.addItem('Box', callback=setTool)
+menu.addItem('Circle', callback=setTool)
+menu.addItem('Triangle', callback=setTool)
+menu.addItem('Polygon', callback=setTool)
+menu.addItem('Magic Pen', callback=setTool)
+menu.addItem('Grab', callback=setTool)
+menu.addItem('Joint', callback=setTool)
+
+# set up the world
+world = elements.Elements(size)
+world.renderer.set_surface(screen)
+
+# load enviornment
+world.add.ground()
- # Flip Display
- pygame.display.flip()
-
- # Try to stay at 30 FPS
- clock.tick(30) # originally 50
- x,y = pygame.mouse.get_pos()
-
+# Main Loop:
+while True:
+ for event in pygame.event.get():
+ currentTool.handleEvents(event)
+
+ # Clear Display
+ screen.fill((255,255,255))
- # Output framerate in caption
- pygame.display.set_caption("x: %i | y: %i | elements: %i | fps: %i" % (x, y, world.element_count, int(clock.get_fps())))
-if __name__ == "__main__":
- main()
+ # Update & Draw World
+ world.update()
+ world.draw()
+
+ # draw output from tools
+ currentTool.draw()
+
+ # draw the menu
+ menu.draw(screen)
+
+ #Print all the text on the screen
+ text = font.render("Current Tool: "+currentTool.name, True, (255,255,255))
+ textpos = text.get_rect(left=700,top=7)
+ screen.blit(text,textpos)
+
+ # Flip Display
+ pygame.display.flip()
+
+ # Try to stay at 30 FPS
+ clock.tick(30) # originally 50