コード例 #1
0
ファイル: main.py プロジェクト: marksbrown/breakout_game
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()
コード例 #2
0
ファイル: Brain.py プロジェクト: WangHanbin/nbites
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
コード例 #3
0
ファイル: Brain.py プロジェクト: hoangtuananh/nbites
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()
コード例 #4
0
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
コード例 #5
0
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
コード例 #6
0
ファイル: main_1.py プロジェクト: Pavlik1400/ping_pong
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)
    
コード例 #7
0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(cl_off_black)
    screen.blit(update_fps(), (16, 5))

    if ball.is_colliding_with(left_paddle) or left_paddle.is_colliding_with(
            ball):
        print("Colliding left")
        ball.bounce_x()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        left_paddle.move(dy=-PADDLE_SPEED)
    if keys[pygame.K_s]:
        left_paddle.move(dy=PADDLE_SPEED)
    if keys[pygame.K_UP]:
        left_paddle.move(dy=-PADDLE_SPEED)
    if keys[pygame.K_DOWN]:
        left_paddle.move(dy=PADDLE_SPEED)

    ball.update()
    left_paddle.draw(on=screen)
    right_paddle.draw(on=screen)
    ball.draw(on=screen)

    # --- Limit to 60 frames per second
    clock.tick(FPS)
    pygame.display.flip()
コード例 #8
0
                        angle = 45 * (2 * circle_count - 1)
                        x, y = get_circle_position(angle)
                        circle = Circle(x, y, circle_count, win)
                        circle_group.add(circle)

        if event.type == pygame.MOUSEBUTTONDOWN:
            clicked = False

    if home_page:
        image, rect, angle = rotate_image(r_msg, r_rect, angle)
        win.blit(image, rect)
        win.blit(otate_msg, (120, HEIGHT // 2 - 190))
        win.blit(dash_msg, (140, HEIGHT // 2 - 140))

        ball.alive = True
        ball.update(color, True)

        tap_to_play.update()

    if score_page:
        if score_bg > 40:
            score_bg -= 1
        win.fill((score_bg, score_bg, score_bg))

        if score and score > high_score:
            high_score = score
            new_high_msg.update(shadow=False)

        final_score_msg.update(score, color)

        if close_btn.draw(win):