def __init__(self): global dt windowSurface = pygame.display.set_mode( (WINDOWS_WIDTH, WINDOWS_HEIGHT)) # Hello Pong ! printTxt(windowSurface, "Hello Pong!", 0, 250) # Player One Score printTxt(windowSurface, player1Score, 120, 120, "scoreFont") # Player Two Score printTxt(windowSurface, player2Score, -120, 120, "scoreFont") if gameState == 'start': printTxt(windowSurface, "Start State", 0, 200) elif gameState == 'play': printTxt(windowSurface, "Play State", 0, 200) player1.render(windowSurface) player2.render(windowSurface) Ball.render(ball, windowSurface) pygame.display.update()
def __init__(self, frame_skip = 2): height = 400 width = 600 goal_length = 300 self.scene = Scene(width, height) self.frame_skip = frame_skip self.ball_idle = 0 self.ball_idle_limit = 3 self.action_space = ActionSpace([Action.up, Action.down, Action.nomoveshoot]) self.box = Box(0, width, 0, height, 0) self.goal1 = Goal(leftright_margin, height / 2, Way.left, goal_length) self.player1 = Player(80, height / 2, player_radius, player_mass, \ player_restitution, player_damping, player_kick_damping, player_kick_power, Side.red) self.ball = Ball(width - 100, height / 2, ball_radius, ball_mass, ball_restitution, ball_damping) self.penalty_spot = Disc(self.ball.center.x, self.ball.center.y, 4, 0, 0, 0, Color.green).make_ghost().make_hollow() # self.player_border_left = VerticalBorder(50, height / 2, height, 0, visible=True) # self.player_border_right = VerticalBorder(100, height / 2, height, 0, visible=True) self.scene.add_object(self.goal1) self.scene.add_object(self.player1) self.scene.add_object(self.ball) self.scene.add_object(self.penalty_spot) self.scene.add_object(self.box) self.reset()
def __init__(self): self.top = Tk() self.canvas = Canvas(self.top, bg="darkgreen", height=700, width=1000) self.field = Field(self.canvas, "darkgreen", 1000, 700, 50, 30, 160, 80, 150, 70, 200, 10, 150, 5) self.meshGrid = MeshGrid(self.canvas, 1000, 700, 50, 15) self.ball = Ball(self.canvas, 500, 350, 10, 4, "white", "black", 1) buttonNextFrame = Button(self.top, text="Next Frame", command=self.nextFrame) buttonNextFrame.place(x=350, y=680) buttonShowMeshgrid = Button(self.top, text="Show Grid", command=self.showMeshGrid) buttonShowMeshgrid.place(x=550, y=680) buttonShowFlowfield = Button(self.top, text="Show Flowfield", command=self.showFlowField) buttonShowFlowfield.place(x=650, y=680) buttonShowField = Button(self.top, text="Show Field", command=self.showFootballField) buttonShowField.place(x=450, y=680) self.animate() self.nextFrame() self.canvas.pack() self.top.mainloop()
def reset_setup(self): self.balls = [ Ball(win_width // 2 - 75, 50), Ball(0, self.wall[0].y + self.wall[0].y // 2 - 15), Ball(64, self.wall[1].y - 64), Ball(self.wall[1].x + 5, self.floor[6].y), Ball(win_width - 64, self.floor[5].y - 64) ] self.pistons = [ Piston(self.floor[1].x - self.floor[1].width, self.floor[1].y + self.floor[1].height + 180, 9), Piston(self.floor[1].x - self.floor[1].width + 125, self.floor[1].y + self.floor[1].height + 120, 7), Piston(self.floor[1].x - self.floor[1].width + 250, self.floor[1].y + self.floor[1].height + 60, 4), Piston(self.floor[1].x - self.floor[1].width + 375, self.floor[1].y + self.floor[1].height + 0, 1) ] self.falling_floor = [ FallingFloor(0, self.wall[0].y + 60 + 2), FallingFloor(0 + 64, self.wall[0].y + 60 + 2), FallingFloor(0, self.wall[0].y + 150 + 2), FallingFloor(0 + 64, self.wall[0].y + 150 + 2), FallingFloor(0, self.wall[0].y + 240 + 2), FallingFloor(0 + 64, self.wall[0].y + 240 + 2), FallingFloor(0 + 64 + 64, self.wall[0].y + 240 + 2), FallingFloor(0, self.wall[1].y + 5), FallingFloor(0 + 64, self.wall[1].y + 5), FallingFloor(0, self.floor[2].y + 5) ] self.bomb = Bomb(win_width + 150, win_height - 125) self.play_jump_sound = True
def __init__(self, pos): Ball.__init__(self, "ball.png", [0, 0], pos) self.upImages = [ pygame.image.load("Resources/Object/Player/PlayerBack2.png") ] self.downImages = [ pygame.image.load("Resources/Object/Player/PlayerForward.png") ] self.leftImages = [ pygame.image.load("Resources/Object/Player/PlayerLeft.png") ] self.rightImages = [ pygame.image.load("Resources/Object/Player/Player.png") ] self.facing = "up" self.changed = False self.images = self.upImages self.frame = 0 self.maxFrame = len(self.images) - 1 self.waitCount = 0 self.maxWait = 60 * .25 self.image = self.images[self.frame] self.rect = self.image.get_rect(center=self.rect.center) self.maxSpeed = 8 self.pistol = Gun("pistol") self.gun = self.pistol self.shooting = False
def __init__(self, name_image="ship-1.png"): Screen.__init__(self) self.keys = { "up": [K_UP], "down": [K_DOWN], "left": [K_LEFT], "right": [K_RIGHT], "rotate_left": [K_a, K_q], "rotate_right": [K_d], "fire": [K_SPACE], # test "lose_life": [K_l] # c'est un L } self.image = pygame.image.load('img/' + name_image).convert_alpha() self.rect = self.image.get_rect() self.rect.center = self.srect.center self.ball = Ball(default_center=self.rect.center) self.vitesse = 2 self.vitesse_rotate = 2 self.orginal = self.image.copy() self.current_angle = 0 self.cheated = 0 self.max_life = 50 self.life = self.max_life self.score = Score()
def __init__(self): self.window = Window() self.paddle = Paddle(self.window) self.bricks = Bricks(self.window) self.ball = Ball(self.window) self.running = True self.check = True
def __init__(self, bot1, bot2): fenceTop = 50 self.fence = Fence(width / 2, height - fenceTop / 2, 10, fenceTop) self.ball = Ball(PVector(width / 2, 100), 25) self.player1 = Player(PVector(width / 4, height), True, bot1) self.player2 = Player(PVector(3 * width / 4, height), False, bot2) self.justReset = False
def __init__(self): w = 500 h = 500 self.pWin = GraphWin("Pong", w, h) myIMG = Image(Point(250, 250), "linesfinished.gif") myIMG.draw(self.pWin) self.b = Ball(self.pWin) self.p = Paddle(self.pWin) self.hits = 0 self.score = 0 self.level = 1 self.scoreTitle = Text(Point(350, 25), "Score:") self.scoreTitle.setTextColor("white") self.scoreTitle.setSize(25) self.userScore = Text(Point(405, 25), self.score) self.userScore.setTextColor("white") self.userScore.setSize(25) self.levelTitle = Text(Point(100, 25), "Level:") self.levelTitle.setTextColor("white") self.levelTitle.setSize(25) self.userLevel = Text(Point(150, 25), self.level) self.userLevel.setTextColor("white") self.userLevel.setSize(25) self.scoreTitle.draw(self.pWin) self.userScore.draw(self.pWin) self.levelTitle.draw(self.pWin) self.userLevel.draw(self.pWin)
def __init__(self): # init pygame and set screen self.pygame = pygame self.pygame.init() self.pygame.display.set_caption('Ball Game') self.screenSize = self.width, self.height = 1200, 850 self.screen = pygame.Surface(self.screenSize) self.display = self.pygame.display.set_mode(self.screenSize) # Defining variables self.highScore = 0 self.level = 1 self.score = 0 self.shake = 0 self.paused = False self.startNewLevel = False # Autopilot self.auto = False # Initialize animations Ball.setFrames() BombCrate.setFrames() self.background = Background() # Initialize UI class self.ui = UI(self) # Set up game clock self.clock = pygame.time.Clock() # finish setting up game setUp(1, self)
def initializeObject(self): self.ball = Ball(constant.WIDTH // 2, constant.HEIGHT // 2, 10, 5, random.uniform(0, math.pi), self.gameDisplay) self.paddle1 = Paddle(30, 20, 150, self.gameDisplay) self.paddle2 = Paddle(constant.WIDTH - 50, 20, 150, self.gameDisplay) self.player1 = Player(self.paddle1) self.player2 = Player(self.paddle2)
def __init__(self, host = "localhost", port = 5555): self.host = host self.port = port self.connected = False Ball.setPrimary('green') self.time = None self.timeout = None
def __init__(self,x,y,vx,vy,radius=15): Circle.__init__(self) self._ball = Ball(x, y, vx, vy) self._radius = radius self.moveTo(self._ball.getPositionX(),self._ball.getPositionY()) self.setRadius(radius) self.setFillColor("green")
def initUI(self): # перемещение self.move(300, 300) # фиксируем ширину и высоту поля self.setFixedSize(Arkanoid.W, Arkanoid.H) # задаём имя программы self.setWindowTitle('Арканоид') # загружаем фоновое изображение self.background = QImage('background.jpg') # создаём кубики self.cubes = Cubes() # созаём ракетку self.racket = Racket(Arkanoid.W / 2 - Racket.W / 2) # создаём шарик self.ball = Ball(Arkanoid.W / 2, Racket.Y - Ball.R, 60) # создаём надпись self.label = Label(150, Arkanoid.H // 2, Arkanoid.W - 300, 60) # создаем очки self.scores = Scores(0, 9, Arkanoid.W, 30) # создаём таймер self.timer = QtCore.QTimer() # заканчиваем время self.timer.timeout.connect(self.tick) # задаём начало счётчика self.timer.start(2) # включаем отслеживание мыши self.setMouseTracking(1) # переходим в состояние запуска self.restart()
def getBalls(self): ##print "Asking server for data" if True: #not self.time or self.time - time.time() > self.timeout: self.time = time.time() try: Ball.clear() ##self.connection.sendall("ball") json_data = self.connection.recv(8000);#self.recv_timeout(self.connection) ##print "Server data: " + json_data if len(json_data) == 0 or json_data == "none": return False i = json_data.index(':') ##dict = {} ##dict['color'] = 'red' ##dict['y'] = 0 ##dict['x'] = json_data[i+1:] ##dict['width'] = json_data[:i] x = int(json_data[i+1:]) width = int(json_data[:i]) return (x, width) ##balls = json.loads(json_data) ##for ball in data: ## Ball.add(Ball(ball)) ## ##return Ball.exist() except: print sys.exc_info()[1] print 'hai' return False else: return Ball.exist()
def update(*args): self = args[0] width = args[1] height = args[2] Ball.update(self, width, height) self.animate() self.changed = False
def __init__(self, master): self.master = master # make it cover the entire screen self.w, self.h = root.winfo_screenwidth(), root.winfo_screenheight() master.overrideredirect(1) geometry = "%dx%d+0+0" % (self.w, self.h) master.geometry(geometry) self.canvas = Canvas(master, width=self.w, height=self.h) master.title("My first Game!") master.bind("<KeyPress>", self.onKeyDown) master.bind("<KeyRelease>", self.onKeyUp) self.canvas.pack() self.playerPaddle = PlayerPaddle(self) self.cpuPaddle = CpuPaddle(self) self.ball = Ball(self) self.playerScore = 0 self.cpuScore = 0 self.master.after(0, self.render)
def __init__(self, pos): Ball.__init__(self, "RSC/objects/images/player_balls/player_ball1up.png", [0, 0], pos) self.upImages = [ pygame.image.load( "RSC/objects/images/player_balls/player_ball2up.png") ] self.downImages = [ pygame.image.load( "RSC/objects/images/player_balls/player_ball2down.png") ] self.leftImages = [ pygame.image.load( "RSC/objects/images/player_balls/player_ball2left.png") ] self.rightImages = [ pygame.image.load( "RSC/objects/images/player_balls/player_ball2right.png") ] self.facing = "up" self.changed = False self.images = self.upImages self.frame = 0 self.maxFrame = len(self.images) - 1 self.waitCount = 0 self.maxWait = 60 * .25 self.image = self.images[self.frame] self.rect = self.image.get_rect(center=self.rect.center) self.maxSpeed = 10
def setup(self): def process_sound(recognizer, audio_data): try: result = self.recognizer.recognize_google(audio_data) except Exception: return force = 0. if result.lower().startswith('l'): force = -10000 elif result.lower().startswith('r'): force = 10000 self.ball.push((force, 0), result) self.stop_listening = self.recognizer.listen_in_background( self.microphone, process_sound, phrase_time_limit=1., ) self.space = pymunk.Space() self.space.gravity = 0.0, -900.0 self.bottom_line = Line(100, 100, 400, 100, self.space) self.left_line = Line(100, 100, 100, 200, self.space) self.right_line = Line(400, 100, 400, 200, self.space) self.ball = Ball(200, 200, 10, self.space)
def __init__(self, maxSpeed, pos = [0,0]): Ball.__init__(self, ["pacman-open-right.png"], [0,0], pos) self.rightImages = [pygame.image.load("pacman-open-right.png"), pygame.image.load("pacman-closed-right.png")] self.leftImages = [pygame.image.load("pacman-open-left.png"), pygame.image.load("pacman-closed-left.png")] self.upImages = [pygame.image.load("pacman-closed-upwards.png"), pygame.image.load("pacman-open-upwards.png")] self.downImages = [pygame.image.load("pacman-closed-downwards.png"), pygame.image.load("pacman-open-downwards.png")] self.images = self.rightImages self.images = self.leftImages self.images = self.upwardsImages self.images = self.downwardsImages self.maxFrame = len(self.images)-1 self.xDirection = "right" self.yDirection = "none" self.maxSpeedx = maxSpeed[0] self.maxSpeedy = maxSpeed[1]
def __init__(self): # Initialize screen pygame.init() self.size = self.width, self.height = 640, 470 self.black = 0, 0, 0 self.screen = pygame.display.set_mode(self.size) self.background = pygame.image.load("sprites/background.png") # Initialize objects and clock self.spriteList = [] self.player1 = Player(self, 1) self.player2 = Player(self, 2) self.ball1 = Ball(self) self.ball2 = Ball(self) self.ball3 = Ball(self) self.score1 = Score(self, 1) self.score2 = Score(self, 2) self.spriteList.append(self.player1) self.spriteList.append(self.player2) self.spriteList.append(self.score1) self.spriteList.append(self.score2) self.spriteList.append(self.ball1) self.player1_tot = 0 self.player2_tot = 0 self.stop = 0 self.win = 0 self.level = 1 self.counter = 120
def setup(self): self.damping = 3 self.ball = Ball(64, 32, 5) # setup all key buttons to INT mode, same time query work fine self.initKeyButtons("INT") # Open accel self.RPiSpark.Attitude.openWith(temp=True, accel=True, gyro=False)
def buildEgoCentricRepresentationOfWorld(self, world): myTeam = [] enemyTeam = [] balls = [] obstacles = [] for agent in world.agents: if agent != self: agentToAppend = Agent(agent.team, self.getEgoCentricOf(agent), agent.rotation - self.rotation, agent.brain, agent.turnRate, agent.colRadius, agent.drawRadius) agentToAppend.setUID(agent.getUID()) if agent.isStunned: agentToAppend.isStunned = True if agent.team == self.team: myTeam.append(agentToAppend) else: enemyTeam.append(agentToAppend) for ball in world.balls: ballToAppend = Ball(self.getEgoCentricOf(ball)) ballToAppend.setUID(ball.getUID()) balls.append(ballToAppend) for obstacle in world.obstacles: obstacleToAppend = Obstacle(self.getEgoCentricOf(obstacle), obstacle.radius) obstacles.append(obstacleToAppend) return myTeam, enemyTeam, balls, obstacles
def splitBall(self, size, x, y): if size / 2 <= MINBALLSIZE: if len(self.balls) == 0: self.timer.stop() time.sleep(1) self.loadNextLevel() else: ball1 = Ball(self, size / 2) ball2 = Ball(self, size / 2) self.setBallProperties(ball1, x, y, True) self.setBallProperties(ball2, x, y, False) self.balls.append(ball1) self.balls.append(ball2) if random.randrange(BONUS_RANGE) == 0: bonus_type = random.choice(bonus_types) bonus = Bonus(self, bonus_type, x, y) bonus.isActive = True self.bonuses.append(bonus) ball1.splitedLeft = True ball2.splitedRight = True ball1.splitedCounter = 42 ball2.splitedCounter = 42 ball1.y = ball1.dy ball2.y = ball2.dy ball1.ball.show() ball2.ball.show()
def __init__(self): self.window = Window() self.canvas = Canvas(self.window.root) self.playerOne = Player() self.playerTwo = Player() self.ball = Ball() self.game_config = GameConfig()
def test_multiple_instantaneous_ball_collisions_hole_numbers(self): boundery = SlipperyBounceBounderyConditions_2D() ball1 = Ball((-0.5, 0.2), (0, -1), 0.1) ball2 = Ball((-0.5, -0.2), (0, 1), 0.1) ball3 = Ball((0.5, 0.2), (0, -1), 0.1) ball4 = Ball((0.5, -0.2), (0, 1), 0.1) start_positions = np.array( [ball1.location, ball2.location, ball3.location, ball4.location]) simulation1 = SimulationModule( boundery_conditions=boundery, balls_arr=[ball1, ball2, ball3, ball4], halt_condition=HaltConditions.HaltAtGivenSimulationTime(0.2)) simulation1.calculate_next_ball_dynamics() self.assert_ball_is_in_position(ball1, start_positions[0]) self.assert_ball_is_in_position(ball2, start_positions[1]) self.assert_ball_is_in_position(ball3, start_positions[2]) self.assert_ball_is_in_position(ball4, start_positions[3]) self.assertRaises(AssertionError, self.assert_ball_not_in_position, ball1, start_positions[0]) simulation1.halt_condition = HaltConditions.HaltAtGivenSimulationTime( 0.3) simulation1.calculate_next_ball_dynamics() self.assert_ball_not_in_position(ball1, start_positions[0]) self.assert_ball_not_in_position(ball2, start_positions[1]) self.assert_ball_not_in_position(ball3, start_positions[2]) self.assert_ball_not_in_position(ball4, start_positions[3])
def initialize_pygame(self): print("Initializing Pong game ...") pygame.mixer.pre_init(self.settings.sound_sample_rate, -16, self.settings.sound_channels, 1024) pygame.mixer.init() pygame.init() self.clock = pygame.time.Clock() width = int(self.settings.screen_width * self.settings.screen_resize) height = int(self.settings.screen_height * self.settings.screen_resize) self.screen = pygame.display.set_mode((width, height)) self.screen_rect = self.screen.get_rect() pygame.display.set_caption(self.settings.screen_title) self.background = Background(self.settings, self.screen) self.welcome_board = WelcomeBoard(self.settings, self.screen, self) self.scoreboard = Scoreboard(self.settings, self.screen, self) self.victory_board = VictoryBoard(self.settings, self.screen, self) self.ball = Ball(self.settings, self.screen) self.scoreboard.set_ball(self.ball) self.initialize_players()
def main(): pygame.init() WIDTH, HEIGHT = 700, 500 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Gravity!') balls = [] balls.append(Ball(50, 50, 20, (255, 0, 0), velocity=20)) balls.append(Ball(100, 50, 25, (0, 255, 0))) balls.append(Ball(50, 100, 20, (255, 0, 0), velocity=20)) balls.append(Ball(150, 150, 20, (255, 0, 0), velocity=30)) balls.append(Ball(300, 150, 20, (0, 0, 255), velocity=10, angle=140)) clicked_ball = None last_tick_pos = None run = True while run: for event in pygame.event.get(): current_mouse_pos = pygame.mouse.get_pos() if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: index = 0 while clicked_ball is None and index < len(balls): if balls[index].hover(current_mouse_pos): clicked_ball = balls[index] clicked_ball.clicked(True) else: index += 1 if event.type == pygame.MOUSEBUTTONUP: if clicked_ball is not None: clicked_ball.clicked(False) vx = current_mouse_pos[0] - last_tick_pos[0] vy = current_mouse_pos[1] - last_tick_pos[1] clicked_ball.set_velocity(Vector2(vx, vy)) clicked_ball = None if event.type == pygame.MOUSEMOTION: if clicked_ball is not None: clicked_ball.set_position(current_mouse_pos) last_tick_pos = current_mouse_pos screen.fill((255, 255, 255)) for i in range(0, len(balls)): for j in range(i + 1, len(balls)): if balls[i].collides(balls[j]): balls[i].handle_balls_collision(balls[j]) balls[i].update(*screen.get_size()) balls[i].draw(screen) balls[i].draw_vec(screen, size=3) balls[i].draw_tracker(screen) pygame.display.flip() time.sleep(0.05)
def main(): width=600 L=width mapping=Mapping_for_Tkinter(-L/2,L/2,-L/2,L/2,L) #creating mapping ##### create a window, canvas, and racket v=300 a=45 window = Tk() canvas = Canvas(window,width=L,height=L,bg="white") canvas.pack() #creating window racket1=Racket(mapping,canvas,L/10,L/60,) racket2=Racket(mapping,canvas,L/10,L/60,False) #creating racket ball1=Ball(mapping,canvas,0,mapping.get_ymin()+racket1.Ly+mapping.get_width()/120,v,a) #creating ball t=0 # real time between event up=True #this is used to switch the key bindings racket2.activate()#activates racket 2. This is the first to play while True: t=t+0.01 #real time between events- in second racket=0 #real total time- in second side=ball1.update_xy(t,racket1.Ly,racket2.Ly)# Update ball position and return collision event window.update() # update the graphic (redraw) if(up): canvas.bind("<Button-1>",lambda e:racket2.shift_left()) canvas.bind("<Button-3>",lambda e:racket2.shift_right()) else: canvas.bind("<Button-1>",lambda e:racket1.shift_left()) canvas.bind("<Button-3>",lambda e:racket1.shift_right()) #binding buttons to the move methods if side!=0: t=0 # reinitialize the local time if side==2: #checks to see if hit top and if it hits the racket, not then break loop up=False #changes up and checks to see to activate or deactivate rackets racket2.deactivate() racket1.activate() ball1.angle=-1*(0.349065875*(random.uniform(1,9)-1)+0.174533)#gives an angle between -10 and -170 degrees if (ball1.x<racket2.x-racket2.Lx/2 or ball1.x>racket2.x+racket2.Lx/2): racket=2 break if side==1: #checks if hit bottom and if it hits the racket, not then break loop up=True #changes up and checks to see to activate or deactivate rackets racket1.deactivate() racket2.activate() ball1.angle=0.349065875*(random.uniform(1,9)-1)+0.174533#gives an angle between 10 and 170 degrees if (ball1.x<racket1.x-racket1.Lx/2 or ball1.x>racket1.x+racket1.Lx/2): racket=1 break time.sleep(0.01) # wait 0.01 second (simulation time) print("Game over for racket %s!"%racket) window.mainloop()
def loopGame(self): clock = pygame.time.Clock() ball = Ball([100,100]) paddle = Paddle([width/2,395]) font = pygame.font.Font(None, 25) sound_collision = pygame.mixer.Sound("music/tick.mp3") vector = [] posRectx = 90 posRecty = 60 score = 0 for i in range(0, 50): if(i%5==0): posRecty = posRecty + 20 posRectx = 80 else: posRectx = posRectx + 80 rectColid = RectColid([posRectx,posRecty]) vector.append(rectColid) running_game = True while running_game: clock.tick(120) textoScore = font.render("Score: %d" % score, True, white) for event in pygame.event.get(): if event.type==QUIT: running_game = False keys = pygame.key.get_pressed() if keys[K_a]: paddle.imagerect.centerx -= 5 if keys[K_d]: paddle.imagerect.centerx += 5 if paddle.imagerect.colliderect(ball.imagerect): if ball.speed[1] > 0: ball.speed[1] = -ball.speed[1] for rect in vector: if rect.imagerect.colliderect(ball.imagerect): vector.remove(rect) ball.speed[1] = -ball.speed[1] sound_collision.play(1) score += 1 ball.update() paddle.update() screen.fill(black) screen.blit(ball.image, ball.imagerect) screen.blit(paddle.image, paddle.imagerect) #Coloca os objetos na tela for rect in vector: screen.blit(rect.image, rect.imagerect) screen.blit(textoScore, [10, 10]) pygame.display.flip()
def __init__(self, image, maxSpeed, pos = [0,0]): Ball.__init__(self, image, [0,0], pos) self.maxSpeedx = maxSpeed[0] self.maxSpeedy = maxSpeed[1] self.didBounceX = False self.didBounceY = False
def place_items(self): padding = 50; y = Utils.myrandom(padding, self.height - 2 * padding) self.whiteBall = Ball(100, y, 10, True) y = Utils.myrandom(padding, self.height - 2 * padding) self.redBall = Ball(self.width / 2, y, 10, False) y = Utils.myrandom(padding, self.height - 2 * padding) self.hole = Hole(self.width - 100, y, 15)
def __init__(self, screen, player_one, player_two): self.ball = Ball(screen, Variables.SCREEN_WIDTH / 2, Variables.SCREEN_HEIGHT / 2) self.check_input(1, player_one) self.check_input(2, player_two) self.score = str(self.player_one.score) + ' : ' + str( self.player_two.score) self.last_winner = 0
def update(*args): self = args[0] width = args[1] height = args[2] playerPos = args[3] self.facePlayer(playerPos) Ball.update(self, width, height) self.animate() self.changed = False
def collides(self, ball: Ball): x1 = ball.x - ball.radius x2 = ball.x + ball.radius y1 = ball.y - ball.radius y2 = ball.y + ball.radius if x1 <= self.x or x2 >= self.x2: ball.reflect_horizontal() if y1 <= self.y or y2 >= self.y2: ball.reflect_vertical()
def createBall(self, player): """ player - instance of the player class Creates an instance of the ball class and sets the player's ball attribute to this ball instance """ self.ball = Ball(player) player.setPossession(self.ball)
def reset_balls( self): # Reset balls and randomize their values (in defined range) self.balls.empty() [ self.balls.add( Ball(6, rand(self.min_vel, self.min_vel + self.dvel))) for i in xrange(self.num_of_balls) ] self.balls.add(Ball(7, self.min_vel + self.dvel, False))
def update(*args): self = args[0] width = args[1] height = args[2] Ball.update(self, width, height,) self.move() if self.life > 0: self.life -= 1 else: self.living = False
def main(): pygame.init() world = World(screen_size=(600, 600), one_second=1000.) ball = Ball() ball.set_pos(pymunk.Vec2d(2.0, 8.0)) ball.body.velocity = pymunk.Vec2d(1.0, 1.0) world.add(ball) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return world.step() world.draw()
def __init__(self): w = 500 h = 500 self.pWin = GraphWin("Pong", w, h ) myIMG = Image(Point(250, 250), "linesfinished.gif") myIMG.draw(self.pWin) self.b = Ball(self.pWin) self.p = Paddle(self.pWin) self.hits = 0 self.score = 0 self.level = 1 self.scoreTitle = Text(Point(350, 25), "Score:") self.scoreTitle.setTextColor("white") self.scoreTitle.setSize(25) self.userScore = Text(Point(405, 25), self.score) self.userScore.setTextColor("white") self.userScore.setSize(25) self.levelTitle = Text(Point(100, 25), "Level:") self.levelTitle.setTextColor("white") self.levelTitle.setSize(25) self.userLevel = Text(Point(150, 25), self.level) self.userLevel.setTextColor("white") self.userLevel.setSize(25) self.scoreTitle.draw(self.pWin) self.userScore.draw(self.pWin) self.levelTitle.draw(self.pWin) self.userLevel.draw(self.pWin)
def __init__(self, name_image="ship-1.png"): Screen.__init__(self) self.keys = { "up" : [K_UP], "down" : [K_DOWN], "left" : [K_LEFT], "right" : [K_RIGHT], "rotate_left" : [K_a, K_q], "rotate_right": [K_d], "fire" : [K_SPACE], # test "lose_life": [K_l] # c'est un L } self.image = pygame.image.load('img/' + name_image).convert_alpha() self.rect = self.image.get_rect() self.rect.center = self.srect.center self.ball = Ball(default_center=self.rect.center) self.vitesse = 2 self.vitesse_rotate = 2 self.orginal = self.image.copy() self.current_angle = 0 self.cheated = 0 self.max_life = 50 self.life = self.max_life self.score = Score()
def run(self): pygame.init() pygame.display.set_caption("Greek Pong") margin = 50 self.player1.reinit(margin, self.gameHeight, self.width) self.player2.reinit(margin, self.gameHeight, self.width) player1 = self.player1 player2 = self.player2 ball = Ball(self.width, self.gameHeight, self.screen, self) black = pygame.Color(0,0,0) counter = 0 runGame = True while runGame and self.play: for event in pygame.event.get(): if (event.type == QUIT): self.play = False self.state = False runGame = False break pygame.event.pump() keys = pygame.key.get_pressed() mouse = pygame.mouse.get_pressed() ball.moveBall(self.width, self.gameHeight, player1, player2, self) player1.movePaddle(keys, self.gameHeight, self.width, ball, self) player2.movePaddle(keys, self.gameHeight, self.width, ball, self) player1.useWeaponRack(keys, ball, player2, self) player2.useWeaponRack(keys, ball, player1, self) self.checkInstruction(keys) if counter == 400: counter = 0 self.redrawAll(player1, player2, ball, counter) counter += 1 if (self.checkWin(player1, player2)): runGame = False break
def __init__(self, images, maxSpeed, pos = [0,0], mass = 100):#50): Ball.__init__(self, images, [0,0], mass, pos) self.originalImage = self.image self.image = pygame.transform.scale(self.originalImage, (mass, mass)) self.rect = self.image.get_rect(center = self.rect.center) self.maxSpeedx = maxSpeed[0] self.maxSpeedy = maxSpeed[1] self.realSpeedx = self.speedx self.realSpeedy = self.speedy self.accControlx = .1 # Higher number means less acceleration effect ie follows mouse movments more closly any number greater than 1 causes more jitter self.accControly = .1 #self.viscosityX = 4 #self.viscosityY = 4 self.accx = self.accControlx/(mass/50) self.accy = self.accControly/(mass/50) self.mass = mass self.amFollowing = False
def update(*args): self = args[0] width = args[1] height = args[2] Ball.update(self, width, height) self.move() self.animate() self.changed = False #print self.gun.coolDown if self.gun.coolDown > 0: if self.gun.coolDown < self.gun.coolDownMax: self.gun.coolDown += 1 else: self.gun.coolDown = 0 if self.hurtTimer > 0: self.hurtTimer -= 1 self.invincible = True else: self.invincible = False
def __init__(self): # Initilaize pygame and the display/window pygame.init() self.width, self.height = 600, 800 self.screen = pygame.display.set_mode((self.width, self.height)) #, pygame.FULLSCREEN) pygame.display.set_caption('Breakout') # background = pygame.image.load("PiInvaders/background.png").convert(); # Create the game objects self.ball = Ball(self.width / 2, self.height - 32) self.paddle = Paddle(self.width / 2, self.height - 16, 80, 16)
def __init__(self, pos): Ball.__init__(self, "images/Player/pballbu.png", [0,0], pos) self.upImages = [pygame.image.load("images/Chicken/up-walk1.png"), pygame.image.load("images/Chicken/up-walk2.png")] self.downImages = [pygame.image.load("images/Chicken/down-walk1.png"), pygame.image.load("images/Chicken/down-walk2.png")] self.rightImages = [pygame.image.load("images/Chicken/right-walk1.png"), pygame.image.load("images/Chicken/right-walk2.png")] self.leftImages = [pygame.image.load("images/Chicken/left-walk1.png"), pygame.image.load("images/Chicken/left-walk2.png")] self.facing = "up" self.changed = False self.images = self.upImages self.frame = 0 self.maxFrame = len(self.images) - 1 self.waitCount = 0 self.maxWait = 60*.25 self.image = self.images[self.frame] self.rect = self.image.get_rect(center = self.rect.center) self.maxSpeed = 5
def buildEgoCentricRepresentationOfWorld(self, world): myTeam = [] enemyTeam = [] balls = [] obstacles =[] for agent in world.agents: if agent != self: agentToAppend = Agent(agent.team, self.getEgoCentricOf(agent), agent.rotation - self.rotation, agent.brain, agent.turnRate, agent.colRadius, agent.drawRadius) agentToAppend.setUID(agent.getUID()) if agent.isStunned: agentToAppend.isStunned = True if agent.team == self.team: myTeam.append(agentToAppend) else: enemyTeam.append(agentToAppend) for ball in world.balls: ballToAppend = Ball(self.getEgoCentricOf(ball)) ballToAppend.setUID(ball.getUID()) balls.append(ballToAppend) for obstacle in world.obstacles: obstacleToAppend = Obstacle(self.getEgoCentricOf(obstacle), obstacle.radius) obstacles.append(obstacleToAppend) return myTeam, enemyTeam, balls, obstacles
def attack(self=None, attack_times=4, attack_critical_rate=0.51, attack_speed=3): castOnCritical = CastOnCritical() spellDamage = 0.00 ball = Ball() Ball.lockBlueBall(ball) blueBall = Ball.BlueBall Ball.unlockBlueBall(ball) if random.random() <= (attack_critical_rate+(0.1104*blueBall*0.5)): for i in range(0, attack_times): # print("Barrage %r gun critical" % i ) if blueBall< Ball.max_blue_ball: ball.lockBlueBall() ball.BlueBall += 1 ball.unlockBlueBall() if random.random() <= 0.7: spellDamage += castOnCritical.castoncritical() #print "Now BlueBall is %r" % Ball.BlueBall # else: # print("Barrage %r gun not critical" % i ) return spellDamage
def __init__(self, pos): Ball.__init__(self, "PHIL THE NINJA.PNG", [0,0], pos) self.upImages = [pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG")] self.downImages = [pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG")] self.leftImages = [pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG")] self.rightImages = [pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG"), pygame.image.load("PHIL THE NINJA.PNG")] self.facing = "up" self.changed = False self.images = self.upImages self.frame = 0 self.maxFrame = len(self.images) - 1 self.waitCount = 0 self.maxWait = 60*.25 self.image = self.images[self.frame] self.rect = self.image.get_rect(center = self.rect.center) self.maxSpeed = 10
def __init__(self): """Called when the the Game object is initialized. Initializes pygame and sets up our pygame window and other pygame tools that we will need for more complicated tutorials.""" pygame.init() self.uiServer = GameControllerServer(self, min_players=2,max_players=2) self.paddleMap = {} self.leftPaddleFree = True self.rightPaddleFree = True self.started = False self.window = pygame.display.set_mode((800, 400)) self.clock = pygame.time.Clock() pygame.display.set_caption("Pong with Android Controller") pygame.event.set_allowed([QUIT, USEREVENT]) self.background = pygame.Surface((800,400)) self.background.fill((255,255,255)) pygame.draw.line(self.background, (0,0,0), (400,0), (400,400), 2) self.window.blit(self.background, (0,0)) pygame.display.flip() self.sprites = pygame.sprite.RenderUpdates() self.leftpaddle = Paddle((50,200)) self.sprites.add(self.leftpaddle) self.rightpaddle = Paddle((750,200)) self.sprites.add(self.rightpaddle) self.ball = Ball((400,200)) self.sprites.add(self.ball) self.scoreImage = Score((400, 50)) self.sprites.add(self.scoreImage) self.pingsound = pygame.mixer.Sound(os.path.join('sound', 'ping.wav')) self.pongsound = pygame.mixer.Sound(os.path.join('sound', 'pong.wav')) self.uiThread = Thread(target=self.uiServer.serve) self.uiThread.start()
def __init__(self): self.score = 0 self.outs = 0 self.fieldingTeam = Team() self.home = Base() self.one = Base() self.two = Base() self.three = Base() self.ball = Ball() ''' Fielding Array (x marks plate, P is pitcher square) ________________ | 0 | 1 | 2 | ________________ | 3 | 4x | 5 | ________________ | 6x | 7P | 8x | ________________ | | 9x | | ---------------- ''' self.rows = 5 self.columns = 4 self.gridFieldArray = [[0 for x in range (self.rows)]for x in range (self.columns)] self.one.setNextBase(self.two) self.two.setNextBase(self.three) self.three.setNextBase(self.home) for x in range(0, 4): for y in range(0, 5): self.gridFieldArray[x][y] = FieldSquare() self.gridFieldArray[0][0].setKey("LF", 15) self.gridFieldArray[0][2].setKey("CF", 15) self.gridFieldArray[0][4].setKey("RF", 15) self.gridFieldArray[2][1].setKey("SS", 8) self.gridFieldArray[2][2].setKey("P", 8) self.gridFieldArray[2][3].setKey("2B", 8) self.gridFieldArray[3][0].setKey("3B", 8) self.gridFieldArray[3][2].setKey("C", 8) self.gridFieldArray[3][4].setKey("1B", 5)
def icenova(self=None, criticalChance=0.6, criticalDamage=3.6): ball = Ball() Ball.lockBlueBall(ball) blueBall = Ball.BlueBall Ball.unlockBlueBall(ball) if random.random() <= (criticalChance + (0.06 * blueBall * 0.5)): criticalResult = True else: criticalResult = False if criticalResult: ice_nova_dph = (IceNova.base_damage) * (1 + Ball.GreenBall * 0.04) * criticalDamage if Ball.BlueBall < Ball.max_blue_ball: Ball.lockBlueBall(ball) Ball.BlueBall += 1 Ball.unlockBlueBall(ball) else: ice_nova_dph = (IceNova.base_damage) * (1 + Ball.GreenBall * 0.04) return ice_nova_dph
def __init__(self): #creates the window, the ball, the two paddles, and draws the background and the scoreboard. self.win = GraphWin("Pong", 800, 400) self.background = Image(Point(400,200),"pingpong.gif") self.background.draw(self.win) self.ball=Ball(self.win) self.paddle = Paddle(self.win,740,150,750,250,"red") self.paddle1 = Paddle(self.win, 60, 150,70,250,"blue") self.radius = self.ball.getRadius() self.scoreboard = Text(Point(400, 50), "") self.scoreboard.setSize(12) self.scoreboard.setTextColor("white") self.scoreboard.draw(self.win) y = 200 self.middle = self.paddle.move(self.win, y) self.middle1 = self.paddle1.move(self.win,y)
def __init__(self, w=800, h=600): if platform.system() == 'Windows': os.environ['SDL_VIDEODRIVER'] = 'windib' os.environ['SDL_VIDEO_WINDOW_POS'] = "100,100" pygame.init() self.clock = pygame.time.Clock() self.window = pygame.display.set_mode((w, h), pygame.DOUBLEBUF|pygame.HWSURFACE) pygame.display.set_caption('Brick Break!') self.ship = Ship(w/2, h-14) self.ball = Ball((self.ship.x, self.ship.y-self.ship.height/2), (400., 0.)) self.backgroundColor = pygame.Color(255,255,255) pygame.mouse.set_visible(False) pygame.mouse.set_pos(100+w/2, 100+h/2) self.blocks = BlockArray(16,11) self.shipx = pygame.mouse.get_pos()[0] self.goLeft = self.goRight = False
def ballDemoState(self, input): #print "Ball Position: " + str(input[kBalls]) if input[kBalls]: #print "Demo: Found Ball" ball = Ball.closestPrimary() diff = ball.x - self.x #print "Position Difference: " + str(diff) if abs(diff) < (ball_proximity_th + ball.radius): self.sendCommand(cForwardSpeed, forward_speed) elif diff > 0: self.turnRight() else: self.turnLeft() else: #print "Demo: Searching" self.turnRight() return self.state
def firestorm(self=None, criticalChance=0.6, criticalDamage=3.6): fire_storm_dph = 0.00 ball = Ball() Ball.lockBlueBall(ball) blueBall = Ball.BlueBall Ball.unlockBlueBall(ball) if random.random() <= (criticalChance + (0.06 * blueBall * 0.5)): criticalResult = True else: criticalResult = False if criticalResult: for i in range(0, 20): fire_storm_dph += (FireStorm.base_damage) * (1 + Ball.GreenBall * 0.04) * criticalDamage if Ball.BlueBall < Ball.max_blue_ball: Ball.lockBlueBall(ball) Ball.BlueBall += 1 Ball.unlockBlueBall(ball) else: for i in range(0, 20): fire_storm_dph += (FireStorm.base_damage) * (1 + Ball.GreenBall * 0.04) return fire_storm_dph/6
# Places the window on top of all other windows top.wm_attributes("-topmost", 1) # Creates the canvas and passes it several parameters: # bd = 0 and highlightthickness = 0 make sure that there isn't a border around the screen canvas = Tkinter.Canvas(top, width=500, height=400, bd=0, highlightthickness=0) # Tells the canvas to size itself according to the width and height parameters we pass in line 17 canvas.pack() # Tells Tkinter to initialize itself top.update() # Creates an object named 'paddle' of the Paddle class that we created in Paddle.py paddle = Paddle(canvas, 'blue') # Creates an object named 'ball' of the Ball class that we created in Ball.py ball = Ball(canvas, paddle, 'red') current_score = 0 # Creates the label for the score score = Tkinter.Label(canvas, text= ball.score()) # Displays that window canvas.create_window(10, 20, window=score, anchor='w') # Tells the canvas to not loop through the listed command until the user close the window while 1: # Calls the draw function on the ball as long as hit_bottom is False
def main(): """This is the main function called when the program starts. It initializes everything it needs, then runs in a loop until exited. """ display = Display() background = display.drawBackground() display.drawPitch(background) display.centreTitleOnBackground(background) # Prepare Game Objects # clock = pygame.time.Clock() clock = pygw.clock() WM = WorldModel() ball = Ball() blue1 = Agent(BLUE1_START_POS, 1, BLUE_START_ANGLE, WM) blue2 = Agent(BLUE2_START_POS, 2, BLUE_START_ANGLE, WM) red1 = Agent(RED1_START_POS, 3, RED_START_ANGLE, WM) red2 = Agent(RED2_START_POS, 4, RED_START_ANGLE, WM) ball.setName("ball") blue1.setName("blue1") blue2.setName("blue2") red1.setName("red1") red2.setName("red2") # ballSprite = pygame.sprite.RenderPlain(ball) ballSprite = pygw.renderplainsprite(ball) blue1Sprite = pygw.renderplainsprite(blue1) blue2Sprite = pygw.renderplainsprite(blue2) red1Sprite = pygw.renderplainsprite(red1) red2Sprite = pygw.renderplainsprite(red2) frame = 0 going = True # Main game loop while going: clock.tick(FPS) if frame >= 30: frame = 0 else: frame += 1 allData = [ball, blue1, blue2, red1, red2] if (frame % WORLD_MODEL_UPDATE) == 0: WM.update_info(allData) #Update Sprites ballSprite.update() blue1Sprite.update() blue2Sprite.update() red1Sprite.update() red2Sprite.update() #Draw Everything display.drawEverything(background, ballSprite, blue1Sprite, blue2Sprite, red1Sprite, red2Sprite) display.updateFeaturesOnScreen(frame, ball, blue1, blue2, red1, red2) #Check for kicks ball.setPushValue(0) if blue1.kicking or blue2.kicking or red1.kicking or red2.kicking: ball.setPushValue(1) ball.setPushSpeed(5) if blue1.kicking: ball.setPushOrientation(blue1.angle) elif blue2.kicking: ball.setPushOrientation(blue2.angle) elif red1.kicking: ball.setPushOrientation(red1.angle) elif red2.kicking: ball.setPushOrientation(red2.angle) # # ball.setPushValue(0) # # if ball.speed == 0: # ball.setPushValue(1) # ball.setPushOrientation(np.random.randint(0, 360)) # ball.setPushSpeed(5) # pygame.display.flip() pygw.updatefulldisplay() # for event in pygame.event.get(): for event in pygw.getIOevent(): if event.type == pygw.QUIT or event.type == pygw.KEYDOWN and event.key == pygw.K_ESCAPE: going = False print('User quit the game') # pygame.quit() pygw.quitgame() sys.exit()
def discharge(self=None, criticalChance=0.6, criticalDamage=3.6): discharge_dph = 0.00 ball = Ball() Ball.lockBlueBall(ball) blueBall = Ball.BlueBall Ball.unlockBlueBall(ball) if random.random() <= (criticalChance + (0.07 * blueBall * 0.5)): criticalResult = True else: criticalResult = False if criticalResult: discharge_dph = (Discharge.base_ice_dph*Ball.GreenBall+Discharge.base_light_dph *blueBall+Discharge.base_fire_dph*Ball.RedBall)*(1+Ball.GreenBall*0.04)*criticalDamage Ball.lockBlueBall(ball) Ball.BlueBall = 0 Ball.unlockBlueBall(ball) if Ball.BlueBall< Ball.max_blue_ball: Ball.lockBlueBall(ball) Ball.BlueBall +=1 Ball.unlockBlueBall(ball) else: discharge_dph = (Discharge.base_ice_dph*Ball.GreenBall+Discharge.base_light_dph *blueBall+Discharge.base_fire_dph*Ball.RedBall)*(1+Ball.GreenBall*0.04) #print "discharge boom with %r" % discharge_dph return discharge_dph