class App: screen_size = (160, 120) margin = 10 @property def objects(self): yield self.paddle def __init__(self): pyxel.init(*App.screen_size) self.background = Background(App.screen_size, App.margin) self.ball = Ball(App.screen_size, App.margin) self.paddle = Paddle(App.screen_size, App.margin) pyxel.run(self.update, self.draw) def update(self): if pyxel.btnp(pyxel.KEY_Q): pyxel.quit() self.ball.update() for obj in self.objects: obj.update() if obj.ball_collide(self.ball) and obj == 'rectangle': obj.alive = False def draw(self): self.background.draw() self.ball.draw() for obj in self.objects: obj.draw()
def __init__(self, number, x_range, y_range, width, height, fps=30, background="black", gravity=9.81): super().__init__(width, height, fps, background) allowed_colours = list(self.colours.keys()) allowed_colours.remove('black') self.balls = [ Ball(1, self.colours[choice(allowed_colours)], (randint(40, self.width - 100), 60), id=i, radius=3) for i in range(number) ] self.centre_ball = Ball(2, self.colours["red"], (self.width / 2, self.height / 2), id=69, radius=10)
def __init__(self): pyxel.init(*App.screen_size) self.background = Background(App.screen_size, App.margin) self.ball = Ball(App.screen_size, App.margin) self.paddle = Paddle(App.screen_size, App.margin) pyxel.run(self.update, self.draw)
def reset_game(self): """Reset score and position.""" self.l_score = 0 self.r_score = 0 self.finish = False self.music.start_music() self.l_paddle = Paddle( coordinates=(PADDLE_SIDE, (HEIGHT - PADDLE_HEIGHT) // 2), colour=COL_PADDLE, width=PADDLE_WIDTH, height=PADDLE_HEIGHT, control_up=pyxel.KEY_W, control_down=pyxel.KEY_S, move_speed=PADDLE_MOVE_SPEED, dimensions=DIMENSIONS, ) self.r_paddle = Paddle( coordinates=( WIDTH - PADDLE_SIDE - PADDLE_WIDTH, (HEIGHT - PADDLE_HEIGHT) // 2, ), colour=COL_PADDLE, width=PADDLE_WIDTH, height=PADDLE_HEIGHT, control_up=pyxel.KEY_UP, control_down=pyxel.KEY_DOWN, move_speed=PADDLE_MOVE_SPEED, dimensions=DIMENSIONS, ) self.ball = Ball( coordinates=(WIDTH // 2, HEIGHT // 2), colour=COL_BALL, width=BALL_SIDE, height=BALL_SIDE, initial_velocity=BALL_INITIAL_VELOCITY, dimensions=DIMENSIONS, ) self.sparkler = ParticleEmitter(self.ball) pickup_types = { "sparkle": PickupType(14, self.sparkler.turn_on, self.sparkler.turn_off), "expand": PickupType(12, self.expand_paddle, self.contract_paddle), "slow": PickupType(8, self.slow_paddle, self.speed_paddle), "bounce": PickupType(11, self.ball.bounce_on, self.ball.bounce_off), "giantball": PickupType(10, self.ball.giant_on, self.ball.giant_off), } self.expand_stack = [] self.speed_stack = [] pickup_side_buffer = PADDLE_WIDTH + PADDLE_SIDE + 2 self.pickups = Pickups( pickup_types, self.music, pickup_side_buffer, WIDTH - pickup_side_buffer, 0, HEIGHT ) self.reset_after_score()
def __init__(self, caption='Server'): pygame.init() pygame.font.init() self.paddle1 = PaddlePlayer(self.WIDTH, self.HEIGHT, self.OFFSET) # player self.paddle2 = PaddleEnemy(self.WIDTH, self.HEIGHT, self.WIDTH - 40) # bot self.b = Ball(self.WIDTH, self.HEIGHT) self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT)) pygame.display.set_caption(caption) self.running = True self.font = pygame.font.SysFont('Arial', 30) self.local = False
def game(): clock = pygame.time.Clock() fps = 120 size = width, height = 460, 620 win = pygame.display.set_mode(size) all_sprites = pygame.sprite.Group() horizontal_border_bottom = pygame.sprite.Group() horizontal_border_top = pygame.sprite.Group() vertical_borders = pygame.sprite.Group() ball_sprite = pygame.sprite.Group() platform_sprite_bottom = pygame.sprite.Group() platform_sprite_top = pygame.sprite.Group() bg = pygame.image.load(f'bg/bg_{random.randint(1, 5)}.png') Border(5, 5, width - 5, 5, all_sprites, horizontal_border_top) Border(5, height - 5, width - 5, height - 5, all_sprites, horizontal_border_bottom) Border(5, 5, 5, height - 5, all_sprites, vertical_borders) Border(width - 5, 5, width - 5, height - 5, all_sprites, vertical_borders) ball = Ball(20, 100, 100, all_sprites, ball_sprite, platform_sprite_bottom, platform_sprite_top) run = False while not run: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: run = True font = pygame.font.Font('fonts/Quicksand-Regular.ttf', 40) rendered = font.render('Press any key', True, pygame.color.Color('white')) rect = rendered.get_rect() rect.y = 260 rect.x = (width - rect.width) / 2 win.blit(rendered, rect) pygame.display.flip() pygame.display.update() time.sleep(1) while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False draw_window(win, bg, width, ball_sprite, horizontal_border_bottom, horizontal_border_top, vertical_borders, victory, clock, fps, platform_sprite_bottom, platform_sprite_top, all_sprites) if ball.restart == True: return 0
def get_empty_3dof_environment(): """An easy difficulty environment for planning tests with two obstacles, a ball as a target, and a simple human arm. """ obstacles = [] ball = Ball([2.5, 2.5, 2.0], 0.25, target=True) q = np.array([0, 0, 0, np.pi / 2, 0, 0, 0]) robot = simple_3dof_arm(2.0, 2.0, 2.0, q, np.array([3.0, 1.0, 0.0])) return Environment(dynamic_objects=[ball], static_objects=obstacles, robot=robot)
def __init__(self ,progs, visualizer,gwidth = 90, glength = 120 , gfriction = 1): self.cycle = Cycle() self.ground = Ground(glength , gwidth ,gfriction ) self.players =[] for i in range(2): for j in range(5): self.players.append(Player(self.ground, progs[i] , i , j , Vector( ((1.0*indexi[j]) * (gwidth / 2)) , (1.0*indexj[j]) * (glength / 2) * ((-1) ** (i)) ) )) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, self.players[j].pos.x, self.players[j].pos.y) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, indexi[j] * gwidth / 2, indexj[j] * glength / 2 * (-1) ** (i)) self.ball = Ball(self.ground) self.state = State(self.players , self.ball) self.referee = Referee(self.state) self.visualizer = visualizer
def get_medium_environment(): """A medium difficulty environment for planning tests with two obstacles, a ball as a target, and a simple human arm. """ obstacles = [ Obstacle([2.5, 0, 2.2], [3.5, 1, 2.5]), Obstacle([3, 2, 1], [4, 2.5, 1.5]) ] ball = Ball([2.5, 2.5, 2.0], 0.25, target=True) q = np.array([0, 0, 0, 0, 0, 0, 0]) robot = simple_human_arm(2.0, 2.0, q, np.array([3.0, 1.0, 0.0])) return Environment(dynamic_objects=[ball], static_objects=obstacles, robot=robot)
def _initialize_game_objects(self): self.screen.fill(BLACK) self.line = MiddleLine(GREY, self.screen, (int(self.screen_width / 2), 0), 1, self.screen_height) pod_player1_position, pod_player2_position = self._compute_player_pods_initial_positions( ) self.pod_player1 = Paddle('seznam_logo.png', self.screen, pod_player1_position, POD_WIDTH, POD_HEIGHT) self.pod_player2 = Paddle('seznam_logo.png', self.screen, pod_player2_position, POD_WIDTH, POD_HEIGHT) score_player1_position, score_player2_position = self._compute_player_score_positions( ) self.score_player1 = Score(self.state['player1']['score'], DARK_GREY, self.screen, score_player1_position, width=SCORE_WIDTH, heigth=SCORE_HEIGHT) self.score_player2 = Score(self.state['player2']['score'], DARK_GREY, self.screen, score_player2_position, width=SCORE_WIDTH, heigth=SCORE_HEIGHT) self.frame = Frame(WHITE, self.screen, (0, 0), self.screen_width, self.screen_height, border=1) self.ball = Ball([5, 5], 'seznam_icon.png', self.screen, width=BALL_WIDTH, height=BALL_HEIGHT) pygame.display.flip()
def initialize_game(self): while True: window = Window(self.level, self.lives, self.score) self.initialize_brickpattern(window) ball1 = Ball(config.PADDLE_X + int(config.PADDLE_WIDTH / 2), config.PADDLE_Y - 1, 1, 1, config.BALL_VX, config.BALL_VY, config.BALL_COLOR, config.BALL_SPRITE) paddle = Paddle(config.PADDLE_X, config.PADDLE_Y, 1, config.PADDLE_WIDTH, config.PADDLE_COLOR, config.PADDLE_SPRITE) window.add(ball1) window.addPaddle(paddle) self.level, self.lives, self.score = window.render() if self.lives == 0: print("Game over youe score is :", self.score) break
def get_hard_environment_v2(): """A very hard difficulty environment for planning tests with three obstacles, a ball as a target, and a simple human arm. """ obstacles = [ Obstacle([2.5, 2.0, 0.0], [4.0, 2.5, 4.0]), Obstacle([1.5, 2.0, 0.0], [2.5, 3.5, 4.0]), Obstacle([3.2, 3.5, 0.0], [5.5, 4.0, 4.0]) ] ball = Ball([2.8, 3.8, 2.0], 0.25, target=True) q = np.array([0, 0, 0, 0, 0, 0, 0]) robot = simple_human_arm(2.0, 2.0, q, np.array([3.0, 3.0, 0.0])) return Environment(dynamic_objects=[ball], static_objects=obstacles, robot=robot)
def get_hard_environment(): """A hard difficulty environment for planning tests with five obstacles, a ball as a target, and a simple human arm. """ obstacles = [ Obstacle([0.0, 2.0, 0.0], [1.5, 2.5, 3.0]), Obstacle([0.0, 4.0, 0.0], [1.5, 4.5, 3.0]), Obstacle([0.0, 2.5, 0.0], [0.5, 4.0, 3.0]), Obstacle([0.0, 2.0, 3.0], [1.5, 4.5, 3.5]), Obstacle([0.5, 2.5, 0.0], [1.5, 4.0, 1.0]) ] ball = Ball([1.0, 3.25, 2.0], 0.5, target=True) q = np.array([0, 0, 0, -np.pi / 2.0, 0, 0, 0]) robot = simple_human_arm(3.0, 2.0, q, np.array([1.0, 1.0, 0.0])) return Environment(dynamic_objects=[ball], static_objects=obstacles, robot=robot)
def get_tutorial_environment(): """Our environment from our documentation tutorial""" # Create an arm with a specific config and base position q0 = np.array([0.5, 0.2, 0, 0.5, 0, 0, 0]) base_pos = np.array([2.0, 2.0, 0.0]) # And link segments of length 2.0 arm = simple_human_arm(2.0, 2.0, q0, base_pos) # We then create a ball, target, and obstacle ball = Ball(position=[2.0, 0.0, 2.0], radius=0.15) target = Target(position=[5.0, 8.0, 2.0], radius=0.5) obstacle = Obstacle([4, 4, 0], [5, 5, 2]) # And use these to create an environment with dimensions 10x10x10 return Environment(dimensions=[10, 10, 10], dynamic_objects=[ball], static_objects=[target, obstacle], robot=arm)
def get_noodle_environment(): """An absurd environment for our noodle arm to do planning tests. It has five obstacles, a ball as a target, and our 10 link noodle arm """ obstacles = [ Obstacle([0.0, 2.0, 0.0], [1.5, 2.5, 3.0]), Obstacle([4.0, 4.0, 0.0], [4.5, 4.5, 3.0]), Obstacle([5.0, 0, 2.0], [5.5, 0.5, 3.0]), Obstacle([2.0, 2.0, 3.0], [5.0, 2.5, 3.5]), Obstacle([3.0, 4.5, 6.0], [7.0, 6.0, 5.0]) ] ball = Ball([5.0, 5.0, 3.0], 0.5, target=True) q = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) seg_lengths = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] robot = noodle_arm(seg_lengths, q, np.array([3.0, 1.0, 0.0])) return Environment(dynamic_objects=[ball], static_objects=obstacles, robot=robot)
def __init__(self, number, x_range, y_range, width, height, fps=30, background="black", gravity=9.81): super().__init__(width, height, fps, background) allowed_colours = list(self.colours.keys()) allowed_colours.remove('black') self.balls = [ Ball(uniform(0.5, 4), self.colours[choice(allowed_colours)], (randint(0, x_range), 60), id=i) for i in range(number) ]
def __init__(self, entities, balls=[]): # Calculate sprite corners spr_corner = SpriteManager.load_sprite('spr_corner.png') width = spr_corner.get_width() height = spr_corner.get_height() spr_corner_top_left = swap_color(spr_corner, Colors.WHITE, Colors.GREY) spr_corner_top_right = pygame.transform.flip(spr_corner_top_left, True, False) spr_corner_bottom_left = pygame.transform.flip(spr_corner_top_left, False, True) spr_corner_bottom_right = pygame.transform.flip( spr_corner_top_right, False, True) # Generate sprite panel self.spr_panel = pygame.Surface((width * 2, height * 2)) self.spr_panel.fill(Colors.BLACK) self.spr_panel.blit(spr_corner_top_left, (0, 0)) self.spr_panel.blit(spr_corner_top_right, (width, 0)) self.spr_panel.blit(spr_corner_bottom_left, (0, height)) self.spr_panel.blit(spr_corner_bottom_right, (width, height)) self.spr_panel.set_colorkey(Colors.BLACK) # Surface for objects that are going to have a shadow self.display = pygame.Surface((250, 350)) # Entities group self.entities = Group(entities) # Projectiles group self.projectiles = Group() # Balls group self.balls = Group() for x, y, radius in balls: self.balls.add(Ball(x, y, radius)) # Particles groups self.top_particles = Group() self.bottom_particles = Group()
def initialize_game(self): begin = clock() while True: window = Window(self.level, self.lives, self.score) self.initialize_brickpattern(window) ball1 = Ball(config.PADDLE_X+int(config.PADDLE_WIDTH / 2), config.PADDLE_Y - 1, 1, 1, config.BALL_VX, config.BALL_VY, config.BALL_COLOR, config.BALL_SPRITE) paddle = Paddle(config.PADDLE_X, config.PADDLE_Y, 1, config.PADDLE_WIDTH, config.PADDLE_COLOR, config.PADDLE_SPRITE) window.add(ball1) window.addPaddle(paddle) self.level, self.lives, self.score = window.render() if self.lives == 0: print("Game over your score is :", self.score) print("time taken :", clock() - begin) break elif self.lives > 0 and self.level == 5: print("You finished the game your score is :", self.score) print("Time taken :", clock() - begin) break
def create_ball(self): speed = (random.randint(-2, 2), c.ball_speed) self.ball = Ball(c.screen_width // 2, c.screen_height // 2, c.ball_radius, c.ball_color, speed) self.objects.append(self.ball) self.pause = c.pause_ball * c.frame_rate
port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((server, port)) except socket.error as e: str(e) s.listen(2) print('Waiting for connection, Server started') game = Game([ Player(45, 285, 10, 150, (255, 255, 255)), Player(945, 285, 10, 150, (255, 255, 255)) ], Ball(465, 330, 25, (255, 255, 255)), -1, 0, 0) def threaded_client(conn, player): global playersCount conn.send(str.encode(str(player))) while True: try: data = pickle.loads(conn.recv(2048)) if not data: print('Disconnected') break else: if data == 'ready': if player == 0:
def __init__(self): """ Class constructor """ self.counter = 0 self.time = time.time() self.on = True # Output Class self.out = NaoOutput.NaoOutput(self) # Setup nao modules inside brain for easy access self.vision = vision.vision self.sensors = sensors.sensors self.logger = loggingBoard.loggingBoard self.comm = comm.inst self.comm.gc.team = TeamConfig.TEAM_NUMBER self.comm.gc.player = TeamConfig.PLAYER_NUMBER #initalize the leds #print leds self.leds = Leds.Leds(self) self.speech = _speech.speech # Initialize motion interface and module references self.motion = motion.MotionInterface() self.motionModule = motion # Get the pointer to the C++ RoboGuardian object for use with Python self.roboguardian = _roboguardian.roboguardian self.roboguardian.enableFallProtection(True) # Get our reference to the C++ localization system self.loc = Loc() # Retrieve our robot identification and set per-robot parameters self.CoA = robots.get_certificate() self.CoA.setRobotGait(self.motion) # coa is Certificate of Authenticity (to keep things short) self.out.printf(self.CoA) self.out.printf("GC: I am on team " + str(TeamConfig.TEAM_NUMBER)) self.out.printf("GC: I am player " + str(TeamConfig.PLAYER_NUMBER)) # Initialize various components self.my = MyInfo(self.loc) # Functional Variables self.my.playerNumber = self.comm.gc.player if self.comm.gc.color == GameController.TEAM_BLUE: self.my.teamColor = Constants.teamColor.TEAM_BLUE else: self.my.teamColor = Constants.teamColor.TEAM_RED # Information about the environment self.initFieldObjects() self.initTeamMembers() self.ball = Ball(self.vision.ball, self.loc, self.my) self.play = Play.Play() self.sonar = Sonar.Sonar() if Constants.LOG_COMM: self.out.startCommLog() # Stability data self.stability = Stability.Stability(self.sensors) # FSAs self.player = Switch.selectedPlayer.SoccerPlayer(self) self.tracker = HeadTracking.HeadTracking(self) self.nav = Navigator.Navigator(self) self.playbook = PBInterface.PBInterface(self) self.kickDecider = KickDecider.KickDecider(self) self.gameController = GameController.GameController(self) self.fallController = FallController.FallController(self)
class Simulator(object): def __init__(self ,progs, visualizer,gwidth = 90, glength = 120 , gfriction = 1): self.cycle = Cycle() self.ground = Ground(glength , gwidth ,gfriction ) self.players =[] for i in range(2): for j in range(5): self.players.append(Player(self.ground, progs[i] , i , j , Vector( ((1.0*indexi[j]) * (gwidth / 2)) , (1.0*indexj[j]) * (glength / 2) * ((-1) ** (i)) ) )) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, self.players[j].pos.x, self.players[j].pos.y) #print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(i, j, indexi[j] * gwidth / 2, indexj[j] * glength / 2 * (-1) ** (i)) self.ball = Ball(self.ground) self.state = State(self.players , self.ball) self.referee = Referee(self.state) self.visualizer = visualizer def send_data(self): for i in range(10): self.visualizer.stdin.write(`int(self.state.players[i].pos.x)`+'\n') self.visualizer.stdin.write(`int(self.state.players[i].pos.y)`+'\n') #print >>sys.stderr, 'THIS IS RS, PLAYER %d: %d, %d'%(i, int(self.state.players[i].pos.x), int(self.state.players[i].pos.y)) self.visualizer.stdin.write(`int(self.state.ball.pos.x)`+'\n') self.visualizer.stdin.write(`int(self.state.ball.pos.y)`+'\n') self.visualizer.stdin.write(`self.state.game_state `+'\n') #def player_move(self, i , coefficient=1.0/100): # self.players[i].move(coefficient) def ball_move(self , coefficient=1.0/100): self.ball.move(coefficient) width = self.ground.width length = self.ground.length while True: x = self.ball.pos.x y = self.ball.pos.y if x <= width/2 and x >= -width/2 and y <= length/2 and y >= -length/2: break #print >>sys.stderr, 'BALL IS OUTSIDE GROUND, VELOCITY IS: %f, %f'%(self.ball.vel.x, self.ball.vel.y) if x>(width/2) : self.ball.vel.x= -self.ball.vel.x self.ball.pos.x= width-x #print >>sys.stderr, 'THE BALL WENT TOO RIGHT, NEW X: %f'%(self.ball.pos.x) if x<-(width/2) : self.ball.vel.x= -self.ball.vel.x self.ball.pos.x= -width-x #print >>sys.stderr, 'THE BALL WENT TOO LEFT, NEW X: %f'%(self.ball.pos.x) if y>(length/2) : self.state.update( self.referee.is_goal(self.ball , self.ground) ) self.ball.vel.y= -self.ball.vel.y self.ball.pos.y= length-y #print >>sys.stderr, 'THE BALL WENT TOO UP, NEW Y: %f'%(self.ball.pos.y) if y<(-(length/2)) : self.state.update( self.referee.is_goal(self.ball , self.ground) ) self.ball.pos.y= -length-y self.ball.vel.y=-self.ball.vel.y #print >>sys.stderr, 'THE BALL WENT TOO DOWN, NEW Y: %f'%(self.ball.pos.y) # def check_pos(self , coefficient=1.0/100): # a = range(10) # random.shuffle(a) # sizes = [i/20.0 for i in xrange(1, 11)] # random.shuffle(sizes) # for i in a: # temp_pos = self.players[i].pos # for j in range(10): # if( ( self.players[j].is_overlap(sizes[i], sizes[j], temp_pos) ) and (j!=i)): # self.players[i].move(-coefficient) # break def move(self): # for j in xrange(100): # for i in xrange(10): # self.player_move(i) # self.ball_move() # self.check_pos() #for t in xrange(steps_per_cycle): coefficient = 1.0/config.steps_per_cycle q = deque(self.players) if self.state.kicked: if self.ball.vel.len() < 4: self.ball.vel = Vector(2*random.choice([-1, 1]), 2*random.choice([-1, 1])) for t in xrange(config.steps_per_cycle): self.ball_move(coefficient) for p in self.players: p.rsteps = config.steps_per_cycle no_change = 0 #print >>sys.stderr, 'move called' #player_size = random.choice([0.3, 0.4, 0.5]) while len(q): c = q.popleft() #print >>sys.stderr, 'moving %d, %d, %d'%(c.team, c.number, c.rsteps) c.move(coefficient) c.rsteps-=1 change = True for other in self.players: if c==other: continue if c.is_overlap(config.player_size, config.player_size, other.pos): c.move(-coefficient) c.rsteps+=1 change = False break if change: no_change=0 else: no_change+=1 if c.rsteps: q.append(c) if no_change==20: #print >>sys.stderr, 'breaking' #for p in self.players: # print >>sys.stderr, 'PLAYER %d, %d: %f, %f'%(p.team, # p.number, # p.pos.x, # p.pos.y) #print >>sys.stderr, 'BALL: %f, %f'%(self.ball.pos.x, # self.ball.pos.y) break # while True: # change = False # for p in self.players: # if not p.rsteps: # continue # p.move(coefficient) # p.rsteps-=1 # change = True # for other in self.players: # if other==p: # continue # if p.is_overlap(config.player_size, config.player_size, # other.pos): # p.move(-coefficient) # change = False # break # if not change: # break def goto_kickoff(self): self.ball.pos = Vector(0, 0) self.ball.vel = Vector(0, 0) gwidth = config.gwidth glength = config.glength for i in xrange(2): for j in xrange(5): self.players[i*5+j].pos=Vector( ((1.0*indexi[j]) * (gwidth / 2)) , (1.0*indexj[j]) * (glength / 2) * ((-1) ** (i)) ) self.players[i*5+j].vel = Vector(0, 0) def simulate(self) : global cycle_length #print self.state.game_state prev_locs = [Vector(0, 0) for i in xrange(10)] for i in xrange(game_duration): #print >>sys.stderr, 'CYCLE #%d'%(i) self.state.kicked = False self.referee.update_state() self.send_data() #self.state.update() for j in xrange(10): self.players[j].comm.send_state(self.state) #print >>sys.stderr, 'DOOOOOOOOOOOOOOOOOOOOOOONE SENDING DATA AT %f'%(time.time()) time.sleep(cycle_length) self.cycle.update_players(self.state) self.move() soc = 0 for (i, p) in enumerate(self.players): soc += (p.pos-prev_locs[i]).len() if soc < 1 and self.state.game_state!=state.kickoff_team1 and self.state.game_state!=state.kickoff_team2: self.ball.vel += Vector(random.choice([-1, 1])*5, random.choice([-1, 1])*5) print 'accel' prev_locs = [Vector(p.pos.x, p.pos.y) for p in self.players] if self.state.game_state==state.team1_goal: self.state.game_state = state.kickoff_team2 self.goto_kickoff() if self.state.game_state==state.team2_goal: self.state.game_state = state.kickoff_team1 self.goto_kickoff() if(self.state.last_kicked != None): pass for i in xrange(10): self.players[i].comm.terminate()
class Pong: """The class that sets up and runs the game.""" def __init__(self): """Initiate pyxel, set up initial game variables, and run.""" pyxel.init(WIDTH, HEIGHT, caption="Pong!", scale=8, fps=60) self.music = Music() self.reset_game() pyxel.run(self.update, self.draw) def reset_game(self): """Reset score and position.""" self.l_score = 0 self.r_score = 0 self.finish = False self.music.start_music() self.l_paddle = Paddle( coordinates=(PADDLE_SIDE, (HEIGHT - PADDLE_HEIGHT) // 2), colour=COL_PADDLE, width=PADDLE_WIDTH, height=PADDLE_HEIGHT, control_up=pyxel.KEY_W, control_down=pyxel.KEY_S, move_speed=PADDLE_MOVE_SPEED, dimensions=DIMENSIONS, ) self.r_paddle = Paddle( coordinates=( WIDTH - PADDLE_SIDE - PADDLE_WIDTH, (HEIGHT - PADDLE_HEIGHT) // 2, ), colour=COL_PADDLE, width=PADDLE_WIDTH, height=PADDLE_HEIGHT, control_up=pyxel.KEY_UP, control_down=pyxel.KEY_DOWN, move_speed=PADDLE_MOVE_SPEED, dimensions=DIMENSIONS, ) self.ball = Ball( coordinates=(WIDTH // 2, HEIGHT // 2), colour=COL_BALL, width=BALL_SIDE, height=BALL_SIDE, initial_velocity=BALL_INITIAL_VELOCITY, dimensions=DIMENSIONS, ) self.sparkler = ParticleEmitter(self.ball) pickup_types = { "sparkle": PickupType(14, self.sparkler.turn_on, self.sparkler.turn_off), "expand": PickupType(12, self.expand_paddle, self.contract_paddle), "slow": PickupType(8, self.slow_paddle, self.speed_paddle), "bounce": PickupType(11, self.ball.bounce_on, self.ball.bounce_off), "giantball": PickupType(10, self.ball.giant_on, self.ball.giant_off), } self.expand_stack = [] self.speed_stack = [] pickup_side_buffer = PADDLE_WIDTH + PADDLE_SIDE + 2 self.pickups = Pickups( pickup_types, self.music, pickup_side_buffer, WIDTH - pickup_side_buffer, 0, HEIGHT ) self.reset_after_score() def reset_after_score(self): """Reset paddles and ball.""" self.start = pyxel.frame_count + 50 self.speed_up = self.start + SPEED_PERIOD self.ball.reset() ############## # Game logic # ############## def update(self): """Update logic of game. Updates the paddles, ball, and checks for scoring/win condition.""" self.l_paddle.update() self.r_paddle.update() self.sparkler.sparkle() if pyxel.frame_count > self.start and not self.finish: outcome = self.ball.update() if outcome: self.score(outcome) self.check_speed() if self.ball.check_collision([self.l_paddle, self.r_paddle]): self.music.sfx_hit() self.pickups.check_pickup() self.pickups.check_collision(self.ball) if pyxel.btn(pyxel.KEY_Q): pyxel.quit() if pyxel.btnp(pyxel.KEY_R): self.reset_game() def check_speed(self): """Adds velocity to the ball periodically.""" if pyxel.frame_count > self.speed_up: self.speed_up += SPEED_PERIOD self.ball.x_vol += SPEED_AMOUNT * sign(self.ball.x_vol) self.ball.y_vol += SPEED_AMOUNT * sign(self.ball.y_vol) def score(self, outcome): """Adds to the score if the ball hits the side. Check win condition.""" self.music.sfx_score() if outcome == "l": self.l_score += 1 elif outcome == "r": self.r_score += 1 if self.l_score >= WIN_CONDITION or self.r_score >= WIN_CONDITION: self.win_event() self.reset_after_score() def win_event(self): """What happens when someone wins the game!""" self.finish = True self.music.stop_music() self.music.sfx_finish() ###################### # Pickup controllers # ###################### def expand_paddle(self): """Expand the pandle temporarily.""" if self.ball.x_vol > 0: paddle = self.l_paddle else: paddle = self.r_paddle paddle.height = PADDLE_HEIGHT_EXPANDED paddle.y -= (PADDLE_HEIGHT_EXPANDED - PADDLE_HEIGHT) // 2 self.expand_stack.append(paddle) def contract_paddle(self): """Revert paddle side to normal.""" paddle = self.expand_stack.pop(0) if paddle not in self.expand_stack: paddle.height = PADDLE_HEIGHT paddle.y += (PADDLE_HEIGHT_EXPANDED - PADDLE_HEIGHT) // 2 def slow_paddle(self): """Slow the pandle temporarily.""" if self.ball.x_vol > 0: paddle = self.l_paddle else: paddle = self.r_paddle paddle.move_speed = PADDLE_MOVE_SPEED_SLOW paddle.colour = COL_PADDLE_SLOW self.speed_stack.append(paddle) def speed_paddle(self): """Speed the paddle back up to normal speed.""" paddle = self.speed_stack.pop(0) if paddle not in self.speed_stack: paddle.move_speed = PADDLE_MOVE_SPEED paddle.colour = COL_PADDLE ############## # Draw logic # ############## def draw(self): """Draw the paddles and ball OR the end screen.""" if self.finish: self.draw_end_screen() else: pyxel.cls(COL_BACKGROUND) self.sparkler.display() self.l_paddle.display() self.r_paddle.display() self.pickups.display() self.ball.display() self.draw_score() def draw_score(self): """Draw the score at the top.""" l_score = "{:01}".format(self.l_score) r_score = "{:01}".format(self.r_score) buffer = PADDLE_SIDE + PADDLE_WIDTH + 2 r_x_position = WIDTH - FONT_WIDTH - buffer pyxel.text(x=buffer, y=2, s=l_score, col=COL_SCORE) pyxel.text(x=r_x_position, y=2, s=r_score, col=COL_SCORE) def draw_end_screen(self): """Draw the final screen with the winner!""" pyxel.cls(col=COL_FINISH) display_text = TEXT_FINISH[:] if self.l_score >= WIN_CONDITION: winner = "The LEFT player!" else: winner = "The RIGHT player!" display_text.insert(1, winner) for i, text in enumerate(display_text): y_offset = (FONT_HEIGHT + 2) * i text_x = self.center_text(text, WIDTH) pyxel.text(text_x, HEIGHT_FINISH + y_offset, text, COL_FINISH_TEXT) @staticmethod def center_text(text, page_width, char_width=FONT_WIDTH): """Helper function for calcuating the start x value for centered text.""" text_width = len(text) * char_width return (page_width - text_width) // 2
class Brain(object): """ Class brings all of our components together and runs the behaviors """ def __init__(self): """ Class constructor """ self.counter = 0 self.time = time.time() self.on = True # Output Class self.out = NaoOutput.NaoOutput(self) # Setup nao modules inside brain for easy access self.vision = vision.vision self.sensors = sensors.sensors self.logger = loggingBoard.loggingBoard self.comm = comm.inst self.comm.gc.team = TeamConfig.TEAM_NUMBER self.comm.gc.player = TeamConfig.PLAYER_NUMBER #initalize the leds #print leds self.leds = Leds.Leds(self) self.speech = _speech.speech # Initialize motion interface and module references self.motion = motion.MotionInterface() self.motionModule = motion # Get the pointer to the C++ RoboGuardian object for use with Python self.roboguardian = _roboguardian.roboguardian self.roboguardian.enableFallProtection(True) # Get our reference to the C++ localization system self.loc = Loc() # Retrieve our robot identification and set per-robot parameters self.CoA = robots.get_certificate() self.CoA.setRobotGait(self.motion) # coa is Certificate of Authenticity (to keep things short) self.out.printf(self.CoA) self.out.printf("GC: I am on team " + str(TeamConfig.TEAM_NUMBER)) self.out.printf("GC: I am player " + str(TeamConfig.PLAYER_NUMBER)) # Initialize various components self.my = MyInfo(self.loc) # Functional Variables self.my.playerNumber = self.comm.gc.player if self.comm.gc.color == GameController.TEAM_BLUE: self.my.teamColor = Constants.teamColor.TEAM_BLUE else: self.my.teamColor = Constants.teamColor.TEAM_RED # Information about the environment self.initFieldObjects() self.initTeamMembers() self.ball = Ball(self.vision.ball, self.loc, self.my) self.play = Play.Play() self.sonar = Sonar.Sonar() if Constants.LOG_COMM: self.out.startCommLog() # Stability data self.stability = Stability.Stability(self.sensors) # FSAs self.player = Switch.selectedPlayer.SoccerPlayer(self) self.tracker = HeadTracking.HeadTracking(self) self.nav = Navigator.Navigator(self) self.playbook = PBInterface.PBInterface(self) self.kickDecider = KickDecider.KickDecider(self) self.gameController = GameController.GameController(self) self.fallController = FallController.FallController(self) def initFieldObjects(self): """ Build our set of Field Objects which are team specific compared to the generic forms used in the vision system """ # Build instances of the vision based field objects # Left post is on that goalie's left # Note: As of 6/8/12, ygrp holds info about ambiguous posts # Yellow goal left and right posts self.yglp = FieldObject(self.vision.yglp, Constants.vis_landmark.VISION_YGLP, self.loc) self.ygrp = FieldObject(self.vision.ygrp, Constants.vis_landmark.VISION_YGRP, self.loc) # Blue Goal left and right posts self.bglp = FieldObject(self.vision.bglp, Constants.vis_landmark.VISION_BGLP, self.loc) self.bgrp = FieldObject(self.vision.bgrp, Constants.vis_landmark.VISION_BGRP, self.loc) # Now we build the field objects to be based on our team color self.makeFieldObjectsRelative() def makeFieldObjectsRelative(self): """ Builds a list of fieldObjects based on their relative names to the robot Needs to be called when team color is determined """ # Note: corner directions are relative to perspective of own goalie # Blue team setup if self.my.teamColor == Constants.teamColor.TEAM_BLUE: # Yellow goal self.oppGoalRightPost = self.yglp self.oppGoalLeftPost = self.ygrp # Blue Goal self.myGoalLeftPost = self.bglp self.myGoalRightPost = self.bgrp # Yellow team setup else: # Yellow goal self.myGoalLeftPost = self.yglp self.myGoalRightPost = self.ygrp # Blue Goal self.oppGoalRightPost = self.bglp self.oppGoalLeftPost = self.bgrp # Since, for ex. bgrp points to the same things as myGoalLeftPost, # we can set these regardless of our team color self.myGoalLeftPost.associateWithRelativeLandmark( Constants.LANDMARK_MY_GOAL_LEFT_POST) self.myGoalRightPost.associateWithRelativeLandmark( Constants.LANDMARK_MY_GOAL_RIGHT_POST) self.oppGoalLeftPost.associateWithRelativeLandmark( Constants.LANDMARK_OPP_GOAL_LEFT_POST) self.oppGoalRightPost.associateWithRelativeLandmark( Constants.LANDMARK_OPP_GOAL_RIGHT_POST) # Build a list of all of the field objects with respect to team color self.myFieldObjects = [self.yglp, self.ygrp, self.bglp, self.bgrp] def initTeamMembers(self): self.teamMembers = [] for i in xrange(Constants.NUM_PLAYERS_PER_TEAM): mate = TeamMember.TeamMember(self) mate.playerNumber = i + 1 self.teamMembers.append(mate) ## ##--------------CONTROL METHODS---------------## ## def profile(self): if self.counter == 0: cProfile.runctx('self.run()', self.__dict__, locals(), 'pythonStats') self.p = pstats.Stats('pythonStats') elif self.counter < 3000: self.p.add('pythonStats') cProfile.runctx('self.run()', self.__dict__, locals(), 'pythonStats') elif self.counter == 3000: self.p.strip_dirs() self.p.sort_stats('cumulative') ## print 'PYTHON STATS:' ## self.p.print_stats() ## print 'OUTGOING CALLEES:' ## self.p.print_callees() ## print 'OUTGOING CALLEES:' ## self.p.print_callers() self.p.dump_stats('pythonStats') self.counter += 1 def run(self): """ Main control loop called every TIME_STEP milliseconds """ # order here is very important # Update Environment self.time = time.time() self.sonar.updateSensors(self.sensors) # Communications update self.updateComm() # Update objects self.updateObjects() # Behavior stuff self.gameController.run() self.fallController.run() self.updatePlaybook() self.player.run() self.tracker.run() self.nav.run() # Kinda of a hack... # check and set loc boolean if ((self.my.teamColor == Constants.teamColor.TEAM_BLUE and self.loc.x > Constants.MIDFIELD_X - Constants.CENTER_CIRCLE_RADIUS) or (self.my.teamColor == Constants.teamColor.TEAM_RED and self.loc.x < Constants.MIDFIELD_X + Constants.CENTER_CIRCLE_RADIUS)): self.onOwnFieldSide = False #Set LEDS self.leds.processLeds() # Broadcast Report for Teammates self.setPacketData() # Update any logs we have self.out.updateLogs() def updateComm(self): temp = self.comm.latestComm() for packet in temp: if len(packet) == Constants.NUM_PACKET_ELEMENTS: packet = Packet.Packet(packet) if packet.playerNumber != self.my.playerNumber: self.teamMembers[packet.playerNumber - 1].update(packet) if Constants.LOG_COMM: self.out.logRComm(packet) # update the activity of our teammates here # active field is set to true upon recipt of a new packet. for mate in self.teamMembers: if (mate.active and mate.isDead()): mate.active = False def updateObjects(self): """ Update estimates of robot and ball positions on the field """ self.ball.update() self.my.update() self.yglp.setBest() self.ygrp.setBest() self.bglp.setBest() self.bgrp.setBest() def updatePlaybook(self): """ updates self.play to the new play """ self.playbook.update(self.play) # move to comm def setPacketData(self): # Team color, team number, and player number are all appended to this # list by the underlying comm module implemented in C++ loc = self.loc self.comm.setData(loc.x, loc.y, loc.h, loc.xUncert, loc.yUncert, loc.hUncert, loc.ballX, loc.ballY, loc.ballXUncert, loc.ballYUncert, self.ball.loc.dist, self.ball.loc.bearing, self.ball.vis.on, self.play.role, self.play.subRole, self.playbook.pb.me.chaseTime, loc.ballVelX, loc.ballVelY) # TODO: remove this and log through C++ and the Logger instead. if Constants.LOG_COMM: packet = Packet.Packet( (TeamConfig.TEAM_NUMBER, TeamConfig.PLAYER_NUMBER, self.my.teamColor, loc.x, loc.y, loc.h, loc.xUncert, loc.yUncert, loc.hUncert, loc.ballX, loc.ballY, loc.ballXUncert, loc.ballYUncert, self.ball.loc.dist, self.ball.loc.bearing, self.ball.vis.on, self.play.role, self.play.subRole, self.playbook.pb.me.chaseTime, loc.ballVelX, loc.ballVelY)) self.out.logSComm(packet) # TODO: Take this out once new comm is in... def activeTeamMates(self): activeMates = 0 for i in xrange(Constants.NUM_PLAYERS_PER_TEAM): mate = self.teamMembers[i] if mate.active: activeMates += 1 return activeMates def resetInitialLocalization(self): """ Reset loc according to team number and team color. Note: Loc uses truly global coordinates. """ if self.my.teamColor == Constants.teamColor.TEAM_BLUE: if self.my.playerNumber == 1: self.loc.resetLocTo( Constants.BLUE_GOALBOX_RIGHT_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 2: self.loc.resetLocTo( Constants.BLUE_GOALBOX_RIGHT_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 3: self.loc.resetLocTo( Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 4: self.loc.resetLocTo( Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) else: if self.my.playerNumber == 1: self.loc.resetLocTo( Constants.YELLOW_GOALBOX_LEFT_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 2: self.loc.resetLocTo( Constants.YELLOW_GOALBOX_LEFT_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 3: self.loc.resetLocTo( Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 4: self.loc.resetLocTo( Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) # Loc knows the side of the field now. Reset accordingly. self.onOwnFieldSide = True #@todo: HACK HACK HACK Mexico 2012 to make sure we still re-converge properly even if #we get manually positioned #should make this nicer (or at least the locations) def resetSetLocalization(self): gameSetResetUncertainties = _localization.LocNormalParams(50, 200, 1.0) if self.my.teamColor == Constants.teamColor.TEAM_BLUE: # # if self.my.playerNumber == 1: # # self.loc.resetLocTo(Constants.BLUE_GOALBOX_RIGHT_X, # # Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, # # Constants.HEADING_UP) # if self.gameController.ownKickOff: # self.loc.resetLocTo(Constants.LANDMARK_BLUE_GOAL_CROSS_X, # Constants.CENTER_FIELD_Y, # 0, # gameSetResetUncertainties) # else: # self.loc.resetLocTo(Constants.BLUE_GOALBOX_RIGHT_X, # Constants.CENTER_FIELD_Y, # 0, # gameSetResetUncertainties) self.loc.resetLocToSide(True) else: # if self.gameController.ownKickOff: # self.loc.resetLocTo(Constants.LANDMARK_YELLOW_GOAL_CROSS_X, # Constants.CENTER_FIELD_Y, # 180, # gameSetResetUncertainties) # else: # self.loc.resetLocTo(Constants.YELLOW_GOALBOX_LEFT_X, # Constants.CENTER_FIELD_Y, # 180, # gameSetResetUncertainties) self.loc.resetLocToSide(False) def resetLocalizationFromPenalty(self): """ Resets localization to both possible locations, depending on team color. """ if self.my.teamColor == Constants.teamColor.TEAM_BLUE: self.loc.resetLocTo(Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0), _localization.LocNormalParams(15.0, 15.0, 1.0)) else: self.loc.resetLocTo(Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0), _localization.LocNormalParams(15.0, 15.0, 1.0)) # Loc knows the side of the field now. Reset accordingly. self.onOwnFieldSide = True def resetGoalieLocalization(self): """ Resets the goalie's localization to the manual position in the goalbox. """ if self.my.teamColor == Constants.teamColor.TEAM_BLUE: self.loc.resetLocTo(Constants.FIELD_WHITE_LEFT_SIDELINE_X, Constants.MIDFIELD_Y, Constants.HEADING_RIGHT, _localization.LocNormalParams(15.0, 15.0, 1.0)) else: self.loc.resetLocTo(Constants.FIELD_WHITE_RIGHT_SIDELINE_X, Constants.MIDFIELD_Y, Constants.HEADING_LEFT, _localization.LocNormalParams(15.0, 15.0, 1.0)) # Loc knows the side of the field now. Reset accordingly. self.onOwnFieldSide = True #TODO: write this method! def resetPenaltyKickLocalization(self): pass
class Brain(object): """ Class brings all of our components together and runs the behaviors """ def __init__(self): """ Class constructor """ self.counter = 0 self.time = time.time() self.on = True # Output Class self.out = NaoOutput.NaoOutput(self) # Setup nao modules inside brain for easy access self.vision = vision.vision self.sensors = sensors.sensors self.logger = loggingBoard.loggingBoard self.comm = comm.inst self.comm.gc.team = TeamConfig.TEAM_NUMBER self.comm.gc.player = TeamConfig.PLAYER_NUMBER #initalize the leds #print leds self.leds = Leds.Leds(self) self.speech = _speech.speech # Initialize motion interface and module references self.motion = motion.MotionInterface() self.motionModule = motion # Get the pointer to the C++ RoboGuardian object for use with Python self.roboguardian = _roboguardian.roboguardian self.roboguardian.enableFallProtection(True) # Get our reference to the C++ localization system self.loc = Loc() # Retrieve our robot identification and set per-robot parameters self.CoA = robots.get_certificate() self.CoA.setRobotGait(self.motion) # coa is Certificate of Authenticity (to keep things short) self.out.printf(self.CoA) self.out.printf("GC: I am on team "+str(TeamConfig.TEAM_NUMBER)) self.out.printf("GC: I am player "+str(TeamConfig.PLAYER_NUMBER)) # Initialize various components self.my = MyInfo(self.loc) # Functional Variables self.my.playerNumber = self.comm.gc.player if self.comm.gc.color == GameController.TEAM_BLUE: self.my.teamColor = Constants.teamColor.TEAM_BLUE else: self.my.teamColor = Constants.teamColor.TEAM_RED # Information about the environment self.initFieldObjects() self.initTeamMembers() self.ball = Ball(self.vision.ball, self.loc, self.my) self.play = Play.Play() self.sonar = Sonar.Sonar() if Constants.LOG_COMM: self.out.startCommLog() # Stability data self.stability = Stability.Stability(self.sensors) # FSAs self.player = Switch.selectedPlayer.SoccerPlayer(self) self.tracker = HeadTracking.HeadTracking(self) self.nav = Navigator.Navigator(self) self.playbook = PBInterface.PBInterface(self) self.kickDecider = KickDecider.KickDecider(self) self.gameController = GameController.GameController(self) self.fallController = FallController.FallController(self) def initFieldObjects(self): """ Build our set of Field Objects which are team specific compared to the generic forms used in the vision system """ # Build instances of the vision based field objects # Left post is on that goalie's left # Note: As of 6/8/12, ygrp holds info about ambiguous posts # Yellow goal left and right posts self.yglp = FieldObject(self.vision.yglp, Constants.vis_landmark.VISION_YGLP, self.loc) self.ygrp = FieldObject(self.vision.ygrp, Constants.vis_landmark.VISION_YGRP, self.loc) # Blue Goal left and right posts self.bglp = FieldObject(self.vision.bglp, Constants.vis_landmark.VISION_BGLP, self.loc) self.bgrp = FieldObject(self.vision.bgrp, Constants.vis_landmark.VISION_BGRP, self.loc) # Now we build the field objects to be based on our team color self.makeFieldObjectsRelative() def makeFieldObjectsRelative(self): """ Builds a list of fieldObjects based on their relative names to the robot Needs to be called when team color is determined """ # Note: corner directions are relative to perspective of own goalie # Blue team setup if self.my.teamColor == Constants.teamColor.TEAM_BLUE: # Yellow goal self.oppGoalRightPost = self.yglp self.oppGoalLeftPost = self.ygrp # Blue Goal self.myGoalLeftPost = self.bglp self.myGoalRightPost = self.bgrp # Yellow team setup else: # Yellow goal self.myGoalLeftPost = self.yglp self.myGoalRightPost = self.ygrp # Blue Goal self.oppGoalRightPost = self.bglp self.oppGoalLeftPost = self.bgrp # Since, for ex. bgrp points to the same things as myGoalLeftPost, # we can set these regardless of our team color self.myGoalLeftPost.associateWithRelativeLandmark( Constants.LANDMARK_MY_GOAL_LEFT_POST) self.myGoalRightPost.associateWithRelativeLandmark( Constants.LANDMARK_MY_GOAL_RIGHT_POST) self.oppGoalLeftPost.associateWithRelativeLandmark( Constants.LANDMARK_OPP_GOAL_LEFT_POST) self.oppGoalRightPost.associateWithRelativeLandmark( Constants.LANDMARK_OPP_GOAL_RIGHT_POST) # Build a list of all of the field objects with respect to team color self.myFieldObjects = [self.yglp, self.ygrp, self.bglp, self.bgrp] def initTeamMembers(self): self.teamMembers = [] for i in xrange(Constants.NUM_PLAYERS_PER_TEAM): mate = TeamMember.TeamMember(self) mate.playerNumber = i + 1 self.teamMembers.append(mate) ## ##--------------CONTROL METHODS---------------## ## def profile(self): if self.counter == 0: cProfile.runctx('self.run()', self.__dict__, locals(), 'pythonStats') self.p = pstats.Stats('pythonStats') elif self.counter < 3000: self.p.add('pythonStats') cProfile.runctx('self.run()', self.__dict__, locals(), 'pythonStats') elif self.counter == 3000: self.p.strip_dirs() self.p.sort_stats('cumulative') ## print 'PYTHON STATS:' ## self.p.print_stats() ## print 'OUTGOING CALLEES:' ## self.p.print_callees() ## print 'OUTGOING CALLEES:' ## self.p.print_callers() self.p.dump_stats('pythonStats') self.counter += 1 def run(self): """ Main control loop called every TIME_STEP milliseconds """ # order here is very important # Update Environment self.time = time.time() self.sonar.updateSensors(self.sensors) # Communications update self.updateComm() # Update objects self.updateObjects() # Behavior stuff self.gameController.run() self.fallController.run() self.updatePlaybook() self.player.run() self.tracker.run() self.nav.run() # Kinda of a hack... # check and set loc boolean if ((self.my.teamColor == Constants.teamColor.TEAM_BLUE and self.loc.x > Constants.MIDFIELD_X - Constants.CENTER_CIRCLE_RADIUS) or (self.my.teamColor == Constants.teamColor.TEAM_RED and self.loc.x < Constants.MIDFIELD_X + Constants.CENTER_CIRCLE_RADIUS)): self.onOwnFieldSide = False #Set LEDS self.leds.processLeds() # Broadcast Report for Teammates self.setPacketData() # Update any logs we have self.out.updateLogs() def updateComm(self): temp = self.comm.latestComm() for packet in temp: if len(packet) == Constants.NUM_PACKET_ELEMENTS: packet = Packet.Packet(packet) if packet.playerNumber != self.my.playerNumber: self.teamMembers[packet.playerNumber-1].update(packet) if Constants.LOG_COMM: self.out.logRComm(packet) # update the activity of our teammates here # active field is set to true upon recipt of a new packet. for mate in self.teamMembers: if (mate.active and mate.isDead()): mate.active = False def updateObjects(self): """ Update estimates of robot and ball positions on the field """ self.ball.update() self.my.update() self.yglp.setBest() self.ygrp.setBest() self.bglp.setBest() self.bgrp.setBest() def updatePlaybook(self): """ updates self.play to the new play """ self.playbook.update(self.play) # move to comm def setPacketData(self): # Team color, team number, and player number are all appended to this # list by the underlying comm module implemented in C++ loc = self.loc self.comm.setData(loc.x, loc.y, loc.h, loc.xUncert, loc.yUncert, loc.hUncert, loc.ballX, loc.ballY, loc.ballXUncert, loc.ballYUncert, self.ball.loc.dist, self.ball.loc.bearing, self.ball.vis.on, self.play.role, self.play.subRole, self.playbook.pb.me.chaseTime, loc.ballVelX, loc.ballVelY) # TODO: remove this and log through C++ and the Logger instead. if Constants.LOG_COMM: packet = Packet.Packet((TeamConfig.TEAM_NUMBER, TeamConfig.PLAYER_NUMBER, self.my.teamColor, loc.x, loc.y, loc.h, loc.xUncert, loc.yUncert, loc.hUncert, loc.ballX, loc.ballY, loc.ballXUncert, loc.ballYUncert, self.ball.loc.dist, self.ball.loc.bearing, self.ball.vis.on, self.play.role, self.play.subRole, self.playbook.pb.me.chaseTime, loc.ballVelX, loc.ballVelY)) self.out.logSComm(packet) # TODO: Take this out once new comm is in... def activeTeamMates(self): activeMates = 0 for i in xrange(Constants.NUM_PLAYERS_PER_TEAM): mate = self.teamMembers[i] if mate.active: activeMates += 1 return activeMates def resetInitialLocalization(self): """ Reset loc according to team number and team color. Note: Loc uses truly global coordinates. """ if self.my.teamColor == Constants.teamColor.TEAM_BLUE: if self.my.playerNumber == 1: self.loc.resetLocTo(Constants.BLUE_GOALBOX_RIGHT_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 2: self.loc.resetLocTo(Constants.BLUE_GOALBOX_RIGHT_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 3: self.loc.resetLocTo(Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 4: self.loc.resetLocTo(Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) else: if self.my.playerNumber == 1: self.loc.resetLocTo(Constants.YELLOW_GOALBOX_LEFT_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 2: self.loc.resetLocTo(Constants.YELLOW_GOALBOX_LEFT_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 3: self.loc.resetLocTo(Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, _localization.LocNormalParams(15.0, 15.0, 1.0)) elif self.my.playerNumber == 4: self.loc.resetLocTo(Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0)) # Loc knows the side of the field now. Reset accordingly. self.onOwnFieldSide = True #@todo: HACK HACK HACK Mexico 2012 to make sure we still re-converge properly even if #we get manually positioned #should make this nicer (or at least the locations) def resetSetLocalization(self): gameSetResetUncertainties = _localization.LocNormalParams(50, 200, 1.0) if self.my.teamColor == Constants.teamColor.TEAM_BLUE: # # if self.my.playerNumber == 1: # # self.loc.resetLocTo(Constants.BLUE_GOALBOX_RIGHT_X, # # Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, # # Constants.HEADING_UP) # if self.gameController.ownKickOff: # self.loc.resetLocTo(Constants.LANDMARK_BLUE_GOAL_CROSS_X, # Constants.CENTER_FIELD_Y, # 0, # gameSetResetUncertainties) # else: # self.loc.resetLocTo(Constants.BLUE_GOALBOX_RIGHT_X, # Constants.CENTER_FIELD_Y, # 0, # gameSetResetUncertainties) self.loc.resetLocToSide(True) else: # if self.gameController.ownKickOff: # self.loc.resetLocTo(Constants.LANDMARK_YELLOW_GOAL_CROSS_X, # Constants.CENTER_FIELD_Y, # 180, # gameSetResetUncertainties) # else: # self.loc.resetLocTo(Constants.YELLOW_GOALBOX_LEFT_X, # Constants.CENTER_FIELD_Y, # 180, # gameSetResetUncertainties) self.loc.resetLocToSide(False) def resetLocalizationFromPenalty(self): """ Resets localization to both possible locations, depending on team color. """ if self.my.teamColor == Constants.teamColor.TEAM_BLUE: self.loc.resetLocTo(Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, Constants.LANDMARK_BLUE_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0), _localization.LocNormalParams(15.0, 15.0, 1.0)) else: self.loc.resetLocTo(Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_BOTTOM_SIDELINE_Y, Constants.HEADING_UP, Constants.LANDMARK_YELLOW_GOAL_CROSS_X, Constants.FIELD_WHITE_TOP_SIDELINE_Y, Constants.HEADING_DOWN, _localization.LocNormalParams(15.0, 15.0, 1.0), _localization.LocNormalParams(15.0, 15.0, 1.0)) # Loc knows the side of the field now. Reset accordingly. self.onOwnFieldSide = True def resetGoalieLocalization(self): """ Resets the goalie's localization to the manual position in the goalbox. """ if self.my.teamColor == Constants.teamColor.TEAM_BLUE: self.loc.resetLocTo(Constants.FIELD_WHITE_LEFT_SIDELINE_X, Constants.MIDFIELD_Y, Constants.HEADING_RIGHT, _localization.LocNormalParams(15.0, 15.0, 1.0)) else: self.loc.resetLocTo(Constants.FIELD_WHITE_RIGHT_SIDELINE_X, Constants.MIDFIELD_Y, Constants.HEADING_LEFT, _localization.LocNormalParams(15.0, 15.0, 1.0)) # Loc knows the side of the field now. Reset accordingly. self.onOwnFieldSide = True #TODO: write this method! def resetPenaltyKickLocalization(self): pass
class Game: WIDTH = 640 HEIGHT = 480 OFFSET = 20 clock = pygame.time.Clock() FPS = 200 def __init__(self, caption='Server'): pygame.init() pygame.font.init() self.paddle1 = PaddlePlayer(self.WIDTH, self.HEIGHT, self.OFFSET) # player self.paddle2 = PaddleEnemy(self.WIDTH, self.HEIGHT, self.WIDTH - 40) # bot self.b = Ball(self.WIDTH, self.HEIGHT) self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT)) pygame.display.set_caption(caption) self.running = True self.font = pygame.font.SysFont('Arial', 30) self.local = False def handle_events(self): for event in pygame.event.get(): if event.type == QUIT: pygame.quit() self.running = 0 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: self.paddle1.KEYUP = True self.paddle1.direction = -1 elif event.key == pygame.K_DOWN: self.paddle1.KEYUP = True self.paddle1.direction = 1 elif event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: self.paddle1.KEYUP = False self.paddle1.direction = 0 def move_objects(self, autonomy=True): self.b.move(self.screen) self.paddle1.move(self.screen, self.b, autonomy=autonomy) self.paddle1.collision(self.b, self.screen) if self.local or autonomy: self.paddle2.move(self.screen, self.b) self.paddle2.collision(self.b, self.screen) def run(self, autonomy=True, move=True): if not self.running: return self.clock.tick(self.FPS) self.handle_events() if move: self.move_objects(autonomy) self.show() def show_background(self, width=10, height=20, gap=10): self.screen.fill(colors.get('gray')) lines = self.screen.get_height() // height color = colors.get('white') y = gap // 2 for i in range(lines): pygame.draw.rect( self.screen, color, (self.screen.get_width() // 2 - width, y, width, height)) y += height + gap def show_objects(self): self.b.show(self.screen) self.paddle1.show(self.screen) self.paddle2.show(self.screen) def draw_score(self): score1 = self.paddle2.score score2 = self.paddle1.score surface1 = self.font.render(str(score1), False, (0, 0, 0)) surface2 = self.font.render(str(score2), False, (0, 0, 0)) self.screen.blit(surface1, (self.screen.get_width() // 4, 0)) self.screen.blit(surface2, (self.screen.get_width() // 4 * 3 - 30, 0)) def show(self): self.show_background() self.show_objects() self.draw_score() pygame.display.flip() def move_player(self, value): self.paddle1.move_by_value(value, self.screen) def move_enemy(self, value): self.paddle2.move_by_value(value, self.screen) def get_info(self): game_info = { 'player_y': self.paddle1.y, 'enemy_y': self.paddle2.y, 'ball_pos': (self.b.x, self.b.y) } return game_info def update(self, game_info): print(type(game_info)) if type(game_info) == dict: self.paddle1.y = game_info['player_y'] self.paddle2.y = game_info['enemy_y'] self.b.x, self.b.y = game_info['ball_pos']
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from drawer import WindowDrawer, MP4Drawer from region import Region from move import StandardMove from objects import Ball, Trace, Area if __name__ == '__main__': # drawer = WindowDrawer() drawer = MP4Drawer() region = Region([[-0.8, -0.8], [-0.8, 0.8], [0.8, 0.8], [0.8, -0.8]]) move = StandardMove([0.5, 0.5], [-0.5, 0], [0, -0.3]) ball = Ball(move, region, 0.1) trace = Trace(ball) area = Area(move, region) drawer.add_object(ball) drawer.add_object(trace, color='b') drawer.add_object(area, color='g') drawer.start()
boss = 0 shoot = 0 #throws error is window is small if wxcor < 140 or wycor < 40: print("terminal size is too small") time.sleep(3) loopvar = 0 print("welcome to BRICK BREAKER 1.0") print("press x to exit") print("press c to continue paused game") print("press a and d to move paddle") print("press s to skip levels") #give paddlewidth as a multiple of 2 everytime paddle = Paddle(int(wxcor / 2) - 5, wycor - 5, 30, 4, 1) ball = Ball(int(wxcor / 2), wycor - 6, 0, 1) bossitem = Boss(int(wxcor / 2) - 5, 5, 20) # bossitem = 0 randomvar = random.choice(randvelocity) ball.setvel(randomvar, -1) # randomloc = random.randint( int(wxcor/2) - 5, wycor-5) # ball.setloc(randomloc, wycor - 6) # print(randomvar) # window.addpaddletoboard(paddle) # window.rendergame() timeout = config.timeouts keyinput = manageinput() time.sleep(4) #test variable test = 0 bossdead = 0
#Standard liraries import sys, time #Third party libraries import pygame #My libraries from objects import Ball, Brick #Initialization pygame.init() screenSize = screenWidth, screenHeight = 320, 240 screen = pygame.display.set_mode(screenSize) tiles = pygame.image.load("sprites.png").convert() collide = [] ball = Ball(tiles, loc=[160, 160]) #player = Player() bricks = [ Brick(tiles, 0, [40, 40]), Brick(tiles, 2, [80, 40]), Brick(tiles, 3, [120, 40]) ] brickRects = [] for brick in bricks: brickRects.append(brick.rect) #Main loop while 1: #Input handling for event in pygame.event.get():
class Brain(object): """ Class brings all of our components together and runs the behaviors """ def __init__(self): """ Class constructor """ self.counter = 0 self.time = time.time() self.on = True # Output Class self.out = NaoOutput.NaoOutput(self) # Setup nao modules inside brain for easy access self.vision = vision.vision self.sensors = sensors.sensors self.logger = loggingBoard.loggingBoard self.comm = comm.inst self.comm.gc.team = TeamConfig.TEAM_NUMBER self.comm.gc.player = TeamConfig.PLAYER_NUMBER #initalize the leds #print leds self.leds = Leds.Leds(self) self.speech = _speech.speech # Initialize motion interface and module references self.motion = motion.MotionInterface() self.motionModule = motion # Get the pointer to the C++ RoboGuardian object for use with Python self.roboguardian = _roboguardian.roboguardian self.roboguardian.enableFallProtection(True) # Get our reference to the C++ localization system self.loc = Loc() # Retrieve our robot identification and set per-robot parameters self.CoA = robots.get_certificate() self.CoA.setRobotGait(self.motion) # coa is Certificate of Authenticity (to keep things short) self.out.printf(self.CoA) self.out.printf("GC: I am on team "+str(TeamConfig.TEAM_NUMBER)) self.out.printf("GC: I am player "+str(TeamConfig.PLAYER_NUMBER)) # Initialize various components self.my = MyInfo(self.loc) # Functional Variables self.my.playerNumber = self.comm.gc.player if self.comm.gc.color == GameController.TEAM_BLUE: self.my.teamColor = Constants.teamColor.TEAM_BLUE else: self.my.teamColor = Constants.teamColor.TEAM_RED # Information about the environment self.initFieldObjects() self.initTeamMembers() self.ball = Ball(self.vision.ball, self.loc, self.my) self.play = Play.Play() self.sonar = Sonar.Sonar() if Constants.LOG_COMM: self.out.startCommLog() # Stability data self.stability = Stability.Stability(self.sensors) # FSAs self.player = Switch.selectedPlayer.SoccerPlayer(self) self.tracker = HeadTracking.HeadTracking(self) self.nav = Navigator.Navigator(self) self.playbook = PBInterface.PBInterface(self) self.kickDecider = KickDecider.KickDecider(self) self.gameController = GameController.GameController(self) self.fallController = FallController.FallController(self) def initFieldObjects(self): """ Build our set of Field Objects which are team specific compared to the generic forms used in the vision system """ # Build instances of the vision based field objects # Left post is on that goalie's left # Yellow goal left and right posts self.yglp = FieldObject(self.vision.yglp, Constants.vis_landmark.VISION_YGLP, self.loc) self.ygrp = FieldObject(self.vision.ygrp, Constants.vis_landmark.VISION_YGRP, self.loc) # Blue Goal left and right posts self.bglp = FieldObject(self.vision.bglp, Constants.vis_landmark.VISION_BGLP, self.loc) self.bgrp = FieldObject(self.vision.bgrp, Constants.vis_landmark.VISION_BGRP, self.loc) # Now we build the field objects to be based on our team color self.makeFieldObjectsRelative() def makeFieldObjectsRelative(self): """ Builds a list of fieldObjects based on their relative names to the robot Needs to be called when team color is determined """ # Note: corner directions are relative to perspective of own goalie # Blue team setup if self.my.teamColor == Constants.teamColor.TEAM_BLUE: # Yellow goal self.oppGoalRightPost = self.yglp self.oppGoalLeftPost = self.ygrp # Blue Goal self.myGoalLeftPost = self.bglp self.myGoalRightPost = self.bgrp # Yellow team setup else: # Yellow goal self.myGoalLeftPost = self.yglp self.myGoalRightPost = self.ygrp # Blue Goal self.oppGoalRightPost = self.bglp self.oppGoalLeftPost = self.bgrp # Since, for ex. bgrp points to the same things as myGoalLeftPost, # we can set these regardless of our team color self.myGoalLeftPost.associateWithRelativeLandmark( Constants.LANDMARK_MY_GOAL_LEFT_POST) self.myGoalRightPost.associateWithRelativeLandmark( Constants.LANDMARK_MY_GOAL_RIGHT_POST) self.oppGoalLeftPost.associateWithRelativeLandmark( Constants.LANDMARK_OPP_GOAL_LEFT_POST) self.oppGoalRightPost.associateWithRelativeLandmark( Constants.LANDMARK_OPP_GOAL_RIGHT_POST) # Build a list of all of the field objects with respect to team color self.myFieldObjects = [self.yglp, self.ygrp, self.bglp, self.bgrp] def initTeamMembers(self): self.teamMembers = [] for i in xrange(Constants.NUM_PLAYERS_PER_TEAM): mate = TeamMember.TeamMember(self) mate.playerNumber = i + 1 self.teamMembers.append(mate) ## ##--------------CONTROL METHODS---------------## ## def profile(self): if self.counter == 0: cProfile.runctx('self.run()', self.__dict__, locals(), 'pythonStats') self.p = pstats.Stats('pythonStats') elif self.counter < 3000: self.p.add('pythonStats') cProfile.runctx('self.run()', self.__dict__, locals(), 'pythonStats') elif self.counter == 3000: self.p.strip_dirs() self.p.sort_stats('cumulative') ## print 'PYTHON STATS:' ## self.p.print_stats() ## print 'OUTGOING CALLEES:' ## self.p.print_callees() ## print 'OUTGOING CALLEES:' ## self.p.print_callers() self.p.dump_stats('pythonStats') self.counter += 1 def run(self): """ Main control loop called every TIME_STEP milliseconds """ # order here is very important # Update Environment self.time = time.time() self.sonar.updateSensors(self.sensors) # Communications update self.updateComm() # Update objects self.update() #Set LEDS self.leds.processLeds() # Behavior stuff self.gameController.run() self.fallController.run() self.updatePlaybook() self.player.run() self.tracker.run() self.nav.run() # Broadcast Report for Teammates self.setPacketData() # Update any logs we have self.out.updateLogs() def updateComm(self): temp = self.comm.latestComm() for packet in temp: if len(packet) == Constants.NUM_PACKET_ELEMENTS: packet = Packet.Packet(packet) if packet.playerNumber != self.my.playerNumber: self.teamMembers[packet.playerNumber-1].update(packet) if Constants.LOG_COMM: self.out.logRComm(packet) # update the activity of our teammates here # active field is set to true upon recipt of a new packet. for mate in self.teamMembers: if (mate.active and mate.isDead()): mate.active = False def update(self): """ Update estimates of robot and ball positions on the field """ self.ball.update() self.my.update() self.yglp.setBest() self.ygrp.setBest() self.bglp.setBest() self.bgrp.setBest() def updatePlaybook(self): """ updates self.play to the new play """ self.playbook.update(self.play) # move to comm def setPacketData(self): # Team color, team number, and player number are all appended to this # list by the underlying comm module implemented in C++ loc = self.loc self.comm.setData(loc.x, loc.y, loc.h, loc.xUncert, loc.yUncert, loc.hUncert, loc.ballX, loc.ballY, loc.ballXUncert, loc.ballYUncert, self.ball.dist, self.ball.bearing, self.play.role, self.play.subRole, self.playbook.pb.me.chaseTime, loc.ballVelX, loc.ballVelY) if Constants.LOG_COMM: packet = Packet.Packet((TeamConfig.TEAM_NUMBER, TeamConfig.PLAYER_NUMBER, self.my.teamColor, loc.x, loc.y, loc.h, loc.xUncert, loc.yUncert, loc.hUncert, loc.ballX, loc.ballY, loc.ballXUncert, loc.ballYUncert, self.ball.dist, self.ball.bearing, self.play.role, self.play.subRole, self.playbook.pb.me.chaseTime, loc.ballVelX, loc.ballVelY)) self.out.logSComm(packet) def resetLocalization(self): """ Reset our localization """ if self.out.loggingLoc: self.out.stopLocLog() self.out.startLocLog() self.loc.reset() def resetGoalieLocalization(self): """ Reset our localization """ if self.out.loggingLoc: self.out.stopLocLog() self.out.startLocLog() if self.my.teamColor == Constants.teamColor.TEAM_BLUE: self.loc.blueGoalieReset() else: self.loc.redGoalieReset()
class Game(Animation): def __init__(self, number, x_range, y_range, width, height, fps=30, background="black", gravity=9.81): super().__init__(width, height, fps, background) allowed_colours = list(self.colours.keys()) allowed_colours.remove('black') self.balls = [ Ball(1, self.colours[choice(allowed_colours)], (randint(40, self.width - 100), 60), id=i, radius=3) for i in range(number) ] self.centre_ball = Ball(2, self.colours["red"], (self.width / 2, self.height / 2), id=69, radius=10) def event_logic(self, event): if event.type == pygame.QUIT: exit() elif event.type == pygame.MOUSEBUTTONDOWN: for ball in self.balls: ball.apply_force([4, 2]) def game_logic(self): selected = None moving = False gravity = [0, 3] for ball in self.balls: #ball.apply_gravity(gravity) #ball.apply_fluid_resistance(1, 0.0001) ball.apply_force([0.1, 0]) force = ball.apply_gravitation_attraction(1, self.centre_ball.mass, self.centre_ball.pos) #self.centre_ball.apply_gravitation_attraction(0.0001, ball.mass, ball.pos) print(force) #if ball.pos[1] == self.height - ball.radius: # ball.apply_friction(0.1, gravity) ball.update() #self.centre_ball.update() #trimmed = trim([0+ball.radius, 0+ball.radius], # [self.width-ball.radius, self.height-ball.radius], # ball.pos) #ball.pos = trimmed[0] #if trimmed[1][0]: # ball.velocity[0] *= -1 #if trimmed[1][1]: # ball.velocity[1] *= -1 print( f"ID: {ball.id}\n\tVelocity: {ball.velocity}\n\tAcceleration: {ball.acceleration}\n\t(x,y): {ball.pos}\n\tmass: {ball.mass}\n\tTouching {ball.pos[1] == self.height - ball.radius}" ) ball.acceleration = np.multiply(ball.acceleration, 0) def display_logic(self): for ball in self.balls: ball.draw(self.screen) self.centre_ball.draw(self.screen)
def update(self, delta_time, scene): # Update the entities self.entities.update(delta_time, self) # Update the projectiles self.projectiles.update(delta_time, self) # Update the balls self.balls.update(delta_time, self) # Update the top particles self.top_particles.update(delta_time) # Update the bottom particles self.bottom_particles.update(delta_time) # Check if an entity has score if self.score: # Wait until all the balls have been removed to reset the scene if len(self.top_particles) == 0 and len(self.balls) == 0: # Check if the stage has ended self.check_score(scene) # Reset score self.score = False # Reset the time for the next ball self.ball_time = self.ball_delay # Add the balls with which the stage began for x, y, radius in self.stage_balls: self.balls.add(Ball(x, y, radius)) else: # Check if the screen have to shake if self.shake: # Stop screen shake if self.shake_time == 0: self.shake = False self.shake_time = self.shake_duration # Reduce time left else: self.shake_time = approach(self.shake_time, 0, 0.06 * delta_time) # Check if a new ball should appear if len(self.balls) < self.max_balls and self.ball_time == 0: # Check if the new ball would collide if collide(self.balls): # If the new ball collides, its appearance is delayed self.ball_time = 60 # Spawn a new ball else: # Reset the time for the next ball self.ball_time = self.ball_delay * len(self.balls) # Add a new ball to the stage self.balls.add(Ball(125, 175, 10)) # Play a sound when a new ball appears random.choice(self.snd_ball).play() # Reduce time left else: self.ball_time = approach(self.ball_time, 0, 0.06 * delta_time)
def main(): clock = pygame.time.Clock() pygame.init() # Some extra variables asseleration = 0.025 speed_game = 30 points = 0 direction = "left_down" # Initializing objects player = Player() ball = Ball() # Adding ball to group balls (that's for collision) balls = pygame.sprite.Group() balls.add(ball) # Making group of all sprites (to blit them later faster) all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ball) running = True screen = pygame.display.set_mode((C.SCREEN_WIDTH, C.SCREEN_HEIGHT)) pygame.display.set_caption("Ping-Pong") font = pygame.font.SysFont('Arial', 800) # Main loop while running: # Check wheather ball hits botoom running = check_collision(player, ball, balls, direction)[0] # Checking events for quiting for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False # User's input pressed_keys = pygame.key.get_pressed() # Updating ackground screen.fill((25, 50, 50)) # Rendering text and drawing it text_points = font.render('{0}'.format(points), True, (100, 100, 100)) text_points_rect = text_points.get_rect(center = (C.SCREEN_WIDTH/2, C.SCREEN_HEIGHT/2)) screen.blit(text_points, text_points_rect) # Updating objects player.update(pressed_keys) ball.update(direction) # Drawing objects for sprite in all_sprites: screen.blit(sprite.surf, sprite.rect) points += check_collision(player, ball, balls, direction)[1] direction = check_collision(player, ball, balls, direction)[2] # flipping and asselereting of framerate pygame.display.flip() if speed_game <+ 120: speed_game += asseleration clock.tick(speed_game) pygame.quit() over.over(points)
def __init__(self): """ Class constructor """ self.counter = 0 self.time = time.time() self.on = True # Output Class self.out = NaoOutput.NaoOutput(self) # Setup nao modules inside brain for easy access self.vision = vision.vision self.sensors = sensors.sensors self.logger = loggingBoard.loggingBoard self.comm = comm.inst self.comm.gc.team = TeamConfig.TEAM_NUMBER self.comm.gc.player = TeamConfig.PLAYER_NUMBER #initalize the leds #print leds self.leds = Leds.Leds(self) self.speech = _speech.speech # Initialize motion interface and module references self.motion = motion.MotionInterface() self.motionModule = motion # Get the pointer to the C++ RoboGuardian object for use with Python self.roboguardian = _roboguardian.roboguardian self.roboguardian.enableFallProtection(True) # Get our reference to the C++ localization system self.loc = Loc() # Retrieve our robot identification and set per-robot parameters self.CoA = robots.get_certificate() self.CoA.setRobotGait(self.motion) # coa is Certificate of Authenticity (to keep things short) self.out.printf(self.CoA) self.out.printf("GC: I am on team "+str(TeamConfig.TEAM_NUMBER)) self.out.printf("GC: I am player "+str(TeamConfig.PLAYER_NUMBER)) # Initialize various components self.my = MyInfo(self.loc) # Functional Variables self.my.playerNumber = self.comm.gc.player if self.comm.gc.color == GameController.TEAM_BLUE: self.my.teamColor = Constants.teamColor.TEAM_BLUE else: self.my.teamColor = Constants.teamColor.TEAM_RED # Information about the environment self.initFieldObjects() self.initTeamMembers() self.ball = Ball(self.vision.ball, self.loc, self.my) self.play = Play.Play() self.sonar = Sonar.Sonar() if Constants.LOG_COMM: self.out.startCommLog() # Stability data self.stability = Stability.Stability(self.sensors) # FSAs self.player = Switch.selectedPlayer.SoccerPlayer(self) self.tracker = HeadTracking.HeadTracking(self) self.nav = Navigator.Navigator(self) self.playbook = PBInterface.PBInterface(self) self.kickDecider = KickDecider.KickDecider(self) self.gameController = GameController.GameController(self) self.fallController = FallController.FallController(self)
def main(): pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCALE = 80 # pixels per meter WIDTH = SCREEN_WIDTH/SCALE HEIGHT = SCREEN_HEIGHT/SCALE SCREEN_CENTRE = Point(WIDTH/2, HEIGHT/2) CENTRE = SCREEN_CENTRE/SCALE DISPLAY = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) CLOCK = pygame.time.Clock() totalTime = 0 GRAVITY = 9.81 helper = Helper(DISPLAY, SCALE, WIDTH, HEIGHT) drawPos = helper.drawPos worldPos = helper.worldPos drawVector = helper.drawVector personImage = pygame.image.load(os.getcwd()+"/person.jpg") personRect = personImage.get_rect() personImage = pygame.transform.scale(personImage, (int(personRect.width*(int(1.8*SCALE)/personRect.height)), int(1.8*SCALE))) moveData = { "lastPos": Point(), "currentPos": Point(CENTRE.x, 0), "lastScreenMousePos": Point(), "mouseHeld": False, "lastVelocity": Vector() } mouseVelocity = Vector() mouseBall = Ball() mouseBall.moveable = False tickerPoints = [] MAX_TICKER_POINTS = 100 TICKER_PERIOD = 0.02 timeSinceLastTicker = 0 ball = Ball() ball.setPos(Point(WIDTH/2, HEIGHT/2)) string = String() string.setConnections(mouseBall, ball) string.active = False while True: DISPLAY.fill(WHITE) deltaT = CLOCK.get_time()/1000 totalTime += deltaT moveData["lastPos"] = Point(moveData["currentPos"]) if not moveData["lastScreenMousePos"] == Point(pygame.mouse.get_pos()): moveData["currentPos"] = Point(worldPos(Point(pygame.mouse.get_pos()))) moveData["lastScreenMousePos"] = Point(pygame.mouse.get_pos()) heldKeys = pygame.key.get_pressed() for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() elif e.type == pygame.KEYDOWN: heldKeys = pygame.key.get_pressed() if (heldKeys[pygame.K_RCTRL] or heldKeys[pygame.K_LCTRL]) and\ (heldKeys[pygame.K_w] or heldKeys[pygame.K_q]): pygame.quit() if (heldKeys[pygame.K_SPACE]): mouseBallDist = moveData["currentPos"].distance(ball.pos) if mouseBallDist > 0: string.toggle() string.length = mouseBallDist elif e.type == pygame.MOUSEBUTTONDOWN: if e.button == 1: moveData["mouseHeld"] = True elif e.type == pygame.MOUSEBUTTONUP: if e.button == 1: moveData["mouseHeld"] = False keyboardMoveSpeed = 1 if heldKeys[pygame.K_a]: moveData["currentPos"] = moveData["currentPos"] - Point(keyboardMoveSpeed*deltaT, 0) elif heldKeys[pygame.K_d]: moveData["currentPos"] = moveData["currentPos"] + Point(keyboardMoveSpeed*deltaT, 0) if heldKeys[pygame.K_w]: moveData["currentPos"] = moveData["currentPos"] + Point(0, keyboardMoveSpeed*deltaT) elif heldKeys[pygame.K_s]: moveData["currentPos"] = moveData["currentPos"] - Point(0, keyboardMoveSpeed*deltaT) if deltaT > 0: moveData["lastVelocity"] = Vector(mouseBall.velocity) mouseVelocity = Vector(((moveData["currentPos"]-moveData["lastPos"])/deltaT).pos()) mouseAcceleration = (mouseVelocity - moveData["lastVelocity"])/deltaT else: mouseVelocity = Vector() mouseAcceleration = Vector() mouseBall.setPos(moveData["currentPos"]) mouseBall.setVelocity(mouseVelocity) #gravity adjustment if heldKeys[pygame.K_i]: GRAVITY = min(30.0,GRAVITY+0.1) elif heldKeys[pygame.K_k]: GRAVITY = max(0.0,GRAVITY-0.1) #ball radius if heldKeys[pygame.K_o]: ball.radius = min(4.0,ball.radius+0.01) elif heldKeys[pygame.K_l]: ball.radius = max(0.1,ball.radius-0.01) #string length if heldKeys[pygame.K_u]: string.length = min(8.0,string.length+0.01) elif heldKeys[pygame.K_j]: string.length = max(0.01,string.length-0.01) #reset all if heldKeys[pygame.K_r]: GRAVITY = 9.81 ball.radius = 0.1 string.length = 2.0 if ball.bottom <= 0: if ball.velocity.y < 0: ball.accelerate(Vector((0, -ball.velocity.y-ball.velocity.y*ball.cor))) else: ball.accelerate(Vector((0, -GRAVITY))*deltaT) #print(ball.velocity) if ball.left <= 0: if ball.velocity.x < 0: ball.accelerate(Vector((-ball.velocity.x-ball.velocity.x*ball.cor, 0))) if ball.right >= WIDTH: if ball.velocity.x > 0: ball.accelerate(Vector((-ball.velocity.x-ball.velocity.x*ball.cor, 0))) string.applyTension(deltaT) if moveData["mouseHeld"]: ball.setPos(moveData["currentPos"]) ball.setVelocity(mouseBall.velocity) ball.setInEquilibrium() else: ball.move(deltaT) string.correctPositions() # === DRAW # draw person DISPLAY.blit(personImage, (-(1/3)*personImage.get_rect().width, SCREEN_HEIGHT-personImage.get_rect().height)) # draw ticker tape if not moveData["mouseHeld"]: timeSinceLastTicker += deltaT if timeSinceLastTicker >= TICKER_PERIOD: tickerPoints.append(Point(ball.pos)) if len(tickerPoints) > MAX_TICKER_POINTS: del tickerPoints[0] timeSinceLastTicker = 0 else: tickerPoints = [] for p in tickerPoints: pygame.draw.circle(DISPLAY, BLUE, drawPos(p), 2, 2) # draw mouse velocity vector drawVector(mouseBall.velocity, moveData["currentPos"], 20, False, BLUE) # velocity vector is scaled so it can be more easily comprehended drawVector(ball.velocity, ball.pos, 10, False, GREEN, 1) # draw ball pygame.draw.circle(DISPLAY, RED, drawPos(ball.pos), int(ball.radius*SCALE), 1) if string.active: pygame.draw.line(DISPLAY, GREEN, drawPos(ball.pos), drawPos(moveData["currentPos"]), 1) font = pygame.font.SysFont("monospace", 15) # render text fps = font.render("{}fps".format(int(CLOCK.get_fps())), 1, BLACK) DISPLAY.blit(fps, (10, 10)) ballVelLabel = font.render("Ball velocity: {:.2f}ms-1".format(ball.velocity.mag), 1, BLACK) DISPLAY.blit(ballVelLabel, (10, 30)) mouseVelLabel = font.render("Mouse velocity: {:.2f}ms-1".format(mouseBall.velocity.mag), 1, BLACK) DISPLAY.blit(mouseVelLabel, (10, 50)) gravityVelLabel = font.render("Gravity: {:.2f}ms-2".format(GRAVITY), 1, BLACK) DISPLAY.blit(gravityVelLabel, (10, 70)) diameterVelLabel = font.render("Ball diameter: {:.2f}m".format(ball.radius*2), 1, BLACK) DISPLAY.blit(diameterVelLabel, (10, 90)) stringVelLabel = font.render("String length: {:.2f}m".format(string.length), 1, BLACK) DISPLAY.blit(stringVelLabel, (10, 110)) #control prompts stringConnect = font.render("Connect string: SPACE", 1, BLACK) DISPLAY.blit(stringConnect, (SCREEN_WIDTH-stringConnect.get_rect().width-10, 10)) stringControl = font.render("String length +/-: U/J", 1, BLACK) DISPLAY.blit(stringControl, (SCREEN_WIDTH-stringConnect.get_rect().width-10, 30)) gravityControl = font.render("Gravity +/-: I/K", 1, BLACK) DISPLAY.blit(gravityControl, (SCREEN_WIDTH-stringConnect.get_rect().width-10, 50)) diameterControl = font.render("Ball diameter +/-: O/L", 1, BLACK) DISPLAY.blit(diameterControl, (SCREEN_WIDTH-stringConnect.get_rect().width-10, 70)) resetAllControl = font.render("Reset all: R", 1, BLACK) DISPLAY.blit(resetAllControl, (SCREEN_WIDTH-stringConnect.get_rect().width-10, 90)) pygame.display.update() CLOCK.tick(120)