def onClicked(event): #todo try catch when self.cPEntry has invalid values #showing my lambda skills.. cPIndices = map(lambda x: int(x), self.cPEntry.text.split(",")) for curve in self.app.selectedHuman.hairs.guides: collision(self.octree,curve,app.selectedHuman.meshData.verts,0.09,cPIndices,True) self.app.selectedHuman.hairs.reloadGuides()
def _collision_pb(self, tma, pa): xc = np.array([self.x[tma][pa], \ self.y[tma][pa], \ self.bx, \ self.by \ ]) vc = np.array([self.vx[tma][pa], \ self.vy[tma][pa], \ self.bvx, \ self.bvy \ ]) xc, vc = collision.collision(xc, vc, \ self.p.r, self.p.rb, \ self.p.m, self.p.mb, \ self.p.R) self.x[tma][pa] = xc[0] self.y[tma][pa] = xc[1] self.bx = xc[2] self.by = xc[3] self.vx[tma][pa] = vc[0] self.vy[tma][pa] = vc[1] self.bvx = vc[2] self.bvy = vc[3]
def touch_semisolid(): for i in hitboxes['semisolid'][str(world) + '-' + str(level)]: collide = collision.collision( [[xpos - 16, xpos + 16], [ypos + 20, ypos + 22]], i) if collide[0]: return collide return [False, []]
def _collision_pp(self, tma, pa, tmb, pb): xc = np.array([self.x[tma][pa], \ self.y[tma][pa], \ self.x[tmb][pb], \ self.y[tmb][pb] \ ]) vc = np.array([self.vx[tma][pa], \ self.vy[tma][pa], \ self.vx[tmb][pb], \ self.vy[tmb][pb] \ ]) xc, vc = collision.collision(xc, vc, \ self.p.r, self.p.r, \ self.p.m, self.p.m, \ self.p.R) self.x[tma][pa] = xc[0] self.y[tma][pa] = xc[1] self.x[tmb][pb] = xc[2] self.y[tmb][pb] = xc[3] self.vx[tma][pa] = vc[0] self.vy[tma][pa] = vc[1] self.vx[tmb][pb] = vc[2] self.vy[tmb][pb] = vc[3]
def rrt(start, goal, obstacles): """ start -- point (x, y) goal -- point (x, y) obstacles: pygame.Surface """ parent = { start: None } depth = { start: 0 } container = pointsContainer() container.insert(start) height = 0 nodes = 1 current = start startTime = time.perf_counter() while not inside(current, goal): if not events.rrtHandler(): # handle user events. return None if drawing.showInfo: # drawing-related. elapsed = time.perf_counter() - startTime drawing.updateInfo(elapsed, nodes, height) drawing.update() sample = randomPoint() nearest = container.NNS(sample) if (sample == nearest): # do not allow two identical points. continue if not collision(sample, nearest, obstacles): container.insert(sample) parent[sample] = nearest depth[sample] = depth[nearest] + 1 height = max(height, depth[sample]) nodes += 1 drawing.addEdge( (nearest, sample) ) current = sample if not goal in parent: parent[goal] = current depth[goal] = depth[current] + 1 height = max(height, depth[goal]) nodes += 1 drawing.addEdge( (current, goal) ) elapsed = time.perf_counter() - startTime drawing.updateInfo(elapsed, nodes, height, depth[goal]) return parent
def test_collision(): # fmt: off data = [ 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0 ] # fmt: on import collision assert_eq(0.4483, collision.collision(data).min_entropy, tolerance=0.0001)
def createPowerUP(self, powerUp, set): if powerUp.Ycor < 32: gb.display[powerUp.Ycor + 3][powerUp.Xcor] = powerUp.powerupNum gb.display[powerUp.Ycor + 1][powerUp.Xcor] = -1 print(gb.display[powerUp.Ycor][powerUp.Xcor], "pu below") if gb.display[powerUp.Ycor + 5][powerUp.Xcor] == 2019111026: collision1 = collision.collision() collision1.puwithpadle(powerUp, set) elif powerUp.Ycor < 34: gb.display[powerUp.Ycor][powerUp.Xcor] = -1 gb.display[powerUp.Ycor + 1][powerUp.Xcor] = -1
def update(self, dt, units): self.skillQ.loop(dt) self.attack.loop(dt) if self.moving == True: if not (collision.collision(self.sprite, self.angle, units)): movementX = self.movementSpeed movementY = self.movementSpeed diferenceX = self.moveX - self.sprite.x diferenceY = self.moveY - self.sprite.y if diferenceX < 0: diferenceX = diferenceX * -1 if diferenceY < 0: diferenceY = diferenceY * -1 if diferenceX > diferenceY: movementY = movementY * (diferenceY / diferenceX) elif diferenceX < diferenceY: movementX = movementX * (diferenceX / diferenceY) if self.sprite.x > self.moveX: self.sprite.x -= movementX * dt if self.sprite.x < self.moveX: self.sprite.x += movementX * dt if self.sprite.y > self.moveY: self.sprite.y -= movementY * dt if self.sprite.y < self.moveY: self.sprite.y += movementY * dt if self.sprite.y == self.moveY and self.sprite.x == self.moveX: self.moving = False else: self.moving = False
def main(): # create a GraphWin win = gr.GraphWin( "extended course", 500, 600, False) win.setBackground('alice blue') # Assign to obstacles the result of calling buildGame obstacles = buildGame(win , 0, 0, 0, 0) # start after clicking mouse win.getMouse() # Make a Ball object, draw it, and launch it into the scene ball = pho.Ball( win, 45, 3 ) ball.draw() ball.setVelocity([-3,5]) launch(ball,43, 13, 5, 15, 250) # make rotating blocks block = pho.RotatingBlock(win, 35, 40, 3, 6, coloring = 'grey' ) block1 = pho.RotatingBlock(win, 15, 20, 3, 6, coloring = 'grey' ) block.draw() block1.draw() # make paddles left_paddle = pho.RotatingBlock(win, 19, 8.5, 7,1.5, coloring = 'LemonChiffon' ) left_paddle.setAngle(300) right_paddle = pho.RotatingBlock(win, 29, 8.5, 6.8, 1.5, coloring = 'LemonChiffon' ) right_paddle.setAngle(60) paddles = [left_paddle, right_paddle] for paddle in paddles: paddle.draw() obstacles.append(paddle) dt = 0.03 # assign to frame the value 0 frame = 0 while win.checkMouse() == None: block.setRotVelocity(200) block.update(dt) obstacles.append(block) block1.setRotVelocity(200) block1.update(dt) obstacles.append(block1) collided = False for item in obstacles: # if the result of calling the collision function with the ball and the item is True if coll.collision( ball, item, dt ) == True: collided == True if collided == False: ball.update(dt) # user input to allow interaction n = win.checkKey() if n == "space": print n left_paddle.setRotVelocity(300) right_paddle.setRotVelocity(-300) if left_paddle.angle > 360: left_paddle.setAngle(360) left_paddle.setRotVelocity(-300) if left_paddle.angle < 300: left_paddle.setRotVelocity(0) left_paddle.setAngle(300) if right_paddle.angle < 0: right_paddle.setAngle(0) right_paddle.setRotVelocity(300) if right_paddle.angle > 60: right_paddle.setRotVelocity(0) right_paddle.setAngle(60) left_paddle.update(dt) right_paddle.update(dt) # check which key # m = win.getKey() # print m if frame % 10 == 0: win.update() time.sleep(0.001) frame += 1 # wait for a mouse click, then close the window win.getMouse() win.close()
def startCollision(self): ## remind id of frame handler self.__collisionID = self.game.player.setOnFrameHandler(lambda:collision.collision(self))
def main(): # variables key = '' dt = 0.02 frame = 0 gamma = 100 delta = 0.5 winWidth = 50 winHeight = 50 counter = 0 # start screen, ie state is 0 # make a window win = gr.GraphWin('Galaxy Impact', 500, 500, False) win.setBackground("black") quit = False state = 0 if state == 0: ship = pho.Ship(win, 8, 40) ship1 = pho.Ship(win, 43, 40) ship.setRotVelocity(30) ship1.setRotVelocity(30) title = gr.Text(gr.Point(250, 100), "Galaxy Impact") title.setFill('red') title.setSize(36) # instruction to start text instruction = gr.Text(gr.Point(250, 200), "click start to begin") instruction.setFill('orangered') instruction.setSize(20) begin = pho.Block(win, 25, 25, 10, 6, coloring='indianred') begins = gr.Text(gr.Point(250, 250), "start") begins.setSize(15) close = pho.Block(win, 25, 15, 10, 6, coloring='indianred') closes = gr.Text(gr.Point(250, 350), "close") closes.setSize(15) instructions = gr.Text( gr.Point(250, 420), " INSTRUCTIONS: \n space to shoot \n up to go up \ left to go left, right to go right \n down to go down" ) instructions.setFill('red') starts = [closes, instruction, title, begins, instructions] boxes = [begin, close, ship, ship1] # draw all the boxes for box in boxes: box.draw() # draw all the text for word in starts: word.draw(win) #wait for a mouse click on start to start while True: ship.update(dt) ship1.update(dt) event = win.checkMouse() if event != None and event.x < 300 and event.x > 200 and event.y > 220 and event.y < 280: state = 1 break elif event != None and event.x < 300 and event.x > 200 and event.y > 320 and event.y < 380: win.close() ### main phase ie state is 1 # make ship, draw it, ship = pho.Ship(win, 25, 5) bullet = pho.Ball(win, -10, -10) ship.setAngle(90) old_rotV = ship.getRotVelocity() gamma = 100 delta = 0.5 winWidth = 50 winHeight = 50 bullets = [] rains = [] if state == 1: # undraw all from start screen for word in starts: word.undraw() # undraw all the boxes for box in boxes: box.undraw() win.setBackground("gray6") # draw objects ship.draw() while state == 1: #scores score = gr.Text(gr.Point(450, 50), "SCORE : %d" % counter) score.setSize(18) score.setFill("white") key = win.checkKey() # raining rain = pho.Ball(win, random.randint(0, 50), random.randint(45, 50), radius=1) rain.setVelocity([random.randint(-5, 3), random.randint(-10, -5)]) # draw if frame % 50 == 0: rain.draw() rains.append(rain) # check for collisions collided = False # for item, go in zip(rains, bullets): #thought this could help double loop # if the bullet hits rain, undraw both ,and increment score for item in rains: if coll.collision(item, bullet, dt) == True: print "S" collided == True item.undraw() bullet.undraw() # counter+=1 # score.undraw() # # win.update() # score.draw(win) # if collided == False: #rain.update(dt) #bullet.update(dt) for item in bullets: if coll.collision(item, rain, dt) == True: print "m" collided == True item.undraw() rain.undraw() # counter+=1 # score.undraw() # # win.update() # score.draw(win) #if collided == False: #rain.update(dt) #bullet.update(dt) # if rain hits spaceship, then you die for item in rains: z = item.getPosition() # scores if the rain doesnt touch, and goes down, not to the side :( if z[1] < 0: counter += 1 if coll.collision(item, ship, dt) == True: collided == True # make ship red ship.vis[0].setFill("red") ship.setFlickerOn() time.sleep(0.001) state = 2 # update world ship.update(dt) for x in bullets: x.update(dt) for x in rains: x.update(dt) # user interface a = ship.getAngle() theta = a * math.pi / 180 cth = math.cos(theta) sth = math.sin(theta) p = ship.getPosition() v = ship.getVelocity() g = bullet.getPosition() # movement if key == 'Up': p[1] += 1 ship.setPosition(p) ship.setFlickerOn() if key == 'Down': p[1] -= 1 ship.setPosition(p) ship.setFlickerOn() if key == 'Left': p[0] -= 1 ship.setPosition(p) ship.setFlickerOn() if key == 'Right': p[0] += 1 ship.setPosition(p) ship.setFlickerOn() # shoot bullets if key == 'space': b = 4 bullet = pho.Ball(win, p[0], p[1], radius=0.5) # too much flick...though I could end up using it bullet.setVelocity([b * cth, b * sth]) bullet.draw() bullets.append(bullet) # end game conditions if key == "q": state = 2 # wrap the window moveit = False p = list(ship.getPosition()) if p[0] < 0: p[0] += winWidth moveit = True elif p[0] > winWidth: p[0] -= winWidth moveit = True if p[1] < 0: p[1] += winHeight moveit = True elif p[1] > winHeight: p[1] -= winHeight moveit = True if moveit: ship.setPosition(p) moveit = False # update visualization if frame % 10 == 0: win.update() time.sleep(dt * 0.5) frame += 1 # end screen ie state == 2 if state == 2: win.setBackground("red") ship.undraw() # undraw all from main screen for rain in rains: rain.undraw() # undraw all the boxes for bullet in bullets: bullet.undraw() # instruction to start text restart = gr.Text(gr.Point(250, 300), "press start to restart") restart.setFill('black') restart.setSize(20) # title of game: title = gr.Text(gr.Point(250, 100), "Galaxy Impact") title.setFill('black') title.setSize(36) # restart begin = pho.Block(win, 25, 25, 10, 6, coloring='brown4') begins = gr.Text(gr.Point(250, 250), "restart") begins.setSize(15) begins.setFill('white') begin.draw() gameover = gr.Text(gr.Point(250, 450), "GAME OVER") gameover.setStyle('bold italic') gameover.setSize(30) score = gr.Text(gr.Point(250, 350), "SCORE : %d" % counter) score.setSize(28) score.setStyle('bold') # draw everything ending = [restart, begins, title, gameover, score] for word in ending: word.draw(win) #wait for a mouse click on start to restart while True: event = win.checkMouse() key = win.checkKey() if key == 'q': win.close() if event != None and event.x < 300 and event.x > 200 and event.y > 220 and event.y < 280: state = 0 win.close() main() break # all done if quit == True: win.close()
def generateHairInterpolation2(self,guide1,guide2,humanMesh,isCollision,startIndex=9,gravity=True): if isCollision: octree = simpleoctree.SimpleOctree(humanMesh.getData().verts,0.08) hairName = "strand%s-%s"%(guide1.name,guide2.name) hSet = HairGroup(hairName) if len(guide1.controlPoints)>= len(guide2.controlPoints): longerGuide = guide1 shorterGuide = guide2 else: longerGuide = guide2 shorterGuide = guide1 nVerts = min([len(guide1.controlPoints),len(guide2.controlPoints)]) interpFactor = 0 vertsListToModify1 = [] vertsListToModify2 = [] for n in range (self.numberOfHairsMultiStrand): h = Hair() interpFactor += 1.0/self.numberOfHairsMultiStrand for i in range(len(longerGuide.controlPoints)): if random.random() < self.randomPercentage: xRand = self.sizeMultiStrand*random.random()*self.randomFactMultiStrand yRand = self.sizeMultiStrand*random.random()*self.randomFactMultiStrand zRand = self.sizeMultiStrand*random.random()*self.randomFactMultiStrand randomVect = [xRand,yRand,zRand] else: randomVect = [0,0,0] if i == 0: i2 = 0 if i == len(longerGuide.controlPoints)-1: i2 = len(shorterGuide.controlPoints)-1 else: i2 = int(round(i*len(shorterGuide.controlPoints)/len(longerGuide.controlPoints))) vert1 = longerGuide.controlPoints[i] vert2 = shorterGuide.controlPoints[i2] #Slerp dotProd = aljabr.vdot(aljabr.vnorm(vert1),aljabr.vnorm(vert2)) #Python has a very very bad numerical accuracy.. we need to do this for very small angle between guides #this occurs when we do collision detection if dotProd>1: angleBetweenGuides = 0.0 else: angleBetweenGuides = math.acos(aljabr.vdot(aljabr.vnorm(vert1),aljabr.vnorm(vert2))) denom = math.sin(angleBetweenGuides) if denom == 0.0: #controlpoints of some guides coincide vert1[0] = self.randomPercentage*self.sizeMultiStrand*random.random()*self.randomFactMultiStrand+vert1[0] vert1[1] = self.randomPercentage*self.sizeMultiStrand*random.random()*self.randomFactMultiStrand+vert1[1] vert1[2] = self.randomPercentage*self.sizeMultiStrand*random.random()*self.randomFactMultiStrand+vert1[2] vert1= aljabr.vadd(vert1,randomVect) angleBetweenGuides = math.acos(aljabr.vdot(aljabr.vnorm(vert1),aljabr.vnorm(vert2))) denom = math.sin(angleBetweenGuides) f1 = math.sin((1-interpFactor)*angleBetweenGuides)/denom f2 = math.sin(interpFactor*angleBetweenGuides)/denom newVert = aljabr.vadd(aljabr.vmul(vert1,f1),aljabr.vmul(vert2,f2)) #Uncomment the following line we use lerp instead slerp #newVert = aljabr.vadd(aljabr.vmul(vert1,(1-interpFactor)),aljabr.vmul(vert2,interpFactor)) h.controlPoints.append([newVert[0]+randomVect[0],\ newVert[1]+randomVect[1],\ newVert[2]+randomVect[2]]) if isCollision: print "h is: ", h.controlPoints for j in (0,len(h.controlPoints)): #print "h.controlPts is : ", h.controlPoints[i] #print "h.controlPts[i] length is: ", len(h.controlPoints[i]) h.controlPoints[i][2] = -h.controlPoints[i][2] #Renderman to Blender coordinates! collision(h.controlPoints,humanMesh,octree.minsize,startIndex,gravity) for j in (0,len(h.controlPoints)): h.controlPoints[i][2] = -h.controlPoints[i][2] #Blender to Renderman coordinates! hSet.hairs.append(h) self.hairStyle.append(hSet)
# %% # main loop while time <= settings.time: if time % 1000 == 0: print(time, len(q), collision_times) int_time += 1 time = round(int_time * settings.time_unit, 1) for car in q: if car.update(): q.remove(car) appear(q, time, settings) q.sort(key=sort_key) for i in range(len(q) - 1, -1, -1): if q[i].y >= settings.lane_length: # out of range: remove q.pop() elif not q[i].is_collide: if check_switch( -1, q, i): # right lane(exist) is available: switch to right lane switch_lane(-1, q[i]) elif check_pass(q, i): # right lane unavalable and need to pass: if check_switch(1, q, i): # left available: switch to left switch_lane(1, q[i]) else: # left unavailable: collide collision(q, i) collision_times += 1 print(collision_times) # %%
def main(): # ----setting up---- win = gr.GraphWin('Survival', 600, 600, False) win.setBackground("black") win.setCoords(0, 0, 600, 600) dt = 0.1 frame = 0 gamma = 2 START_PHASE = 1 PLAY_PHASE = 2 PLAY_PHASE2 = 4 STOP_PHASE = 3 missile = None phase = 1 intro(win) # Event loop while True: key = win.checkKey() if key == 'q': # get outta here altogether win.close() return if phase == START_PHASE: if key == 's': # Break down this phase and set-up next phase for item in start: item.undraw() ship = drawGame(win) asteroids = drawAsteroids(win) phase = PLAY_PHASE elif phase == PLAY_PHASE: collided = False if missile != None: if missile.getPosition( )[0] > win.getWidth() + 5 / 10: #if missile goes off screen missile = None else: missile.update(dt) for asteroid in asteroids: asteroid.update(dt) # handling collisions if col.collision(asteroid, bounds[0], dt) == True: collided = True if col.collision(asteroid, bounds[1], dt) == True: collided = True if missile != None: if col.collision(asteroid, missile, dt) == True: os.system("afplay cannon.mp3 &") missile.undraw() asteroid.undraw() global score score += 10 # increment score for each hit collided = True else: missile.undraw() collided = True # lose game if col.collision(asteroid, ship, dt) == True: collided = True phase = STOP_PHASE if collided == False: asteroid.update(dt) # relaunching asteroids into scene when they go off screen if (asteroid.getPosition()[0] < 0 or asteroid.getPosition()[0] > win.getWidth()) or ( asteroid.getPosition()[1] < 0 or asteroid.getPosition()[1] > win.getHeight()): asteroid.setPosition([60, 30]) asteroid.setVelocity([-0.1, random.randint(-2, 2)]) asteroid.setForce([-0.1, random.randint(-2, 2)]) # move ship up if key == 'Up': ship.moveShip(0, -gamma) ship.setFlickerOn() ship.update(dt) # move ship down elif key == 'Down': ship.moveShip(0, gamma) ship.setFlickerOn() ship.update(dt) # fire a missile elif key == 'space': missile = drawMissile(win, ship) ship.update(dt) if score >= 100: phase == PLAY_PHASE2 elif phase == PLAY_PHASE2: for item in play: item.undraw() for item in next: item.draw(win) for item in play: item.draw() collided = False if missile != None: if missile.getPosition( )[0] > win.getWidth() + 5 / 10: #if missile goes off screen missile = None else: missile.update(dt) for asteroid in asteroids: asteroid.update(dt) # handling collisions if col.collision(asteroid, bounds[0], dt) == True: collided = True if col.collision(asteroid, bounds[1], dt) == True: collided = True if missile != None: if col.collision(asteroid, missile, dt) == True: os.system("afplay cannon.mp3 &") missile.undraw() if asteroid.isGreen(): # if the asteroid is green asteroid.undraw() missile.undraw() global score score += 10 # increment score for each hit collided = True else: missile.undraw() collided = True # lose game if col.collision(asteroid, ship, dt) == True: collided = True phase = STOP_PHASE if collided == False: asteroid.update(dt) # relaunching asteroids into scene when they go off screen if (asteroid.getPosition()[0] < 0 or asteroid.getPosition()[0] > win.getWidth()) or ( asteroid.getPosition()[1] < 0 or asteroid.getPosition()[1] > win.getHeight()): asteroid.setPosition([60, 30]) asteroid.setVelocity([-0.1, random.randint(-2, 2)]) asteroid.setForce([-0.1, random.randint(-2, 2)]) # move ship up if key == 'Up': ship.moveShip(0, -gamma) ship.setFlickerOn() ship.update(dt) # move ship down elif key == 'Down': ship.moveShip(0, gamma) ship.setFlickerOn() ship.update(dt) # fire a missile elif key == 'space': missile = drawMissile(win, ship) ship.update(dt) # --- last phase --- elif phase == STOP_PHASE: for item in play: item.undraw() drawEndLose(win) # replay if key == 'r': for item in end: item.undraw() score = 0 phase = START_PHASE if frame % 10 == 0: win.update() frame += 1
def main(): # create a GraphWin win = gr.GraphWin("Golf", 500, 600, False) win.setBackground('alice blue') # Assign to obstacles the result of calling buildGame obstacles = buildGame(win, 0, 0, 0, 0) #make launchpad launchpad = pho.Triangle(win, 41, 11, 5, 5, coloring='orange') launchpad.draw() # Make a Ball object, draw it ball = pho.Ball(win, 43, 9.5) ball.draw() # make rotating blocks block = pho.RotatingBlock(win, 40, 45, 3, 7) block1 = pho.RotatingBlock(win, 10, 30, 3, 7) block.draw() block1.draw() # make paddles left_paddle = pho.RotatingBlock(win, 19, 8.5, 6.8, 2) left_paddle.setAngle(315) right_paddle = pho.RotatingBlock(win, 29, 8.5, 6.8, 2) right_paddle.setAngle(45) paddles = [left_paddle, right_paddle] for paddle in paddles: paddle.draw() obstacles.append(paddle) dt = 0.03 # start after clicking mouse win.getMouse() # assign to frame the value 0 frame = 0 while win.checkMouse() == None: block.setRotVelocity(200) block.update(dt) obstacles.append(block) block1.setRotVelocity(200) block1.update(dt) obstacles.append(block1) collided = False for item in obstacles: # if the result of calling the collision function with the ball and the item is True if coll.collision(ball, item, dt) == True: collided == True if collided == False: ball.update(dt) # user input to allow interaction n = win.checkKey() if n == "space": print n left_paddle.setRotVelocity(400) right_paddle.setRotVelocity(-400) if left_paddle.angle > 360: left_paddle.setAngle(360) left_paddle.setRotVelocity(-300) if left_paddle.angle < 315: left_paddle.setRotVelocity(0) left_paddle.setAngle(315) if right_paddle.angle < 0: right_paddle.setAngle(0) right_paddle.setRotVelocity(300) if right_paddle.angle > 45: right_paddle.setRotVelocity(0) right_paddle.setAngle(45) left_paddle.update(dt) right_paddle.update(dt) p = ball.getPosition() # if the ball is out of the window, user launches it if p[1] < 10 or p[1] > 60 or p[0] < 0 or p[0] > 50: if n == "0": ball.setVelocity([-3, 5]) launch(ball, 43, 13, 5, 15, 250) if n == "period": ball.setVelocity([0, 0]) ball.setPosition([43, 9]) ball.update(dt) # check which key # m = win.getKey() # print m if frame % 10 == 0: win.update() time.sleep(0.01) frame += 1 # wait for a mouse click, then close the window win.getMouse() win.close()
def bevent(evt): global tipMagnet,hairDiameterClump,hairDiameterMultiStrand global numberOfHairsClump,numberOfHairsMultiStrand,randomFactClump global randomFactMultiStrand,randomPercentage,sizeClump,sizeMultiStrand global blendDistance,sizeMultiStrand,rootCOlor,tipCOlor, humanMesh global noGuides, noCPoints, gLength, gFactor if (evt== 1): Exit() elif (evt== 2): saveRib("hair-test.rib") elif (evt== 3): hairsClass.tipMagnet = tipMagnet.val hairsClass.hairDiameterClump = hairDiameterClump.val hairsClass.hairDiameterMultiStrand = hairDiameterMultiStrand.val hairsClass.numberOfHairsClump= numberOfHairsClump.val hairsClass.numberOfHairsMultiStrand= numberOfHairsMultiStrand.val hairsClass.randomFactClump= randomFactClump.val hairsClass.randomFactMultiStrand= randomFactMultiStrand.val hairsClass.randomPercentage= randomPercentage.val hairsClass.sizeClump= sizeClump.val hairsClass.sizeMultiStrand= sizeMultiStrand.val hairsClass.blendDistance= blendDistance.val hairsClass.tipColor= tipColor.val hairsClass.rootColor= rootColor.val hairsClass.noGuides = noGuides.val hairsClass.noCPoints = noCPoints.val hairsClass.gLength = gLength.val hairsClass.gFactor = gFactor.val elif (evt== 4): Window.FileSelector (saveHairsFile, "Save hair data") elif (evt== 5): Window.FileSelector (loadHairsFile, "Load hair data") elif (evt==8): scn = Scene.GetCurrent() #get current scene mesh = humanMesh.getData() mat = humanMesh.getMatrix() verts=[] for v in mesh.verts: #reduces vertices for simplifying octree, improves performance if v.co[0]<=2 and v.co[0]>=-2 and v.co[1]<=8.6 and v.co[1]>=3.6: #2D bounding box between head and chest verts.append(local2World(v.co,mat)) #localspace to worldspace octree = simpleoctree.SimpleOctree(verts,0.09) for obj in scn.objects: if obj.type == "Curve": data = obj.getData() if data[0].isNurb(): mat = obj.getMatrix() curve=[] for p in data[0]: curve.append(local2World([p[0],p[1],p[2]],mat)) collision(curve,humanMesh,octree.minsize,9,True) #collision will after 9th controlPoint!!! N=data.getNumPoints(0) if N<len(curve): #Window.SetCursorPos(curve[len(curve)-1]) for i in range(0,len(curve)): temp = world2Local(curve[i],mat) if i < N: data.setControlPoint(0,i,[temp[0],temp[1],temp[2],1]) else: data.appendPoint(0,[temp[0],temp[1],temp[2],1]) #data[0].recalc() data.update() Blender.Redraw() elif (evt==9): #noCPoints=15 mesh = humanMesh.getData() #scalp = 269 vertices! vertIndices = mesh.getVertsFromGroup("part_head-back-skull") vertIndices.extend(mesh.getVertsFromGroup("part_head-upper-skull")) vertIndices.extend(mesh.getVertsFromGroup("part_l-head-temple")) vertIndices.extend(mesh.getVertsFromGroup("part_r-head-temple")) scalpVerts = len(vertIndices) #Collects all vertices that are part of the head where hair grows! interval = int(scalpVerts/noGuides.val) #variable used to randomly distribute scalp-vertices cPInterval = gLength.val/float(noCPoints.val) #Length between c.P. for hairs being generated #print "cPInterval is : ", cPInterval scn = Scene.GetCurrent() #get current scene for i in range(0,noGuides.val): if i==noGuides.val-1: r= random.randint(interval*i,scalpVerts-1) else: r = random.randint(interval*i,interval*(i+1)) v= mesh.verts[vertIndices[r]].co normal = mesh.verts[vertIndices[r]].no point2 = vadd(v,vmul(normal,gLength.val)) curve=[vadd(v,vmul(normal,-0.5))] w,normal2,point22,curve2 =[],[],[],[] for j in range(0,scalpVerts): w=mesh.verts[vertIndices[j]].co dist = vdist(v,w) if dist>=0.05 and dist<=0.3: normal2=mesh.verts[vertIndices[j]].no point22 = vadd(w,vmul(normal2,gLength.val)) curve2=[vadd(w,vmul(normal2,-0.5))] break curve.append(vadd(v,vmul(normal,-0.2))) curve2.append(vadd(w,vmul(normal2,-0.2))) for j in range(1,noCPoints.val-1): curve.append(vadd(v,vmul(normal,cPInterval*j))) curve2.append(vadd(w,vmul(normal2,cPInterval*j))) curve.append(point2) curve2.append(point22) drawGuidePair(scn,curve[:],curve2[:]) #r= random.randint(interval*(noGuides.val-1),scalpVerts-1) Blender.Redraw() elif (evt==10): selected = Blender.Object.GetSelected() start=1 #starting c.P. to use gravity! for obj in selected: if obj.type == "Curve": #we use virtual Young's modulus data= obj.getData() if data[0].isNurb(): mat = obj.getMatrix() curve=[] for p in data[0]: curve.append(local2World([p[0],p[1],p[2]],mat)) gravitize(curve,start,mat,gFactor.val) for i in range(start,len(curve)): temp = world2Local(curve[i],mat) data.setControlPoint(0,i,[temp[0],temp[1],temp[2],1]) data.update() Blender.Redraw() elif (evt==11): groups = Group.Get() for grp in groups: obj1, obj2 = grp.objects[0], grp.objects[1] if obj1.type == "Curve" and obj2.type == "Curve": data1, data2 = obj1.getData(), obj2.getData() if data1[0].isNurb() and data2[0].isNurb(): mat1, mat2 = obj1.getMatrix(), obj2.getMatrix() curve1,curve2=[],[] l1,l2 = list(data1[0]), list(data2[0]) for i in range(0,len(l1)): curve1.append(local2World([l1[i][0],l1[i][1],l1[i][2]],mat1)) curve2.append(local2World([l2[i][0],l2[i][1],l2[i][2]],mat2)) clamp(curve1,curve2) for i in range(0, len(curve1)): temp = world2Local(curve1[i],mat1) data1.setControlPoint(0,i,[temp[0],temp[1],temp[2],1]) temp = world2Local(curve2[i],mat2) data2.setControlPoint(0,i,[temp[0],temp[1],temp[2],1]) data1.update() data2.update() Blender.Redraw()
def main(): # create a GraphWin win = gr.GraphWin("extended course", 500, 600, False) win.setBackground('alice blue') # Assign to obstacles the result of calling buildGame obstacles = buildGame(win, 0, 0, 0, 0) # start after clicking mouse win.getMouse() # Make a Ball object, draw it, and launch it into the scene ball = pho.Ball(win, 45, 3) ball.draw() ball.setVelocity([-3, 5]) launch(ball, 43, 13, 5, 15, 250) # make rotating blocks block = pho.RotatingBlock(win, 35, 40, 3, 6, coloring='grey') block1 = pho.RotatingBlock(win, 15, 20, 3, 6, coloring='grey') block.draw() block1.draw() # make paddles left_paddle = pho.RotatingBlock(win, 19, 8.5, 7, 1.5, coloring='LemonChiffon') left_paddle.setAngle(300) right_paddle = pho.RotatingBlock(win, 29, 8.5, 6.8, 1.5, coloring='LemonChiffon') right_paddle.setAngle(60) paddles = [left_paddle, right_paddle] for paddle in paddles: paddle.draw() obstacles.append(paddle) dt = 0.03 # assign to frame the value 0 frame = 0 while win.checkMouse() == None: block.setRotVelocity(200) block.update(dt) obstacles.append(block) block1.setRotVelocity(200) block1.update(dt) obstacles.append(block1) collided = False for item in obstacles: # if the result of calling the collision function with the ball and the item is True if coll.collision(ball, item, dt) == True: collided == True if collided == False: ball.update(dt) # user input to allow interaction n = win.checkKey() if n == "space": print n left_paddle.setRotVelocity(300) right_paddle.setRotVelocity(-300) if left_paddle.angle > 360: left_paddle.setAngle(360) left_paddle.setRotVelocity(-300) if left_paddle.angle < 300: left_paddle.setRotVelocity(0) left_paddle.setAngle(300) if right_paddle.angle < 0: right_paddle.setAngle(0) right_paddle.setRotVelocity(300) if right_paddle.angle > 60: right_paddle.setRotVelocity(0) right_paddle.setAngle(60) left_paddle.update(dt) right_paddle.update(dt) # check which key # m = win.getKey() # print m if frame % 10 == 0: win.update() time.sleep(0.001) frame += 1 # wait for a mouse click, then close the window win.getMouse() win.close()
movex += -2.0 elif keystate.state('RIGHT'): movex += 2.0 if keystate.state('DOWN'): ''' nothing currently ''' #movey += 2.0 if keystate.state('UP'): if player.onGround: movey += -5.5 movey -= physics.gravity(player.y, player.dy, delta) bound = collision.calcBound(player.nextModel(movex,movey), (player.x+movex, player.y+movey), player.size) static = collision.calcBound(*som.getStaticGrid((player.x, player.y), 4, 4)) cols = collision.collision(bound, static) collision.moveable(player, cols, movex, movey, delta) # Draw stuff screen.fill((0,0,0)) som.blitBackground() som.blitGround() player.draw(screen) som.blitForeground() fpsClock.tick(60) pygame.display.flip() playerSizeX, playerSizeY = player.bbox() if player.x > SWIDTH-(playerSizeX/2): # TODO figure out this magic constant
def main(): win = gr.GraphWin('Space Game', 500, 500, False) blocks = [pho.RotatingBlock(win, 10, 20, 5, 5),pho.RotatingBlock(win, 25, 20, 5, 5),pho.RotatingBlock(win, 40, 20, 5, 5), pho.RotatingBlock(win, 25, 36, 3, 11), pho.RotatingBlock(win, 25, 36, 11, 3)] b = gr.Image(gr.Point(250,250),"background.gif") b.draw(win) start = gr.Text(gr.Point(250, 250), "Start") start.draw(win) obstacles = pho.buildGame(win, 50, 50, 50, 4) ball = pho.Ball(win, 25, 25) pho.launch(ball, 40, 10, 10, 10, 200) ball.setVelocity([0, 100]) ball.setForce([0, -50]) ball.setElasticity(0.9) ball.draw() for block in blocks: block.setRotVelocity(300) block.draw() dt = 0.01 frame = 0 win.getMouse() while win.checkMouse() == None: collided = False for item in obstacles: if col.collision(ball, item, dt) == True: collided = True ball.setFill(gr.color_rgb(random.randint(1,255),random.randint(1,255),random.randint(1,255))) for block in blocks: if col.collision(ball, block, dt) == True: collided = True ball.setFill(gr.color_rgb(random.randint(1,255),random.randint(1,255),random.randint(1,255))) if collided == False: ball.update(dt) for block in blocks: block.update(dt) block.setFill('grey') block.setOutline('grey') movingBlockDown = obstacles[-1] movingBlockUp = obstacles[-2] n = win.checkKey() if n == "Right": movingBlockDown.moveBlock(20,0) movingBlockDown.update(dt) if n == "Left": movingBlockDown.moveBlock(-20, 0) movingBlockDown.update(dt) if n == "d": movingBlockUp.moveBlock(20,0) movingBlockUp.update(dt) if n == "a": movingBlockUp.moveBlock(-20, 0) movingBlockUp.update(dt) if n == "space": pho.launch(ball, 10, 10, 20, 20, 100) if (ball.getPosition()[0] < 0 or ball.getPosition()[0] > win.getWidth()) or (ball.getPosition()[1] < 0 or ball.getPosition()[1] > win.getHeight()): ball.setPosition([25, 25]) ball.setVelocity([0, random.randint(-10, 10)]) #relaunch the ball pho.launch(ball, 10, 10, 20, 20, 100) if frame % 10 == 0: win.update() frame += 1 win.getMouse() win.close()
def touch_ceiling(): return collision.collision( [[xpos - 16, xpos + 16], [ypos - 32, ypos - 30]], hitboxes['ground'][str(world) + '-' + str(level)])
def main(): # variables key = '' dt = 0.02 frame = 0 gamma = 100 delta = 0.5 winWidth = 50 winHeight = 50 counter = 0 # start screen, ie state is 0 # make a window win = gr.GraphWin('Galaxy Impact', 500, 500, False) win.setBackground("black") quit = False state = 0 if state == 0: ship = pho.Ship(win, 8, 40) ship1 = pho.Ship(win, 43, 40) ship.setRotVelocity(30) ship1.setRotVelocity(30) title = gr.Text(gr.Point(250, 100), "Galaxy Impact") title.setFill('red') title.setSize(36) # instruction to start text instruction = gr.Text(gr.Point(250, 200), "click start to begin") instruction.setFill('orangered') instruction.setSize(20) begin = pho.Block(win, 25, 25, 10, 6, coloring = 'indianred') begins = gr.Text(gr.Point(250, 250), "start") begins.setSize(15) close = pho.Block(win, 25, 15, 10, 6, coloring = 'indianred') closes = gr.Text(gr.Point(250, 350), "close") closes.setSize(15) instructions = gr.Text(gr.Point(250, 420), " INSTRUCTIONS: \n space to shoot \n up to go up \ left to go left, right to go right \n down to go down") instructions.setFill('red') starts = [closes,instruction, title, begins, instructions ] boxes = [begin, close, ship, ship1] # draw all the boxes for box in boxes: box.draw() # draw all the text for word in starts: word.draw(win) #wait for a mouse click on start to start while True: ship.update(dt) ship1.update(dt) event = win.checkMouse() if event != None and event.x < 300 and event.x > 200 and event.y > 220 and event.y < 280: state = 1 break elif event != None and event.x < 300 and event.x > 200 and event.y > 320 and event.y < 380: win.close() ### main phase ie state is 1 # make ship, draw it, ship = pho.Ship(win, 25, 5) bullet = pho.Ball(win, -10,-10) ship.setAngle(90) old_rotV = ship.getRotVelocity() gamma = 100 delta = 0.5 winWidth = 50 winHeight = 50 bullets = [] rains = [] if state == 1: # undraw all from start screen for word in starts: word.undraw() # undraw all the boxes for box in boxes: box.undraw() win.setBackground("gray6") # draw objects ship.draw() while state == 1: #scores score = gr.Text(gr.Point(450, 50), "SCORE : %d" % counter) score.setSize(18) score.setFill("white") key = win.checkKey() # raining rain = pho.Ball(win, random.randint(0,50),random.randint(45,50),radius = 1 ) rain.setVelocity([random.randint(-5,3),random.randint(-10,-5)]) # draw if frame % 50 == 0: rain.draw() rains.append(rain) # check for collisions collided = False # for item, go in zip(rains, bullets): #thought this could help double loop # if the bullet hits rain, undraw both ,and increment score for item in rains: if coll.collision( item, bullet, dt ) == True: print "S" collided == True item.undraw() bullet.undraw() # counter+=1 # score.undraw() # # win.update() # score.draw(win) # if collided == False: #rain.update(dt) #bullet.update(dt) for item in bullets: if coll.collision( item, rain, dt ) == True: print "m" collided == True item.undraw() rain.undraw() # counter+=1 # score.undraw() # # win.update() # score.draw(win) #if collided == False: #rain.update(dt) #bullet.update(dt) # if rain hits spaceship, then you die for item in rains: z = item.getPosition() # scores if the rain doesnt touch, and goes down, not to the side :( if z[1] < 0: counter += 1 if coll.collision( item, ship, dt ) == True: collided == True # make ship red ship.vis[0].setFill("red") ship.setFlickerOn() time.sleep(0.001) state = 2 # update world ship.update(dt) for x in bullets: x.update(dt) for x in rains: x.update(dt) # user interface a = ship.getAngle() theta = a*math.pi / 180 cth = math.cos(theta) sth = math.sin(theta) p = ship.getPosition() v = ship.getVelocity() g = bullet.getPosition() # movement if key == 'Up': p[1] += 1 ship.setPosition(p) ship.setFlickerOn() if key == 'Down': p[1] -= 1 ship.setPosition(p) ship.setFlickerOn() if key == 'Left': p[0] -= 1 ship.setPosition(p) ship.setFlickerOn() if key == 'Right': p[0] += 1 ship.setPosition(p) ship.setFlickerOn() # shoot bullets if key == 'space': b = 4 bullet = pho.Ball(win, p[0],p[1], radius = 0.5) # too much flick...though I could end up using it bullet.setVelocity([b*cth, b*sth]) bullet.draw() bullets.append(bullet) # end game conditions if key == "q": state = 2 # wrap the window moveit = False p = list(ship.getPosition()) if p[0] < 0: p[0] += winWidth moveit = True elif p[0] > winWidth: p[0] -= winWidth moveit = True if p[1] < 0: p[1] += winHeight moveit = True elif p[1] > winHeight: p[1] -= winHeight moveit = True if moveit: ship.setPosition(p) moveit = False # update visualization if frame % 10 == 0: win.update() time.sleep(dt*0.5) frame += 1 # end screen ie state == 2 if state == 2: win.setBackground("red") ship.undraw() # undraw all from main screen for rain in rains: rain.undraw() # undraw all the boxes for bullet in bullets: bullet.undraw() # instruction to start text restart = gr.Text(gr.Point(250, 300), "press start to restart") restart.setFill('black') restart.setSize(20) # title of game: title = gr.Text(gr.Point(250, 100), "Galaxy Impact") title.setFill('black') title.setSize(36) # restart begin = pho.Block(win, 25, 25, 10, 6, coloring = 'brown4') begins = gr.Text(gr.Point(250, 250), "restart") begins.setSize(15) begins.setFill('white') begin.draw() gameover = gr.Text(gr.Point(250, 450), "GAME OVER") gameover.setStyle('bold italic') gameover.setSize(30) score = gr.Text(gr.Point(250, 350), "SCORE : %d" % counter) score.setSize(28) score.setStyle('bold') # draw everything ending = [restart, begins, title, gameover, score] for word in ending: word.draw(win) #wait for a mouse click on start to restart while True: event = win.checkMouse() key = win.checkKey() if key == 'q': win.close() if event != None and event.x < 300 and event.x > 200 and event.y > 220 and event.y < 280: state = 0 win.close() main() break # all done if quit == True: win.close()
def mainPhase(game): image = game.getImage() win = createGameBackground() sprite = initializeSprite(win) Pipes = createObstacle( win ) #index 0 is are the pipes (top and bottom) and index 1 is the checker pos = sprite.getPosition() mask = maskSprite(win, pos[0], pos[1], image) if game.Cheat(): for pipe in Pipes: pipe.setVelocity([-12, 0]) #Initialize and create the score text score = 0 score_text = gr.Text(gr.Point(200, 25), score) score_text.setTextColor('white') score_text.setSize(36) score_text.setStyle('bold') score_text.draw(win) win.getKey() game_finished = False while game_finished == False: key = win.checkKey() pos1 = sprite.getPosition() if game.Cheat(): Hole = getHole(sprite, Pipes[0], Pipes[1]) if Hole - pos1[1] > 2: if game.Volume(): os.system('afplay woosh.wav&') sprite.setVelocity([0, 12]) #Make the sprite go up if key == 'space': if game.Volume(): os.system('afplay woosh.wav&') sprite.setVelocity([0, 12]) #Make it so that the sprite can't drop down too fast if sprite.getVelocity() <= -20: sprite.setAcceleration([0, 0]) if sprite.getPosition()[1] < 0: game_finished = True if game.Volume(): os.system('afplay Loss.wav&') ds = sprite.update(0.1) maskMove(mask, ds[0], ds[1]) new_pipe = False for pipe in Pipes: if coll.collision(sprite, pipe, 0.05): game_finished = True if game.Volume(): os.system('afplay Loss.wav&') if Pipes[0].getPosition()[0] < 0: for pipe in Pipes: pipe.undraw() new_pipe = True else: for pipe in Pipes: pipe.update(0.05) if new_pipe: Pipes = createObstacle(win) if game.Cheat(): for pipe in Pipes: pipe.setVelocity([-12, 0]) new_pipe = False if abs(sprite.getPosition()[0] - Pipes[0].getPosition()[0] - 2.5) < 0.25: if game.Volume(): os.system('afplay ding.wav&') score += 1 score_text.setText(score) key = win.checkKey() gameOver = gr.Text(gr.Point(200, 300), 'Game Over') gameOver.setSize(36) gameOver.setStyle('bold') gameOver.draw(win) while key != 'q': key = win.checkKey() new_pipe = False for pipe in Pipes: if pipe.getPosition()[0] < 0: pipe.undraw() new_pipe = True else: pipe.update(0.05) if new_pipe: Pipes = createObstacle(win) new_pipe = False if sprite.getPosition() > -10: ds = sprite.update(0.1) maskMove(mask, ds[0], ds[1]) if game.Volume(): os.system('afplay click.wav&') win.close() if game.Volume(): os.system('killall afplay') return score
def main(): score = 0 balls = 3 win = gr.GraphWin( 'Pinball', 1200, 900, False ) win.setBackground("Black") obstacles = buildGame(win) ball = Ball(win,74,8,2) ball.vis[0].setFill("White") ball.draw() P = gr.Text(gr.Point(1000,200),"P") P.setFace('arial') P.setStyle("bold") P.setSize(36) P.setTextColor("White") P.draw(win) I = gr.Text(gr.Point(1000,240),"I") I.setFace('arial') I.setStyle("bold") I.setSize(36) I.setTextColor("White") I.draw(win) N = gr.Text(gr.Point(1000,280),"N") N.setFace('arial') N.setStyle("bold") N.setSize(36) N.setTextColor("White") N.draw(win) B = gr.Text(gr.Point(1000,320),"B") B.setFace('arial') B.setStyle("bold") B.setSize(36) B.setTextColor("White") B.draw(win) A = gr.Text(gr.Point(1000,360),"A") A.setFace('arial') A.setStyle("bold") A.setSize(36) A.setTextColor("White") A.draw(win) L = gr.Text(gr.Point(1000,400),"L") L.setFace('arial') L.setStyle("bold") L.setSize(36) L.setTextColor("White") L.draw(win) L1 = gr.Text(gr.Point(1000,440),"L") L1.setFace('arial') L1.setStyle("bold") L1.setSize(36) L1.setTextColor("White") L1.draw(win) A1 = gr.Text(gr.Point(1000,875),"Click to move paddles.") A1.setFace('arial') A1.setStyle("bold") A1.setSize(20) A1.setTextColor("White") A1.draw(win) A2 = gr.Text(gr.Point(1000,100),"Created By Robert Durst") A2.setFace('arial') A2.setStyle("bold") A2.setSize(20) A2.setTextColor("White") A2.draw(win) A3 =gr.Rectangle(gr.Point(850,800),gr.Point(1150,500)) A3.setFill('goldenrod4') A3.draw(win) pinball = [P,I,N,B,A,L,L1] win.getMouse() launch(ball,74,4,5+random.random(),5,1) dt = 0.01 frame = 0 while True: for letter in pinball: color = (gr.color_rgb(255*random.random(),255*random.random(),255*random.random())) letter.setTextColor(color) collided = False for item in obstacles: if coll.collision(ball,item,dt): collided = True if collided == False: ball.update(dt) if frame % 10 == 0: win.update() frame += 1 if ball.getPosition()[1] < 0: launch(ball,74,3,5+random.random(),5,1) win.getMouse() win.getMouse() win.close()
def main(): ##### ASKS USER FOR HP VALUE ##### hp = int(input("How much HP do you want for your ship?\n")) win = gr.GraphWin( "Space Invaders", 500, 800, False) state = 0 #### LOOPING TO CHECK FOR DIFFERENT STATES #### while state != '': ##### START SCREEN ######################################################################## dt = 0.008 bgm = False drawn = False while state == 0: if drawn == False: visualship = pho.RotShip(win, 25, 50) visualship.draw() wordplace1 = gr.Point( 250, 200 ) startingwords1 = gr.Text(wordplace1, "SPACE INVADERS") startingwords1.setSize(36) startingwords1.setFace('courier') startingwords1.draw(win) wordplace2 = gr.Point( 250, 500 ) words2 = "PRESS SPACE TO PLAY" startingwords2 = gr.Text(wordplace2, words2) startingwords2.setSize(36) startingwords2.setFace('courier') startingwords2.draw(win) startingwords3 = gr.Text(gr.Point(250, 600), "Use the Left and Right Arrow keys to move" + "\n" +"and use the space bar to shoot!") startingwords3.setSize(20) startingwords3.setFace('courier') startingwords3.draw(win) drawn = True else: pass visualship.update(0.003) key = win.checkKey() if key == 'space': startingwords1.undraw() startingwords2.undraw() state = 1 elif key == 'q': state = 3 break ################################################################################## ################################################################################## ##### MAIN PHASE ################################################################# if state == 1: ###### REGULATES BGM WHEN STATE GOES BACK TO MAIN PHASE if bgm == False: os.system("afplay ./music/bgm.mp3 &") bgm = True else: pass #### ALL OBJECTS SET HERE (EXCEPT FOR ENEMIES) ceiling = pho.Floor(win, 0, 80, 50, 15, 'yellow') ship = pho.Ship(win, 5, 5, 2, 2, healthcounter = hp) ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, 'yellow') enemyball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 3, 3, 'red') #### MOVING BACKGROUND background = pho.Floor(win, 0, 25, 50, 120, 'black') stars = [] starmaking = True while starmaking: star = pho.Ball( win, random.randrange(0, 50, 2), random.randrange(0, 1000, 2), 0.1, 0.1, 'white') star.setVelocity( [0, -100] ) stars.append( star ) if len(stars) == 500: starmaking = False #### DRAWING THE OBJECTS HERE background.draw() for starmade in stars: starmade.draw() ceiling.draw() ship.draw() ##### SET ALL NECESSARY VARIABLES HERE ##### ######################################################################## ###### int variables###### frame = 0 time1 = 0. time2 = 0. time3 = 0. time4 = 0. invincibletimer = 0 bigshottimer = 0 score = 0 LEVEL = 1 #### list variables ### colors = ['white','salmon2','orange','pink','green','yellow','red'] enemies = [] ballList = [] enemyballList = [] newballs = [] newenemyballs = [] hit1enemies = [] hit2enemies = [] deadenemies = [] ### booleans #### newtime = True invincible = False shipflash = False spawn = True bigshots = False bossbattle = True lagcheck = True shot = False leveldrawn = False start = False minibattle = True toomany = False #### other variable health = ship.healthcounter key = '' #### DRAWING THE FIRST HEALTH AND SCORE scorefunc(win, score) healthfunc(win, health) ##### STARTING THE MAIN LOOP OF MINIBATTLE ################################### while state == 1 and minibattle == True: key = win.checkKey() #print 'minibattle' ##### ALL UPDATE FUNC #### ship.update(dt) for i in ballList: i.update(dt) for j in newenemyballs: j.update(dt) for k in enemies: k.update(dt) for l in stars: l.update(dt) ### SHIP UPGRADES ###### ##### times the duration of the invincible upgrade ##### invincible timing: basically invincibletimer gets incremented every time #### through this while loop when invincible is assigned to True ### after 200 loops, invincibletimer is set to 0 and invicinble is set to False if invincible: invincibletimer += 1 if invincibletimer > 200: invincible = False invincibletimer =0 invincibletext.setTextColor('black') #### visual effect for when ship is invincible, draws and undraws one after another #### every time through the while loop by using booleans if invincible == True: if shipflash == False: ship.undraw() shipflash = True else: ship.draw() shipflash = False ##### times the duration of the bigshots upgrade if bigshots: bigshottimer += 1 if bigshottimer > 200: bigshots = False bigshottimer =0 bigshottext.setTextColor('black') ###################################################################### ######### MOVING SHIP WITH USER INPUT # move ship with user input if key == 'Left': ship.setVelocity( [-90, 0 ] ) ship.setFlickerOn() if key == 'Right': ship.setVelocity( [90, 0 ] ) ship.setFlickerOn() # ship boundaries if ship.getPosition()[0] > 50: ship.setVelocity( [-30, 0] ) if ship.getPosition()[0] < 0: ship.setVelocity( [30, 0] ) # shoot balls from the ship WITH USER INPUT ##### REGUALTES THE NUMBER OF BALLS BEING SHOT AT A TIME ##### made a self.undrawn field in the physics_objects.py file #### and made it be assigned to True when self.undrawn() is called and vice versa #### ALSO ADDED SOUND EFFECT BY USING os package if key == 'space': if ball.undrawn == True: if bigshots == False: ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, random.choice(colors)) else: ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 5, 5, random.choice(colors)) ballList.append( ball ) ball.setVelocity( [1,60]) ball.draw() os.system("afplay " + "./music/shoot.wav" + "&") else: pass ###################################################################### # undraw the ball when it gets out of bounds if ball.getPosition()[1] > 70: ball.undraw() # ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, 'yellow') # print "undrawn!" else: newballs.append( ball ) # print ball.getPosition()[1] ########################################################################## #ENEMY SPAWNING ZONE # spawn new enemy every 1 seconds if newtime == True: time1 = time.time() else: time2 = time.time() if time2 - time1 >= 1: spawn = True newtime = True else: newtime = False ##### WROTE TO SOLVE LAGGING PROBLEM # every 39 seconds increments the time step (dt) so that it looks like it # isn't lagging if lagcheck == True: time3 = int(time.time()) else: time4 = int(time.time()) if (time4 - time3) % 40 == 39: dt += 0.01 lagcheck = True else: lagcheck = False ###################################################################### # regulating number of enemies if len(enemies) > 8: toomany = True else: toomany = False ###################################################################### # the actual spawning part if toomany == True: pass else: if spawn == True: if random.random() < 0.3: enemy = pho.Ship(win, 10, 10, 10, 10, angle = 270., dangle = 270., hit1 = False) elif random.random() < 0.2: enemy = pho.Ship(win, 1, 1, 1, 1, angle = 270., dangle = 270., hit1 = False) elif random.random() < 0.1: enemy = pho.Ship(win, 1, 1, 2, 2, angle = 270., dangle = 270., hit1 = False) # elif score % 31 == 5: # boss = pho.Ship(win, 1, 1, 12, 12, angle = 270., dangle = 270., hit1 = False, hit2 = True, healthcounter = 500) # bossbattle = True # enemies.append( boss ) # boss.draw() # boss.setPosition( [ 25, 60 ] ) # boss.setVelocity( [0, -30] ) else: enemy = pho.Ship(win, 5, 5, 5, 5, angle = 270., dangle = 270., hit1 = False) enemies.append( enemy ) enemy.draw() enemy.setPosition( [random.randrange(20, 45, 1), random.randrange(20, 55, 1 )]) enemy.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])]) spawn = False ########################################################################## ###### ENEMY MOVEMENT CONTROL AND ENEMY BALL SHOOTING for badguy in enemies: if badguy.getPosition()[0] > 50: badguy.setVelocity( [random.randrange(-60, -40, 1), random.randrange(-30, 30, 10 )] ) if badguy.getPosition()[0] < 0: badguy.setVelocity( [random.randrange(40, 60, 1), random.randrange(-30, 30, 10 )] ) if badguy.getPosition()[1] > 65: badguy.setVelocity( [random.randrange(-30, 30, 10), random.randrange(-60, -40, 1 )] ) if badguy.getPosition()[1] < 20: badguy.setVelocity( [random.randrange(-30, 30, 1), random.randrange(40, 60, 1 )] ) if random.random() < 0.05: badguy.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])] ) # ENEMY SHOOTING BALL if random.random() < 0.02: enemyball = pho.Ball(win, badguy.getPosition()[0], badguy.getPosition()[1] - 4, 2, 2, 'red') enemyballList.append( enemyball ) enemyball.setVelocity( [0,-70]) # print ship.getPosition()[0], ship.getPosition()[1] enemyball.draw() # print "hi" ################################################################################### ################################################################################# # COLLISIONS AND UNDRAWING ## ENEMY AND SHIP BALL if collision.collision( ball, badguy, dt): ball.undraw() ballList.remove(ball) ### HERE IT PUTS ENEMIES INTO LISTS ACCORDING TO HOW MANY TIMES ##### IT GOT HIT if badguy.hit1 == False: # badguy.vis[0].setFill("green") #TESTING # badguy.vis[0].setOutline("green") #TESTING badguy.hit1 = True hit1enemies.append(badguy) elif badguy.hit2 == False and badguy.hit1 == True: # badguy.vis[0].setFill("red") # badguy.vis[0].setOutline("red") badguy.hit2 = True hit2enemies.append(badguy) else: # badguy.hit1 = False # badguy.hit2 = False deadenemies.append(badguy) score += 1 if score % 11 == 10: minibattle = False scorefunc(win, score) if random.random() < 0.08: invincible = True invincibletext = gr.Text( gr.Point( 250, 400 ), "INVINCIBLE TIME!" ) invincibletext.setTextColor('white') invincibletext.setSize(36) invincibletext.draw(win) elif random.random() < 0.08: bigshots = True bigshottext = gr.Text( gr.Point( 250, 500 ), "BIGGER SHOTS!" ) bigshottext.setTextColor('white') bigshottext.setSize(36) bigshottext.draw(win) ##### CHANGES COLORS OF THE ENEMY ACCRODING TO WHICH LIST THEY ARE IN for element in hit1enemies: element.vis[0].setFill("green") element.vis[0].setOutline("green") for alien in hit2enemies: alien.vis[0].setFill("red") alien.vis[0].setOutline("red") for alien1 in deadenemies: alien1.undraw() os.system("afplay " + "./music/Invaderkilled.wav" + "&") enemies.remove(alien1) ## SHIP AND ENEMYBALL for enball in enemyballList: if collision.collision(enball, ship, dt): enball.undraw() enemyballList.remove( enball ) if invincible == False: health -= 1 else: pass healthfunc(win, health) deadenemies = [] #### undraw the ball when it gets out of bounds if enemyball.getPosition()[1] < 0: enemyball.undraw() else: newenemyballs.append( enemyball ) ##### UPDATES THE WINDOW EVERY 10 LOOPS if frame % 10 == 0: win.update() #### MAKES IT SO THAT ONLY THE BALLS THAT ARE DRAWN ARE UPDATED FOR COLLISION #### IN THE NEXT LOOP ballList = newballs enemyballList = newenemyballs # GAME OVER if health <= 0: os.system("killall afplay ./music/bgm.mp3") os.system("afplay ./music/explosion.wav &") os.system("afplay ./music/gameover.mov &") ship.undraw() state = 2 # user input to quit if key == 'q': state = 3 frame += 1 ########################################################################################## # BOSS BATTLE # BASICALLY THE SAME AS THE CODE ABOVE BUT THE SPAWNING AND THE # REQUIREMENT FOR THE BOSS TO UNDRAW IS DIFFERENT # THE BOSS USES A HP SYSTEM ########################################################################################## leveldrawn = False while state == 1 and minibattle == False: if leveldrawn == False: os.system("afplay " + "./music/levelup.mov" + "&") lv2 = gr.Text( gr.Point( 250, 100 ), "LEVEL " + str(LEVEL) + " BOSS BATTLE") lv2.setTextColor('white') lv2.setSize(36) instructions = gr.Text( gr.Point(250, 700), "Press Space to Continue") instructions.setTextColor('white') instructions.draw(win) lv2.draw(win) leveldrawn = True else: pass key = win.checkKey() if key == 'space': lv2.setTextColor('black') instructions.setTextColor('black') start = True if key == 'q': state = 3 if start == True and minibattle == False: while state == 1 and minibattle == False: key = win.checkKey() ship.update(dt) for i in ballList: i.update(dt) for j in newenemyballs: j.update(dt) for k in enemies: k.update(dt) for l in stars: l.update(dt) if invincible: invincibletimer += 1 if invincibletimer > 200: invincible = False invincibletimer =0 invincibletext.setTextColor('black') if invincible == True: if shipflash == False: ship.undraw() shipflash = True else: ship.draw() shipflash = False if bigshots: bigshottimer += 1 if bigshottimer > 200: bigshots = False bigshottimer =0 bigshottext.setTextColor('black') if bossbattle: for everyone in enemies[0:]: everyone.undraw() enemies.remove(everyone) # move ship with user input if key == 'Left': ship.setVelocity( [-90, 0 ] ) ship.setFlickerOn() if key == 'Right': ship.setVelocity( [90, 0 ] ) ship.setFlickerOn() # ship boundaries if ship.getPosition()[0] > 50: ship.setVelocity( [-30, 0] ) if ship.getPosition()[0] < 0: ship.setVelocity( [30, 0] ) # shoot balls from the ship if key == 'space': if ball.undrawn == True: if bigshots == False: ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, 'yellow') else: ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 5, 5, 'yellow') ballList.append( ball ) ball.setVelocity( [1,60]) ball.draw() os.system("afplay " + "./music/shoot.wav" + "&") else: pass # undraw the ball when it gets out of bounds if ball.getPosition()[1] > 70: ball.undraw() newballs.append( ball ) else: newballs.append( ball ) #solve lagging if lagcheck == True: time3 = int(time.time()) else: time4 = int(time.time()) if (time4 - time3) % 40 == 39: dt += 0.01 lagcheck = True else: lagcheck = False # regulating number of enemies if len(enemies) > 8: toomany = True else: toomany = False # the actual spawning part if toomany == True: pass else: if bossbattle == True: boss = pho.Ship(win, 5, 5, 10, 10, angle = 270., dangle = 270., hit1 = False, healthcounter = 50*LEVEL) enemies.append( boss ) boss.draw() boss.setPosition( [random.randrange(20, 45, 1), random.randrange(20, 55, 1 )]) boss.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])]) bosshp = gr.Text( gr.Point( 250, 100 ), "BOSS HP: " + str(boss.healthcounter)) bosshp.setSize(36) bosshp.setTextColor('white') bosshp.draw(win) bossbattle = False spawn = False #ENEMY MOVEMENT CONTROL for badguy in enemies: if badguy.getPosition()[0] > 50: badguy.setVelocity( [random.randrange(-60, -40, 1), random.randrange(-30, 30, 10 )] ) if badguy.getPosition()[0] < 0: badguy.setVelocity( [random.randrange(40, 60, 1), random.randrange(-30, 30, 10 )] ) if badguy.getPosition()[1] > 65: badguy.setVelocity( [random.randrange(-30, 30, 10), random.randrange(-60, -40, 1 )] ) if badguy.getPosition()[1] < 20: badguy.setVelocity( [random.randrange(-30, 30, 1), random.randrange(40, 60, 1 )] ) if random.random() < 0.05: badguy.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])] ) # ENEMY SHOOTING BALL if random.random() < 0.1: enemyball = pho.Ball(win, badguy.getPosition()[0], badguy.getPosition()[1] - 4, 2, 2, 'red') enemyballList.append( enemyball ) enemyball.setVelocity( [0,-70]) enemyball.draw() # COLLISIONS AND UNDRAWING ## ENEMY AND SHIP BALL if collision.collision( ball, badguy, dt): badguy.healthcounter -= 1 bosshp.setTextColor('black') bosshp = gr.Text( gr.Point( 250, 100 ), "BOSS HP: " + str(boss.healthcounter)) bosshp.setSize(36) bosshp.setTextColor('white') bosshp.draw(win) ball.undraw() ballList.remove(ball) bosscolor = random.choice(colors) boss.vis[0].setFill(bosscolor) boss.vis[0].setOutline(bosscolor) if boss.healthcounter <= 0: bosshp.setTextColor('black') deadenemies.append(badguy) score += 100 scorefunc(win, score) minibattle = True start = False bossbattle = True os.system("afplay " + "./music/BossExplode.mp3" + "&") LEVEL += 1 if random.random() < 0.08: invincible = True invincibletext = gr.Text( gr.Point( 250, 400 ), "INVINCIBLE TIME!" ) invincibletext.setTextColor('white') invincibletext.setSize(36) invincibletext.draw(win) elif random.random() < 0.08: bigshots = True bigshottext = gr.Text( gr.Point( 250, 500 ), "BIGGER SHOTS!" ) bigshottext.setTextColor('white') bigshottext.setSize(36) bigshottext.draw(win) for element in hit1enemies: element.vis[0].setFill("green") element.vis[0].setOutline("green") for alien in hit2enemies: alien.vis[0].setFill("red") alien.vis[0].setOutline("red") for alien1 in deadenemies: alien1.undraw() os.system("afplay " + "./music/Invaderkilled.wav" + "&") enemies.remove(alien1) ## SHIP AND ENEMYBALL for enball in enemyballList: if collision.collision(enball, ship, dt): enball.undraw() enemyballList.remove( enball ) if invincible == False: health -= 1 else: pass healthfunc(win, health) deadenemies = [] # undraw the ball when it gets out of bounds if enemyball.getPosition()[1] < 0: enemyball.undraw() else: newenemyballs.append( enemyball ) if frame % 10 == 0: win.update() ballList = newballs enemyballList = newenemyballs # GAME OVER if health <= 0: os.system("killall afplay ./music/bgm.mp3") os.system("afplay ./music/explosion.wav &") os.system("afplay ./music/gameover.mov &") ship.undraw() state = 2 # user input to quit if key == 'q': state = 3 frame += 1 ########################################################################################## # GAME OVER SCREEN # user can decide to replay the game or quit ########################################################################################## drawn = False while state == 2: if drawn == False: visualship = pho.RotShip(win, 25, 50) visualship.draw() wordplace3 = gr.Point( 250, 200 ) words3 = "GAME OVER" endingwords1 = gr.Text(wordplace3, words3) endingwords1.setSize(36) endingwords1.setTextColor('white') endingwords1.draw(win) wordplace4 = gr.Point( 250, 700 ) words4 = "Press S to Play Again!" endingwords2 = gr.Text(wordplace4, words4) endingwords2.setSize(36) endingwords2.setTextColor('white') endingwords2.draw(win) endingwords3 = gr.Text(gr.Point( 250, 600) , "Score: " + str(score)) endingwords3.setSize(36) endingwords3.setTextColor('white') endingwords3.draw(win) drawn = True else: pass visualship.update(dt) key = win.checkKey() if key == 's': startingwords1.undraw() startingwords2.undraw() state = 1 if key == 'q': state = 3 ########################################################################################## # STATE 3: LED TO HERE WHEN USER DECIDES TO QUIT WHEN IN ANY OF THE OTHER SCREENS # KILLS THE MUSIC ########################################################################################## if state == 3: os.system("killall afplay ./music/bgm.mp3") win.close() break
def updateBall(self, set, ball, Yspeed, Xspeed): col = True if ball.Xcor - 1 <= 0: collision1 = collision.collision() collision1.withLeft(ball.Ycor, ball.Xcor) elif ball.Xcor + Xspeed >= 122: collision1 = collision.collision() collision1.withRight(ball.Ycor, ball.Xcor) elif ball.Ycor - 1 == 0: collision1 = collision.collision() collision1.withTop(ball.Ycor, ball.Xcor) elif ball.Ycor + 1 > 35: gb.display[34] = -1 gb.lives -= 1 ball.updateYX(set.slider.Ycor - 1, set.slider.Xcor + 3) gb.Xspeed = 0 gb.Yspeed = -1 gb.motionUp = True gb.grab = True gb.thru = False gb.motionRight = True if gb.lives < 0: print("Game Over") sys.exit(0) else: if gb.motionUp and col: if gb.display[ball.Ycor - 1][ball.Xcor] != -1 and ( gb.display[ball.Ycor - 1][ball.Xcor] != 12301 or gb.display[ball.Ycor - 1][ball.Xcor] != 12302 or gb.display[ball.Ycor - 1][ball.Xcor] != 12303 or gb.display[ball.Ycor - 1][ball.Xcor] != 12304 or gb.display[ball.Ycor - 1][ball.Xcor] != 12305 or gb.display[ball.Ycor - 1][ball.Xcor] != 12306): collision1 = collision.collision() col = False collision1.withTop(ball.Ycor - 1, ball.Xcor) elif not (gb.motionUp) and col: print(ball.Xcor, ball.Ycor, "debug") if gb.display[ball.Ycor + 1][ball.Xcor] != -1 and ( gb.display[ball.Ycor + 1][ball.Xcor] != 12301 or gb.display[ball.Ycor + 1][ball.Xcor] != 12302 or gb.display[ball.Ycor + 1][ball.Xcor] != 12303 or gb.display[ball.Ycor + 1][ball.Xcor] != 12304 or gb.display[ball.Ycor + 1][ball.Xcor] != 12305 or gb.display[ball.Ycor + 1][ball.Xcor] != 12306): collision1 = collision.collision() col = False collision1.withBottom(ball.Ycor + 1, ball.Xcor) if gb.motionRight and col: if gb.display[ball.Ycor][ball.Xcor + 1] != -1 and gb.display[ ball.Ycor][ball.Xcor + 1] != 2019111026 and ( gb.display[ball.Ycor][ball.Xcor + 1] != 12301 or gb.display[ball.Ycor][ball.Xcor + 1] != 12302 or gb.display[ball.Ycor][ball.Xcor + 1] != 12303 or gb.display[ball.Ycor][ball.Xcor + 1] != 12304 or gb.display[ball.Ycor][ball.Xcor + 1] != 12305 or gb.display[ball.Ycor][ball.Xcor + 1] != 12306): collision1 = collision.collision() col = False collision1.withRight(ball.Ycor, ball.Xcor + 1) elif not (gb.motionRight) and col: if gb.display[ball.Ycor][ball.Xcor - 1] != -1 and gb.display[ ball.Ycor][ball.Xcor - 1] != 2019111026: collision1 = collision.collision() col = False collision1.withLeft(ball.Ycor, ball.Xcor - 1) if gb.motionUp and gb.motionRight and col: if gb.display[ball.Ycor - 1][ball.Xcor + 1] != -1: collision1 = collision.collision() col = False collision1.withTopRight(ball.Ycor - 1, ball.Xcor + 1) elif not (gb.motionUp) and not (gb.motionRight) and col: if gb.display[ball.Ycor + 1][ball.Xcor - 1] != -1 and gb.display[ ball.Ycor + 1][ball.Xcor - 1] != 2019111026: collision1 = collision.collision() col = False collision1.withBottomLeft(ball.Ycor + 1, ball.Xcor - 1) elif not (gb.motionRight) and gb.motionUp and col: if gb.display[ball.Ycor - 1][ball.Xcor - 1] != -1: collision1 = collision.collision() col = False collision1.withTopLeft(ball.Ycor - 1, ball.Xcor - 1) elif gb.motionRight and not (gb.motionUp) and col: if gb.display[ball.Ycor + 1][ball.Xcor + 1] != -1 and gb.display[ ball.Ycor + 1][ball.Xcor + 1] != 2019111026: collision1 = collision.collision() col = False collision1.withBottomRight(ball.Ycor + 1, ball.Xcor + 1) # if gb.display[ball.Ycor - Yspeed][ball.Xcor -Xspeed] != 123 and gb.display[ball.Ycor + Yspeed][ball.Xcor +Xspeed] != 123: # gb.display[ball.Ycor][ball.Xcor] = 8011 # else: gb.display[ball.Ycor - Yspeed][ball.Xcor - Xspeed] = -1 gb.display[ball.Ycor][ball.Xcor] = 8011
renderText=collisionText.render("Hey i am Intersected", 1,(255,255,0),(0,0,0)) otherObjectSize=otherObject.get_size() otherObject.fill((255,255,255),None, pygame.BLEND_RGBA_MAX) x,y=0,0 clock=pygame.time.Clock() directionX,directionY=1,1 def playSound(): sound.stop() sound.play() rectangle = collision(0,0,400,400)#New object square mario = collision(0,0,otherObjectSize[0],otherObjectSize[1]) #new object, the otherObject while 1: clock.tick(30) screen.fill((0,0,0)) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() captureMouse = pygame.mouse.get_pos() x = captureMouse[0] y = captureMouse[1] mario.setPosition(x,y)
def test_collisions(self): for i, entity in enumerate(self.entities): for entity2 in self.entities[i + 1:]: if pygame.sprite.collide_rect(entity, entity2): print("collision detected") collision.collision(entity, entity2)
def main(): # create a GraphWin win = gr.GraphWin( "Golf", 500, 600, False) win.setBackground('alice blue') # Assign to obstacles the result of calling buildGame obstacles = buildGame(win , 0, 0, 0, 0) #make launchpad launchpad = pho.Triangle(win, 41, 11, 5, 5, coloring = 'orange') launchpad.draw() # Make a Ball object, draw it ball = pho.Ball( win, 43, 9.5 ) ball.draw() # make rotating blocks block = pho.RotatingBlock(win, 40, 45, 3, 7 ) block1 = pho.RotatingBlock(win, 10, 30, 3, 7 ) block.draw() block1.draw() # make paddles left_paddle = pho.RotatingBlock(win, 19, 8.5, 6.8, 2 ) left_paddle.setAngle(315) right_paddle = pho.RotatingBlock(win, 29, 8.5, 6.8, 2 ) right_paddle.setAngle(45) paddles = [left_paddle, right_paddle] for paddle in paddles: paddle.draw() obstacles.append(paddle) dt = 0.03 # start after clicking mouse win.getMouse() # assign to frame the value 0 frame = 0 while win.checkMouse() == None: block.setRotVelocity(200) block.update(dt) obstacles.append(block) block1.setRotVelocity(200) block1.update(dt) obstacles.append(block1) collided = False for item in obstacles: # if the result of calling the collision function with the ball and the item is True if coll.collision( ball, item, dt ) == True: collided == True if collided == False: ball.update(dt) # user input to allow interaction n = win.checkKey() if n == "space": print n left_paddle.setRotVelocity(400) right_paddle.setRotVelocity(-400) if left_paddle.angle > 360: left_paddle.setAngle(360) left_paddle.setRotVelocity(-300) if left_paddle.angle < 315: left_paddle.setRotVelocity(0) left_paddle.setAngle(315) if right_paddle.angle < 0: right_paddle.setAngle(0) right_paddle.setRotVelocity(300) if right_paddle.angle > 45: right_paddle.setRotVelocity(0) right_paddle.setAngle(45) left_paddle.update(dt) right_paddle.update(dt) p = ball.getPosition() # if the ball is out of the window, user launches it if p[1] < 10 or p[1]>60 or p[0]<0 or p[0]>50: if n == "0": ball.setVelocity([-3,5]) launch(ball,43, 13, 5, 15, 250) if n == "period": ball.setVelocity([0,0]) ball.setPosition([43,9]) ball.update(dt) # check which key # m = win.getKey() # print m if frame % 10 == 0: win.update() time.sleep(0.01) frame += 1 # wait for a mouse click, then close the window win.getMouse() win.close()