Skip to content

Instantly share code, notes, and snippets.

@python4d
Created October 4, 2012 16:26
Show Gist options
  • Save python4d/3834753 to your computer and use it in GitHub Desktop.
Save python4d/3834753 to your computer and use it in GitHub Desktop.
Simple game code which uses Module Box2D pour Python
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
'''
Created on 22 fvr. 2012
@author: damien samain
'''
import random
import pygame
from Box2D import *
import Box2D
Box2D.b2_angularSlop
#Taille de l'écran
size=[400,800]
# Initialize the game engine
pygame.init()
screen=pygame.display.set_mode(size)
pygame.display.set_caption("Balls Test")
pygame.display.toggle_fullscreen()
#Zone de calcul de Box2D & création de l'objet world
worldAABB=b2AABB()
worldAABB.lowerBound = (-10000.0, -10000.0)
worldAABB.upperBound = ( 10000.0, 10000.0)
gravity = (0.0,-20.0)
#permet d'arrêter le calcul des coord. d'un body lorsqu'il est immobile
doSleep = True
world = b2World(worldAABB, gravity, doSleep)
#définition de body/shape (implicitement static) définissant les 'parois'
groundBodyDef = b2BodyDef()
groundShapeDef = b2PolygonDef()
#création de deux parois (horizontale penché et verticale par rapport au point body en bas à gauche = coord.(0,0)
groundBodyDef.position = (0, 0)
groundBody = world.CreateBody(groundBodyDef)
groundShapeDef.setVertices( [ (-150, 0.0), (150, 0.0), (0.0, 10) ] )
groundBody.CreateShape(groundShapeDef)
groundShapeDef.SetAsBox(1, 400)
groundBody.CreateShape(groundShapeDef)
#création d'une paroi (horizontale penché type triangle) à partir du gauche/bas de l'écran
groundBodyDef.position = (400, 0)
groundBody = world.CreateBody(groundBodyDef)
groundBody.CreateShape(groundShapeDef)
groundShapeDef.setVertices( [ (-150, 0.0), (150, 0.0), (0.0, 10) ] )
groundBody.CreateShape(groundShapeDef)
#.setVertices( [ (-1.0, 0.0), (1.0, 0.0), (0.0, 2.0) ] )
groundBodyDef.position = (210,size[1]/2-25)
groundShapeDef.setVertices( [ (-100, 0.0), (100, 0.0), (0.0, 60) ] )
groundBody = world.CreateBody(groundBodyDef)
groundBody.CreateShape(groundShapeDef)
nb_balls=10
# Création des body balls
for i in range(nb_balls):
bodyDef= b2BodyDef()
bodyDef.position = ((i+1)*400/(nb_balls+1), 800)
body= world.CreateBody(bodyDef)
shapeDef = b2CircleDef()
shapeDef.radius=10
shapeDef.density = 0.1*(1+random.random())
shapeDef.friction = 0.3
shapeDef.restitution=0.9
body.CreateShape(shapeDef)
body.SetMassFromShapes()
body.userData=[int(random.random()*255),int(random.random()*255),int(random.random()*255)]
# Gestion du temps de simulation: calcul de 60 coordonnées des body par secondes
timeStep = 1.0 / 10.0
velocityIterations = 10
positionIterations = 8
world.Step(timeStep, velocityIterations, positionIterations)
# Define the colors we will use in RGB format
black = [ 0, 0, 0]
white = [255,255,255]
blue = [ 0, 0,255]
green = [ 0,255, 0]
red = [255, 0, 0]
pi=3.141592653
#Loop until the user clicks the close button.
done=False;nbhigh=0
clock = pygame.time.Clock()
while done==False:
# This limits the while loop to a max of 10 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(100)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
if event.type == pygame.MOUSEBUTTONDOWN:
bodyDef= b2BodyDef()
x,y=pygame.mouse.get_pos()
bodyDef.position = (x,800-y)
body= world.CreateBody(bodyDef)
shapeDef = b2CircleDef()
shapeDef.radius=10
shapeDef.density = 0.1*(1+random.random())
shapeDef.friction = 0.3
shapeDef.restitution=0.9
body.CreateShape(shapeDef)
body.SetMassFromShapes()
body.userData=[int(random.random()*255),int(random.random()*255),int(random.random()*255)]
screen.fill(black)
world.Step(timeStep, velocityIterations, positionIterations)
nb=0
for balls in world:
if balls.IsDynamic() :
if int(balls.position[1])<-1000:
try:
world.DestroyBody(balls)
except:
print "ERROR destroy!!"
nb+=1
try:
pygame.draw.circle(screen, balls.userData if balls.userData<>[] else [int(random.random()*255),int(random.random()*255),int(random.random()*255)] ,[int(balls.position[0]),800-int(balls.position[1])],10,5)
except:
print "ERROR draw ball!! %s" % str(balls.userData)
if balls.IsStatic() :
for shape in balls.shapeList: # iterates over body.shapeList
try:
shape_coords=[[int(balls.position[0])+sx,800-int(balls.position[1])-sy] for sx,sy in shape.vertices]
pygame.draw.lines(screen, white, True, shape_coords, 5)
except:
print "ERROR draw lines!!"
# Select the font to use. Default font, 25 pt size.
font = pygame.font.Font(None, 25)
# Render the text. "True" means anti-aliased text.
# Black is the color. This creates an image of the
# letters, but does not put it on the screen
text = font.render("{:^10}".format(str(nb)+" Balles"),True,green)
# Put the image of the text on the screen at 250x250
screen.blit(text, [size[0]/2-2*8,size[1]/2])
if nbhigh<nb : nbhigh=nb
text = font.render(("{:^10}".format('HighScore='+str(nbhigh))),True,red)
screen.blit(text, [2,2])
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# Be IDLE friendly
pygame.quit ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment