Ejemplo n.º 1
0
class ContraGame():
    """creating a class to model a game character"""
    def __init__(self):
        """Initialize the game properties"""
        pygame.init()

        self.screen = pygame.display.set_mode((1200, 800))
        self.bg_colour = (200, 175, 220)

        pygame.display.set_caption('Contra')
        self.shooter = Shooter(self)

    def play_game(self):
        """Runs the game with its properties"""

        while True:
            self._check_status()
            self.shooter.update_shooter()
            self._update_visuals()

    def _check_status(self):
        #watch for keyboard and mouse responses
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            #moves the character to right by setting a moving flag
            # to true
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    self.shooter.move_right = True

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        self.shooter.move_left = True

                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_SPACE:
                            self.shooter.jump = True

            #stops the movement of the character by setting a moving
            #flag to false
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    self.shooter.move_right = False

                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT:
                        self.shooter.move_left = False

                    elif event.type == pygame.KEYUP:
                        if event.key == pygame.K_SPACE:
                            self.shooter.jump = False

    def _update_visuals(self):
        self.screen.fill(self.bg_colour)

        self.shooter.blitme()

        pygame.display.flip()
Ejemplo n.º 2
0
    def robotInit(self):
        """
        This function is called upon program startup and
        should be used for any initialization code.
        """
        self.driver_stick = wpilib.Joystick(0)
        self.codriver_stick = wpilib.Joystick(1)

        self.left_shooter_motor = ctre.WPI_TalonSRX(0)
        self.left_drivetrain_motor = ctre.WPI_TalonSRX(1)
        self.right_drivetrain_motor = ctre.WPI_TalonSRX(2)
        self.right_shooter_motor = ctre.WPI_TalonSRX(3)

        self.intake_motor = wpilib.Spark(8)
        self.arm_pivot_motor = wpilib.Spark(6)
        self.arm_lock_motor = wpilib.Spark(5)

        self.timer = wpilib.Timer()
        #self.navx       = navx.AHRS.create_spi()

        self.duration = 20

        self.drivetrain = DriveTrain(self.left_drivetrain_motor,
                                     self.right_drivetrain_motor)
        self.shooter = Shooter(self.intake_motor, self.left_shooter_motor,
                               self.right_shooter_motor)
        self.arm = Arm(self.arm_pivot_motor, self.arm_lock_motor)
    def __init__(self):
        """Initialize the game and create game resources."""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        pygame.display.set_caption("Sideways Shooter")

        # Create an instance to store game statistics, and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.shooter = Shooter(self)
        self.lines = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()
        self.bulletbs = pygame.sprite.Group()
        self.balls = pygame.sprite.Group()
        self.ball2s = pygame.sprite.Group()

        self._create_fleet()
        self._create_fleet2()

        # Make the play button.
        self.play_button = PlayButton(self, "Right wheel to play")

        # Make the Settings button.
        self.settings_button = SettingsButton(self, "Settings")

        # Make the setttings menu.
        self.settings_menu = SettingsMenu(self, "fast or slow press y or n")

        # Make the speed button.
        self.speed_button = SpeedButton(self, "you have selected the fast option")

        # Make the second speed button.
        self.speed_button2 = SpeedButton2(self, "You have selected the slower options")
Ejemplo n.º 4
0
class ShooterTest(unittest.TestCase):

	mock_data = []

	def setUp(self):
		self.jake = Shooter('Jake')
		print(self.mock_data)
		self.mock_data = [1, 2, 3, 4, 5]


	def tearDown(self):
		self.mock_data = []


	def test_get_cash(self):
		# jake = Shooter('Jake')
		self.jake.get_cash(500)
		self.assertEqual(self.jake.money, 1500)
		print(self.mock_data)


	def test_greet(self):
		# jake = Shooter('Jake')
		self.assertEqual(self.jake.greet(), 'Hello! How are you?')
		self.jake.money = 50
		self.assertEqual(self.jake.greet(), 'Hello! I need cash')
Ejemplo n.º 5
0
def main():
    if len(sys.argv) == 2:
        movie_name = sys.argv[1]

        print("Start download sub from shooter...")
        sub_searcher = Shooter()
        sub_url = sub_searcher.get_sub_url(movie_name)
        sub_downloader.download_sub(sub_url)
Ejemplo n.º 6
0
    def __init__(self):
        """Initialize the game properties"""
        pygame.init()

        self.screen = pygame.display.set_mode((1200, 800))
        self.bg_colour = (200, 175, 220)

        pygame.display.set_caption('Contra')
        self.shooter = Shooter(self)
Ejemplo n.º 7
0
 def __init__(self, screen):
     self.targets = []
     self.eat_food = []
     self.eat_count = 0
     self.screen = screen
     self.shooter = Shooter(self.screen)
     self.mouth = Mouth(screen)
     self.total_score = 0
     self.final_score = 0
     self.eating = False
     self.chew_timer = 0
     self.spawn_count = 0
    def execute(self, base_path, signal, subjects, window, window_overlap, selector, use_classifiers, with_all_signals, times):
        self.subjects = subjects
        self.window = window
        self.window_overlap = window_overlap
        self.selector = selector
        self.with_all_signals = with_all_signals

        predicts_rf = []
        predicts_clf = []
        predicts_nbrs = []
        predicts_shooter = []
        testings = []

        for sub in subjects:
            print('sujeito = ', sub)
            training_labels, training_features = self.get_data(base_path, signal, sub, 'training')
            testing_labels, testing_features = self.get_data(base_path, signal, sub, 'testing')

            if (np.isscalar(training_features[0])):
                training_features = training_features.reshape(-1,1)
                testing_features = testing_features.reshape(-1,1)

            testings.insert(sub, testing_labels)

            if 'forest' in use_classifiers:
                rf = RandomForestClassifier(n_estimators=100, max_depth=5, oob_score=True)
                rf = rf.fit(training_features, training_labels)
                predictions = rf.predict(testing_features)
                predicts_rf.insert(sub, predictions)
                predicts_rf_subject = predictions

            if 'svm' in use_classifiers:
                clf = svm.SVC(gamma='scale', C=4)
                clf = clf.fit(training_features, training_labels)
                predictions = clf.predict(testing_features)
                predicts_clf.insert(sub, predictions)
                predicts_clf_subject = predictions
        
            if 'knn' in use_classifiers:
                knn = KNeighborsClassifier(n_neighbors=11, weights='distance', algorithm='auto', metric='euclidean')
                knn = knn.fit(training_features, training_labels)
                predictions = knn.predict(testing_features)
                predicts_nbrs.insert(sub, predictions)
                predicts_nbrs_subject = predictions
            
            if 'shooter' in use_classifiers:
                shoot2 = Shooter()
                predictions = shoot2.choose(predicts_rf_subject, predicts_nbrs_subject, predicts_clf_subject)
                predicts_shooter.insert(sub, predictions)

        return predicts_rf, predicts_clf, predicts_nbrs, predicts_shooter, testings
Ejemplo n.º 9
0
 def __init__(self):
     super().__init__()
     self.loader = Loader()
     self.shooter = Shooter()
     self.drive = Drive(config.robotDrive, config.leftJoy, config.hsButton,
                        config.alignButton)
     self.componets = [ self.loader, self.shooter, self.drive ]
    def __init__(self, fullscreen, sceneName=None):
        # Start Panda
        preSetWindowIcon("media/heavy_destruction.ico")
        ShowBase()

        # Some non-gameplay setup.
        self.name = "Heavy Destruction"
        self.version = 1.0
        base.setBackgroundColor(0, 0, 0)
        centerWindow()
        render.setAntialias(AntialiasAttrib.MAuto)
        if fullscreen: toggleFullscreen()
        self.setupKeys()
        self.setupFps()
        self.setupTitle()

        # Setup game objects.
        self.world = World(self)
        self.character = Character(self.world)
        self.cameraHandler = CameraHandler(self.character)
        self.shooter = Shooter(self.character)

        # Select a scene.
        if sceneName == "balls":
            self.scene = scene.FallingBalls(self.world, render,
                                            self.cameraHandler, self.character)
        else:
            self.scene = scene.BasicWall(self.world, render,
                                         self.cameraHandler, self.character)
Ejemplo n.º 11
0
    def __init__(self):
        ## sets dimension of the screen and the background
        pygame.init()
        self.w = 900
        self.h = 600
        self.screen = pygame.display.set_mode((self.w, self.h), pygame.FULLSCREEN)
        self.background = pygame.image.load("background.png")

        ## creates all the objects and lists needed for the game
        self.player = Player(self.w, self.h, self.background)
        self.shooter = Shooter(self.player.x, self.player.y, self.player.d)
        self.shield = Shield(self.player.x, self.player.y, self.player.d)
        self.generator = Generator(self.player.x, self.player.y, self.player.d)
        self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation)
        self.enemies = [Enemy(self.w, self.h)]
        self.enemies_2 = []
        self.counter_enemies_2_dead = 0
        self.collectible = Collectible(self.w, self.h)
        self.ray = Ray(self.w, self.h)

        ## loads energy image and sets its default value
        self.energy_5 = pygame.image.load("energy_5.png")
        self.energy = 100

        ## sets all default values
        self.points = 0
        self.killed_big_enemies = 0
        self.killed_small_enemies = 0
        self.rays_collected = 0
        self.collectibles_collected = 0

        ## initializes fonts and creates the first text
        font = pygame.font.SysFont("comic", 64)
        self.font = pygame.font.SysFont("arial", 10)
        text = font.render("Click to play", True, (255, 255, 255))

        ## loads sound
        self.sound = pygame.mixer.Sound("blip.wav")

        ## sets timer and default timer variables
        self.clock = pygame.time.Clock()
        self.timer = 0
        self.seconds = 0
        self.minutes = 0

        ## manages beginning screen and first inputs
        beginning = True
        while beginning:
            self.screen.fill((0, 0, 0))
            self.screen.blit(text, ((self.w / 2) - 150, (self.h / 2) - 64))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.display.quit()
                if event.type == pygame.MOUSEBUTTONUP:
                    beginning = False
                    self.screen.blit(self.background, (0, 0))
                    self.screen.blit(self.player.images[1], (self.player.x, self.player.y))
                    self.screen.blit(self.shooter.image, (self.shooter.x, self.shooter.y))
                    self.running()
            pygame.display.update()
Ejemplo n.º 12
0
    def robotInit(self):
        super().__init__()
        # Instances of classes

        # Instantiate Subsystems
        #XXX DEBUGGING
        self.drivetrain = Drivetrain(self)
        self.shooter = Shooter(self)
        self.carrier = Carrier(self)
        self.feeder = Feeder(self)
        self.intake = Intake(self)
        #self.winch = Winch(self)
        #self.climber = Climber(self)
        #self.climber_big = Climber_Big(self)
        #self.climber_little = Climber_Little(self)

        # Instantiate Joysticks
        self.left_joy = wpilib.Joystick(1)
        self.right_joy = wpilib.Joystick(2)
        # Instantiate Xbox
        self.xbox = wpilib.Joystick(3)

        # Instantiate OI; must be AFTER joysticks are inited
        self.oi = OI(self)

        self.timer = wpilib.Timer()
Ejemplo n.º 13
0
 def __init__(self):
     super().__init__()
     robot = DriveBot(initSuper=False)
     self.addModule(robot)
     self.addModule(DebugMode(robot))
     self.addModule(Climber(initSuper=False))
     self.addModule(Shooter(initSuper=False))
Ejemplo n.º 14
0
 def prep_shooters(self):
     """Show how many shooters are left."""
     self.shooters = Group()
     for shooter_number in range(self.stats.shooters_left):
         shooter = Shooter(self.ss_game)
         shooter.rect.x = 10 + shooter_number * shooter.rect.width
         shooter.rect.y = 100
         self.shooters.add(shooter)
Ejemplo n.º 15
0
    def robotInit(self):
        """Initialization method for the Frobo class.  Initializes objects needed elsewhere throughout the code."""

        # Initialize Joystick
        self.controller = Joystick(Values.CONTROLLER_ID)

        # Initialize Drive Sub-System
        self.drive = FroboDrive(self, Values.DRIVE_LEFT_MAIN_ID,
                                Values.DRIVE_LEFT_SLAVE_ID,
                                Values.DRIVE_RIGHT_MAIN_ID,
                                Values.DRIVE_RIGHT_SLAVE_ID)

        # Initialize Shooter Sub-System
        self.compressor = wpilib.Compressor()
        self.shooter = Shooter(self, Values.SHOOT_FRONT_ID,
                               Values.SHOOT_BACK_ID,
                               Values.SHOOT_SOLENOID_FORWARD_CHANNEL_ID,
                               Values.SHOOT_SOLENOID_REVERSE_CHANNEL_ID)
    def one_classifier_and_decision(self, selection, number):
        print('Begining ' + str(number) + ' - todos com decisão ' + selection +
              ' ')
        shoot2 = Shooter()

        ecg_predicts_rf, ecg_predicts_clf, ecg_predicts_nbrs, ecg_predicts_shooter, ecg_testings = self.individual(
            'ecg', selection, 0, True, ['svm'])
        eda_predicts_rf, eda_predicts_clf, eda_predicts_nbrs, eda_predicts_shooter, eda_testings = self.individual(
            'eda', selection, 0, True, ['forest'])
        # emg_predicts_rf, emg_predicts_clf, emg_predicts_nbrs, emg_predicts_shooter, emg_testings = self.individual('emg', selection, 0, True, ['svm'])
        resp_predicts_rf, resp_predicts_clf, resp_predicts_nbrs, resp_predicts_shooter, resp_testings = self.individual(
            'resp', selection, 0, True, ['svm'])

        # decision_predicts = []
        # i = 0
        # j = 0
        # for i in range(self.CLASSIFICATION_TIMES):
        #     decision_predicts.insert(i, [])
        #     for j in range(len(self.BASE_SUBJECTS)):
        #         decisao = shoot2.choose(ecg_predicts_clf[i][j], eda_predicts_rf[i][j], emg_predicts_clf[i][j])
        #         decision_predicts[i].insert(j, decisao)

        # evaluate = Evaluator()
        # evaluate.report(self.BASE_SUBJECTS, self.CLASSIFICATION_TIMES, ecg_testings, ecg_predicts_clf, eda_predicts_rf, emg_predicts_clf, decision_predicts, '/Volumes/My Passport/TCC/Resultados3/TODOS_' + str(number) + '_' + selection + '_1.csv')

        decision_predicts2 = []
        i = 0
        j = 0
        for i in range(self.CLASSIFICATION_TIMES):
            decision_predicts2.insert(i, [])
            for j in range(len(self.BASE_SUBJECTS)):
                decisao = shoot2.choose(ecg_predicts_clf[i][j],
                                        eda_predicts_rf[i][j],
                                        resp_predicts_clf[i][j])
                decision_predicts2[i].insert(j, decisao)

        evaluate = Evaluator()
        evaluate.report(
            self.BASE_SUBJECTS, self.CLASSIFICATION_TIMES, ecg_testings,
            ecg_predicts_clf, eda_predicts_rf, resp_predicts_clf,
            decision_predicts2, '/Volumes/My Passport/TCC/Resultados3/TODOS_' +
            str(number) + '_' + selection + '_2.csv')
Ejemplo n.º 17
0
    def update(self):
        has_to_read, _, _ = select([self.gamepad.fd], [], [], 0.01)

        if has_to_read:
            for event in self.gamepad.read():
                if event.type == ecodes.EV_KEY:
                    if event.code == self.LEFT_ARROW_KEY_CODE and event.value == 1:
                        Player.get_instance().running_left = True
                    if event.code == self.LEFT_ARROW_KEY_CODE and event.value == 0:
                        Player.get_instance().running_left = False
                    if event.code == self.RIGHT_ARROW_KEY_CODE and event.value == 1:
                        Player.get_instance().running_right = True
                    if event.code == self.RIGHT_ARROW_KEY_CODE and event.value == 0:
                        Player.get_instance().running_right = False
                    if event.code == self.CIRCLE_KEY_CODE and event.value == 1:
                        Shooter.spawn_bullet(Direction.RIGHT)
                    if event.code == self.SQUARE_KEY_CODE and event.value == 1:
                        Shooter.spawn_bullet(Direction.LEFT)
                    if event.code == self.START_KEY_CODE and event.value == 1:
                        GameManager.get_instance().restart()
Ejemplo n.º 18
0
    def __init__(self):
        super().__init__()

        self.drive_stick = wpilib.Joystick(1)
        self.arm_stick = wpilib.Joystick(2)

        self.front_right_motor = wpilib.Jaguar(2)
        self.front_left_motor = wpilib.Jaguar(1)
        self.back_left_motor = wpilib.Jaguar(3)
        self.back_right_motor = wpilib.Jaguar(4)

        self.intake_wheels_motor = wpilib.Jaguar(10)
        self.intake_arm_motor = wpilib.Jaguar(6)

        self.shooter_servo = wpilib.Servo(7)
        self.shooter_motor = wpilib.Jaguar(5)
        self.encoder = wpilib.Encoder(1, 2, True)

        self.mecanum_drive = MecanumDrive(self.front_right_motor,
                                          self.front_left_motor,
                                          self.back_right_motor,
                                          self.back_left_motor,
                                          self.drive_stick)

        self.intake = Intake(self.intake_wheels_motor, self.intake_arm_motor,
                             self.arm_stick)

        self.shooter_service = ShooterService(self.shooter_motor,
                                              self.shooter_servo,
                                              self.arm_stick)

        self.shooter = Shooter(self.shooter_motor, self.encoder,
                               self.shooter_servo, self.arm_stick,
                               self.shooter_service)

        self.autonomous = Autonomous(self.shooter_service,
                                     self.intake_arm_motor,
                                     self.front_left_motor,
                                     self.front_right_motor,
                                     self.back_left_motor,
                                     self.back_right_motor)
Ejemplo n.º 19
0
def to_shooter(list):
    """
    creates a shooter with a list of a shooter information
    """
    s = Shooter(screen, list[0], list[1])
    for tup in list[2]:
        s.stack.append(Bullet(screen, tup[0], tup[1], tup[2], tup[3],tup[4]))
    s.color = list[3]
    s.angle = list[4]
    s.life = list[5]
    s.score = list[6]
    s.X_BOUND = X_BOUND
    s.Y_BOUND = Y_BOUND
    return s
Ejemplo n.º 20
0
def run_game():
    # determine the pygame window position
    x = 100
    y = 45
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x, y)

    # Initialize game and create a screen object.
    pygame.init()
    programIcon = pygame.image.load('images/covid_ic.png')
    pygame.display.set_icon(programIcon)
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Corona Epidemic")
    # Make the play button.
    play_button = Button(ai_settings, screen, "Play")
    # Create an instance to store game statistics.
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Make a shooter.
    shooter = Shooter(ai_settings, screen)
    # Make a group to store bullets in.
    bullets = Group()
    covids = Group()

    # Create the fleet on covids.
    gf.create_fleet(ai_settings, screen, shooter, covids)


    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, shooter, covids, bullets)

        if stats.game_active:
            shooter.update()
            gf.update_bullets(ai_settings, screen, stats, sb, shooter, covids, bullets)
            gf.update_covids(ai_settings, screen, stats, sb, shooter, covids, bullets)

        gf.update_screen(ai_settings, screen, stats, sb, shooter, covids, bullets, play_button)
Ejemplo n.º 21
0
  def __init__(self):
    super().__init__()

    self.drive_stick = wpilib.Joystick(1)
    self.arm_stick = wpilib.Joystick(2)

    self.front_right_motor = wpilib.Jaguar(2)
    self.front_left_motor = wpilib.Jaguar(1)
    self.back_left_motor = wpilib.Jaguar(3)
    self.back_right_motor = wpilib.Jaguar(4)

    self.intake_wheels_motor = wpilib.Jaguar(10)
    self.intake_arm_motor = wpilib.Jaguar(6)

    self.shooter_servo = wpilib.Servo(7)
    self.shooter_motor = wpilib.Jaguar(5)
    self.encoder = wpilib.Encoder(1, 2, True)

    self.mecanum_drive = MecanumDrive(
        self.front_right_motor,
        self.front_left_motor,
        self.back_right_motor,
        self.back_left_motor,
        self.drive_stick
      )

    self.intake = Intake(self.intake_wheels_motor,
        self.intake_arm_motor,
        self.arm_stick
      )

    self.shooter_service = ShooterService(self.shooter_motor,
        self.shooter_servo,
        self.arm_stick
      )

    self.shooter = Shooter(self.shooter_motor,
        self.encoder,
        self.shooter_servo,
        self.arm_stick,
        self.shooter_service
      )

    self.autonomous = Autonomous(
        self.shooter_service,
        self.intake_arm_motor,
        self.front_left_motor,
        self.front_right_motor,
        self.back_left_motor,
        self.back_right_motor
      )
Ejemplo n.º 22
0
def run_game():
    pygame.init()
    target_settings = Settings()
    screen = pygame.display.set_mode(
        (target_settings.screen_width, target_settings.screen_height))
    pygame.display.set_caption("Shoot The Box")

    play_button = Button(target_settings, screen, "Start")
    stats = GameStats(target_settings)
    sb = Scoreboard(target_settings, screen, stats)
    shooter = Shooter(target_settings, screen)
    target = Target(target_settings, screen)
    bullets = Group()
    while True:
        gf.check_events(target_settings, stats, screen, sb, shooter, target,
                        bullets, play_button)
        if stats.game_active:
            shooter.update()
            gf.update_bullets(target_settings, stats, screen, sb, shooter,
                              target, bullets)
            gf.update_target(target_settings, target)
        gf.update_screen(target_settings, stats, screen, sb, shooter, target,
                         bullets, play_button)
Ejemplo n.º 23
0
    def __init__(self):
        # Setting up the screen
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption('SpaceShooter')

        self.stats = Stats(self)
        self.space_bg = Space(self)
        self.shooter = Shooter(self)
        # Create a list that will store the lasers
        self.lasers = pygame.sprite.Group()
        self.spaceships = pygame.sprite.Group()
        self.display_shooters = pygame.sprite.Group()

        self._create_fleet()
        self._display_shooters()

        self.button = Button(self, 'Play')
        self.quitbutton = QuitButton(self, 'Quit')

        self.sb = Scoreboard(self)
Ejemplo n.º 24
0
def run_game():
    pygame.init()
    sideway_shooter = Settings()
    screen = pygame.display.set_mode((
        sideway_shooter.width, sideway_shooter.height))
    pygame.display.set_caption("__Hjira__")
    shooter = Shooter(screen)
    bullets = Group()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    shooter.moving_up = True
                if event.key == pygame.K_DOWN:
                    shooter.moving_down = True
                elif event.key == pygame.K_SPACE:
                    new_bullet = Bullet(screen, sideway_shooter, shooter)
                    bullets.add(new_bullet)
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    shooter.moving_up = False
                if event.key == pygame.K_DOWN:
                    shooter.moving_down = False
        shooter.update()
        screen.fill(sideway_shooter.bg_color)
        shooter.belitme()
        bullets.update()
        for bullet in bullets.sprites():
            bullet.draw_bullet()
        for bullet in bullets.copy():
            if bullet.rect.top <= 0:
                bullets.remove(bullet)
        print(len(bullets))
        pygame.display.flip()
Ejemplo n.º 25
0
 def __init__(self):
     super().__init__()
     self.setObjectName("Ventana")
     self.setMouseTracking(True)
     self.setGeometry(200, 100, 800, 600)
     self.setStyleSheet("#Ventana {background-image: url('img/bg.gif');background-color:green;}")
     self.setWindowTitle("Zombitch")
     self.shooter = Shooter(parent=self, x=400, y=300)
     self.timer = QtCore.QTimer(self)
     self.timer.timeout.connect(self.create_zombie)
     self.timer.setInterval(1000)
     self.timer.start()
     self.zombies = [Zombie(parent=self, x=0, y=0, target=self.shooter)]
     self.packages = []
     self.__kills = 0
     self.start_time = datetime.now()
     self.status = Status(parent=self)
     self.overlay = Overlay(parent=self)
     self.message = Message(parent=self)
Ejemplo n.º 26
0
class Aimbot(wpilib.SimpleRobot):

  def __init__(self):
    super().__init__()

    self.drive_stick = wpilib.Joystick(1)
    self.arm_stick = wpilib.Joystick(2)

    self.front_right_motor = wpilib.Jaguar(2)
    self.front_left_motor = wpilib.Jaguar(1)
    self.back_left_motor = wpilib.Jaguar(3)
    self.back_right_motor = wpilib.Jaguar(4)

    self.intake_wheels_motor = wpilib.Jaguar(10)
    self.intake_arm_motor = wpilib.Jaguar(6)

    self.shooter_servo = wpilib.Servo(7)
    self.shooter_motor = wpilib.Jaguar(5)
    self.encoder = wpilib.Encoder(1, 2, True)

    self.mecanum_drive = MecanumDrive(
        self.front_right_motor,
        self.front_left_motor,
        self.back_right_motor,
        self.back_left_motor,
        self.drive_stick
      )

    self.intake = Intake(self.intake_wheels_motor,
        self.intake_arm_motor,
        self.arm_stick
      )

    self.shooter_service = ShooterService(self.shooter_motor,
        self.shooter_servo,
        self.arm_stick
      )

    self.shooter = Shooter(self.shooter_motor,
        self.encoder,
        self.shooter_servo,
        self.arm_stick,
        self.shooter_service
      )

    self.autonomous = Autonomous(
        self.shooter_service,
        self.intake_arm_motor,
        self.front_left_motor,
        self.front_right_motor,
        self.back_left_motor,
        self.back_right_motor
      )

  def Autonomous(self):

    self.GetWatchdog().SetEnabled(False)
    self.autonomous.reset()

    while self.IsAutonomous() and self.IsEnabled():
      self.autonomous.iterate()
      wpilib.Wait(0.01)

  def OperatorControl(self):

    dog = self.GetWatchdog()
    dog.SetEnabled(True)
    dog.SetExpiration(0.25)

    while self.IsOperatorControl() and self.IsEnabled():
      dog.Feed()

      self.mecanum_drive.iterate()
      self.intake.iterate()
      self.shooter.iterate()
      self.shooter_service.iterate()

      wpilib.Wait(0.04)
Ejemplo n.º 27
0
    for mushroom in range(mushrooms):
        newX = randrange(0, width)
        newY = randrange(0, height)
        mushroomList.append(Mushroom([newX,newY]))
    return mushroomList

pygame.init()

size = width, height = 800, 600
black = 0, 0, 0
screen = pygame.display.set_mode(size)
pos = [300,400]
imageLocation = "./images/shooter.png"
Status = Enum('Status', 'win lose')

shooter = Shooter(imageLocation, pos, width, height)
centipede = Centipede([-1,0],[500,1], width, height, 13)

allSpriteGroup = pygame.sprite.Group()
allSpriteGroup.add(shooter)
allSpriteGroup.add(centipede)

# A group containing all of the lasers the Shooter shoots
laserGroup = pygame.sprite.Group()
# A group containing all mushrooms in the game
mushroomGroup = pygame.sprite.Group()
mushroomGroup.add(randomlyGenerateMushrooms(width, height))

# All the non player character sprites
npcGroups = [laserGroup, centipede, mushroomGroup]
Ejemplo n.º 28
0
class Frobo(wpilib.IterativeRobot):
    """Control code for Frobo, the 2013 Competition Robot of FRC Team 2403 (Plasma Robotics)"""
    def robotInit(self):
        """Initialization method for the Frobo class.  Initializes objects needed elsewhere throughout the code."""

        # Initialize Joystick
        self.controller = Joystick(Values.CONTROLLER_ID)

        # Initialize Drive Sub-System
        self.drive = FroboDrive(self, Values.DRIVE_LEFT_MAIN_ID,
                                Values.DRIVE_LEFT_SLAVE_ID,
                                Values.DRIVE_RIGHT_MAIN_ID,
                                Values.DRIVE_RIGHT_SLAVE_ID)

        # Initialize Shooter Sub-System
        self.compressor = wpilib.Compressor()
        self.shooter = Shooter(self, Values.SHOOT_FRONT_ID,
                               Values.SHOOT_BACK_ID,
                               Values.SHOOT_SOLENOID_FORWARD_CHANNEL_ID,
                               Values.SHOOT_SOLENOID_REVERSE_CHANNEL_ID)

    def robotPeriodic(self):
        pass

    # DISABLED MODE

    def disabledInit(self):
        """Method ran when Frobo first enters the *disabled* mode."""
        self.shooter.disable()

    def disabledPeriodic(self):
        """Method that runs while Frobo is in the *disabled* mode."""
        pass

    # AUTONOMOUS MODE

    def autonomousInit(self):
        """Method ran when Frobo first enters the *autonomous* mode."""
        pass

    def autonomousPeriodic(self):
        """Method that runs while Frobo is in the *autonomous* mode."""
        pass

    # TELEOP MODE

    def teleopInit(self):
        """Method ran when Frobo first enters the *teleop* mode."""
        self.shooter.disable()

    def teleopPeriodic(self):
        """Method that runs while Frobo is in the *teleop* mode."""
        self.drive.fps(power_axis=self.controller.LEFTY,
                       turn_axis=self.controller.RIGHTX)
        self.shooter.update(self.controller)

    # TEST MODE

    def testInit(self):
        """Method ran when Frobo first enters the *test* mode."""
        self.shooter.disable()

    def testPeriodic(self):
        """Method that runs while Frobo is in the *test* mode."""
        self.shooter.update(self.controller)
Ejemplo n.º 29
0
def do_client(new_sock):
    """
    ~main server's loop~
    for each client -
    send his shooter and all shooters in arena after some update, and checks
    """
    me = Shooter(None, 500, 30)
    me.set_new_color()
    while not get_approval(me):
        me.set_new_color()

    me.set_random_position(X_BOUND, Y_BOUND)
    shooters.append(me)

    Done = False
    while not Done:
        try:
            to_send = shooters_to_send(me)

            if me.life <= 0:
                Done = True
                to_send = "LOS"
            elif me.life < 100:
                me.life += 0.01

            to_send = json.dumps(to_send)
            new_sock.send(to_send)

            recv = new_sock.recv(1024)

            if recv == "CLD":  #stands for - CLient Disconnected
                print "Client Disconnected"
                Done = True
            else:
                recv = json.loads(recv)
                me.angle = recv[0]
                presses = recv[1::]
                control_player(presses, me)
                me.move_shot()
                update_shooters(me)
                check_hits(me)

        except:
            print "closing current socket because of technical issues"
            Done = True
    shooters.remove(me)
    new_sock.close()
Ejemplo n.º 30
0
    def __init__(self,
                 imagenDeInicializacion,
                 areaProtegida,
                 areaDeConfirmacion,
                 areaDeInteresPlacas=[[0, 0], [2592, 1944]],
                 framesPorSegundo=10,
                 nombreCarpetaAlmacenamiento='casosReportados',
                 modoDebug=False):
        # REGISTROS AUTOMOVILES:
        self.numeroDePuntosASeguir = 3
        self.miReporte = MiReporte(levelLogging=logging.INFO, nombre=__name__)
        self.areaDeResguardo = AreaDeResguardo(imagenDeInicializacion,
                                               self.numeroDePuntosASeguir,
                                               areaProtegida,
                                               areaDeConfirmacion)
        self.areaDeConfirmacion = np.array(areaDeConfirmacion)
        self.poligonoProtegidoParaVisualizacion = np.array(areaProtegida)

        self.reporteVideo = []  # Minimo 9 frames Maximo 15 frames
        self.misInfracciones = []

        # Parametros auxiliares
        self.numeroDeFrame = 0
        self.framesPorSegundoEnVideo = framesPorSegundo
        self.ultimaVelocidad = 0
        self.widerVideo = 6  # aumenta el numero de frames al inicio y al final del video
        self.formaOndaDebug = []
        self.infraccionesConfirmadas = 0
        self.infraccionesDescartadasPorTiempo = 0
        self.infraccionesDescartadasPorEstacionario = 0
        self.infraccionesDescartadasGiro = 0
        self.numeroInfraccionesTotales = 0

        # Variables de reporte:
        self.reportarDebug = modoDebug
        # El directorio por defecto sera uno u otro en la memoria USB
        # Estas variables son auxiliares para definir la variable que sera de reporte en cuanto se sepa si hay unidad flash introducida

        self.nombreDirectorioLocal = os.getenv(
            'HOME') + '/trafficFlow/prototipo11'
        self.nombreDirectorioUSB = '/media/' + os.getenv('HOME').split(
            '/')[-1] + '/usbName'

        if os.path.exists(self.nombreDirectorioUSB):
            self.carpetaDeReporte = self.nombreDirectorioUSB + '/' + nombreCarpetaAlmacenamiento
            self.miReporte.info(
                'Encontrada unidad USB, guardando informacion en el medio: ' +
                self.carpetaDeReporte)
            self.carpetaDeReporteDebug = self.nombreDirectorioUSB + '/debug'
        else:
            self.carpetaDeReporte = self.nombreDirectorioLocal + '/' + nombreCarpetaAlmacenamiento
            self.miReporte.info(
                'No se detectó unidad USB, guardando archivos de forma local:'
                + self.carpetaDeReporte)
            self.carpetaDeReporteDebug = self.nombreDirectorioLocal + '/casosDebug'

        if not os.path.exists(self.carpetaDeReporte):
            try:
                os.makedirs(self.carpetaDeReporte)
            except Exception as e:
                self.miReporte.error('ERROR, No pude crear el directorio ' +
                                     self.carpetaDeReporteDebug + ' por: ' +
                                     str(e))

        if not os.path.exists(self.carpetaDeReporteDebug):
            try:
                os.makedirs(self.carpetaDeReporteDebug)
            except Exception as e:
                self.miReporte.error('ERROR, No pude crear el directorio ' +
                                     self.carpetaDeReporteDebug + ' por: ' +
                                     str(e))

        # Si estoy en el raspberry creo la clase shooter
        self.miComputadora = os.uname()[1]
        if self.miComputadora == 'raspberrypi':
            #print('ESTOY TRABAJANDO EN LA PI, CREANDO SHOOTER SHOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOTER')
            self.miCamara = Shooter(cutPoly=areaDeInteresPlacas)
            self.miReporte.debug('Creada camara de alta resolucion')

        # Creo las carpetas de reporte actual y para el debug, por ahora la misma
        self.fechaReporte = datetime.datetime.now().strftime(
            '%Y-%m-%d-%H-%M-%S')
        self.carpetaDeReporteActual = self.carpetaDeReporte + '/' + self.fechaReporte
        self.carpetaDeReporteActualDebug = self.carpetaDeReporteDebug + '/' + self.fechaReporte
Ejemplo n.º 31
0
class Game(object):
    def __init__(self):
        ## sets dimension of the screen and the background
        pygame.init()
        self.w = 900
        self.h = 600
        self.screen = pygame.display.set_mode((self.w, self.h), pygame.FULLSCREEN)
        self.background = pygame.image.load("background.png")

        ## creates all the objects and lists needed for the game
        self.player = Player(self.w, self.h, self.background)
        self.shooter = Shooter(self.player.x, self.player.y, self.player.d)
        self.shield = Shield(self.player.x, self.player.y, self.player.d)
        self.generator = Generator(self.player.x, self.player.y, self.player.d)
        self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation)
        self.enemies = [Enemy(self.w, self.h)]
        self.enemies_2 = []
        self.counter_enemies_2_dead = 0
        self.collectible = Collectible(self.w, self.h)
        self.ray = Ray(self.w, self.h)

        ## loads energy image and sets its default value
        self.energy_5 = pygame.image.load("energy_5.png")
        self.energy = 100

        ## sets all default values
        self.points = 0
        self.killed_big_enemies = 0
        self.killed_small_enemies = 0
        self.rays_collected = 0
        self.collectibles_collected = 0

        ## initializes fonts and creates the first text
        font = pygame.font.SysFont("comic", 64)
        self.font = pygame.font.SysFont("arial", 10)
        text = font.render("Click to play", True, (255, 255, 255))

        ## loads sound
        self.sound = pygame.mixer.Sound("blip.wav")

        ## sets timer and default timer variables
        self.clock = pygame.time.Clock()
        self.timer = 0
        self.seconds = 0
        self.minutes = 0

        ## manages beginning screen and first inputs
        beginning = True
        while beginning:
            self.screen.fill((0, 0, 0))
            self.screen.blit(text, ((self.w / 2) - 150, (self.h / 2) - 64))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.display.quit()
                if event.type == pygame.MOUSEBUTTONUP:
                    beginning = False
                    self.screen.blit(self.background, (0, 0))
                    self.screen.blit(self.player.images[1], (self.player.x, self.player.y))
                    self.screen.blit(self.shooter.image, (self.shooter.x, self.shooter.y))
                    self.running()
            pygame.display.update()

    def running(self):
        while True:

            ## manages time
            time_passed = self.clock.tick(30)
            time_seconds = time_passed / 1000.0
            self.timer += 1
            self.seconds += 0.03
            if self.seconds >= 60:
                self.minutes += 1
                self.seconds = 0

            ## gets all the inputs and calls function related to each input
            for event in pygame.event.get():
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_ESCAPE:
                        pygame.display.quit()
                    if event.key == pygame.K_a:
                        self.shield.index -= 1
                        if self.shield.index == -5:
                            self.shield.index = -1
                    elif event.key == pygame.K_j:
                        self.shield.index += 1
                        if self.shield.index == 4:
                            self.shield.index = 0
                    elif event.key == pygame.K_l:
                        self.generator.index += 1
                        if self.generator.index == 4:
                            self.generator.index = 0
                    elif event.key == pygame.K_s:
                        self.generator.index -= 1
                        if self.generator.index == -5:
                            self.generator.index = -1
            key = pygame.key.get_pressed()
            if key[pygame.K_UP]:
                self.player.moves_up(time_seconds)
                self.player.index = 0
            if key[pygame.K_DOWN]:
                self.player.moves_down(time_seconds)
                self.player.index = 1
            if key[pygame.K_LEFT]:
                self.player.moves_left(time_seconds)
                self.player.index = 2
            if key[pygame.K_RIGHT]:
                self.player.moves_right(time_seconds)
                self.player.index = 3

            ## blits the background
            self.screen.blit(self.background, (0, 0))

            ## manages energy and prints it
            if self.energy >= 100:
                self.energy = 100
            if self.energy <= 10:
                self.sound.play()
            if self.energy <= 0:
                self.collectible.finished = True
            for n in xrange(0, self.energy / 5):
                self.screen.blit(self.energy_5, (self.w - 35 - 10 * n, 4))

            ## manages the text (points and time)
            text = self.font.render((str(self.minutes) + ":" + str(self.seconds)), True, (255, 255, 255))
            self.screen.blit(text, (10, 10))
            text = self.font.render(("Points: " + str(self.points)), True, (255, 255, 255))
            self.screen.blit(text, (440, 10))

            ## manages collectibles
            self.collectible.blit_check(self.background, self.timer)
            if self.collectible.blit:
                self.screen.blit(self.collectible.image, (self.collectible.x, self.collectible.y))
                self.collectible_rect = pygame.Rect(self.collectible.x, self.collectible.y, 20, 20)

            ## manages player and collision with collectible
            self.screen.blit(self.player.images[self.player.index], (self.player.x, self.player.y))
            self.player_rect = pygame.Rect(self.player.x, self.player.y, 40, 40)
            if self.collectible.blit:
                if self.player_rect.colliderect(self.collectible_rect):
                    i = self.collectible.index
                    self.collectible = Collectible(self.w, self.h)
                    self.collectible.index = i
                    self.points += 100
                    self.collectibles_collected += 1

            ## manages bullet, checks hits with walls
            self.bullet.moves(self.shooter.x, self.shooter.y)
            if self.bullet.rotate:
                self.bullet.rotates(time_seconds)
                self.screen.blit(self.bullet.rotated_image, self.bullet.image_draw_pos)
                self.bullet.check_shot()
                if self.bullet.shot:
                    self.energy -= 5
            if self.bullet.shot:
                self.screen.blit(self.bullet.rotated_image, (self.bullet.x, self.bullet.y))
                self.bullet.hits_borders(self.background)
            if self.bullet.hits_bg:
                self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation)
            self.bullet_rect = pygame.Rect(self.bullet.x, self.bullet.y, 4, 10)

            ## manages generator
            self.generator.moves(self.player.x, self.player.y, self.player.d)
            self.screen.blit(self.generator.images[self.generator.index], (self.generator.x, self.generator.y))
            generator_rect = pygame.Rect(self.generator.x, self.generator.y, self.generator.w, self.generator.h)

            ## manages shooter
            self.shooter.moves(self.player.x, self.player.y, self.player.d)
            self.shooter.rotates(time_seconds)
            self.screen.blit(self.shooter.rotated_image, self.shooter.image_draw_pos)

            ## manages shield
            self.shield.moves(self.player.x, self.player.y, self.player.d)
            self.screen.blit(self.shield.images[self.shield.index], (self.shield.x, self.shield.y))
            shield_rect = pygame.Rect(self.shield.x, self.shield.y, self.shield.w, self.shield.h)

            ## manages big enemies one by one, checks collisions with bullets, shield and tank
            for n in xrange(0, len(self.enemies)):
                enemy = self.enemies[n]
                enemy.moves(time_seconds)
                enemy.bounces(self.background)
                if enemy.error:
                    self.enemies[n] = Enemy(self.w, self.h)
                self.screen.blit(enemy.image, (enemy.x, enemy.y))
                enemy_rect = pygame.Rect(enemy.x, enemy.y, enemy.d, enemy.d)
                if enemy_rect.colliderect(self.bullet_rect):
                    self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation)
                    self.enemies_2.append(Enemy_2(enemy.x, enemy.y))
                    self.enemies_2.append(Enemy_2(enemy.x, enemy.y))
                    self.enemies_2.append(Enemy_2(enemy.x, enemy.y))
                    enemy.alive = False
                    self.points += 10
                    self.killed_big_enemies += 1
                elif enemy_rect.colliderect(shield_rect):
                    enemy.reverse()
                    self.energy -= 5
                elif enemy_rect.colliderect(self.player_rect):
                    enemy.reverse()
                    self.energy -= 10
            if (self.timer == 30 * 5 or self.timer == 30 * 10) and len(self.enemies) <= 2:
                self.enemies.append(Enemy(self.w, self.h))
            ## temporary list to manage the elimination of some enemies
            l = []
            for n in xrange(0, len(self.enemies)):
                enemy = self.enemies[n]
                if enemy.alive:
                    l.append(self.enemies[n])
            self.enemies = l

            ## manages small enemies one by one, checks collision with bullets, shield and tank
            for n in xrange(0, len(self.enemies_2)):
                enemy_2 = self.enemies_2[n]
                enemy_2.moves(time_seconds)
                enemy_2.bounces(self.background)
                if enemy.error:
                    self.enemies_2[n] = Enemy_2(self.w, self.h)
                self.screen.blit(enemy_2.image, (enemy_2.x, enemy_2.y))
                enemy_2_rect = pygame.Rect(enemy_2.x, enemy_2.y, enemy_2.d, enemy_2.d)
                if enemy_2_rect.colliderect(self.player_rect):
                    enemy_2.reverse()
                    self.energy -= 10
                elif enemy_2_rect.colliderect(shield_rect):
                    enemy_2.reverse()
                    self.energy -= 5
                elif enemy_2_rect.colliderect(self.bullet_rect):
                    self.bullet = Bullet(self.shooter.x, self.shooter.y, self.shooter.image_rotation)
                    enemy_2.alive = False
                    self.counter_enemies_2_dead += 1
                    self.points += 10
                    self.killed_small_enemies += 1
            ## temporary list to manage the elimination of some enemies
            l = []
            for n in xrange(0, len(self.enemies_2)):
                enemy_2 = self.enemies_2[n]
                if enemy_2.alive:
                    l.append(self.enemies_2[n])
            self.enemies_2 = l
            if self.counter_enemies_2_dead == 3:
                self.counter_enemies_2_dead = 0
                self.enemies.append(Enemy(self.w, self.h))

            ## manages rays of energy and collision with generator and tank and manages life time
            self.ray.moves(time_seconds)
            self.ray.bounces(self.background)
            self.screen.blit(self.ray.image, (self.ray.x, self.ray.y))
            ray_rect = pygame.Rect(self.ray.x, self.ray.y, self.ray.d, self.ray.d)
            if ray_rect.colliderect(generator_rect):
                self.ray.check_caught()
                if self.ray.caught:
                    self.ray = Ray(self.w, self.h)
                    self.energy += 20
                    self.points += 10
                    self.rays_collected += 1
                else:
                    self.ray.reverse()
            if ray_rect.colliderect(self.player_rect):
                self.ray.reverse()
            if (
                self.timer >= 30 * 15
                and self.timer <= 30 * 15.01
                or self.timer >= 30 * 30
                and self.timer <= 30 * 30.01
                or self.timer >= 30 * 45
                and self.timer <= 30 * 45.01
                or self.timer >= 30 * 60
                and self.timer <= 30 * 60.01
                or self.timer >= 30 * 75
                and self.timer <= 30 * 75.01
                or self.timer >= 30 * 90
                and self.timer <= 30 * 90.01
                or self.timer >= 30 * 105
                and self.timer <= 30 * 105.01
                or self.timer >= 30 * 120
                and self.timer <= 30 * 120.01
            ):
                self.ray = Ray(self.w, self.h)

            ## manages the end of the loop
            if self.collectible.finished == True:
                pygame.display.quit()
                self.end()

            pygame.display.update()

    def end(self):
        ## creates a whole new screen, calculates points and blits results
        pygame.init()
        screen = pygame.display.set_mode((600, 300), 0, 32)
        screen.fill((0, 0, 0))

        points = self.seconds + (self.minutes * 60) + self.energy + self.points
        if (
            self.killed_big_enemies >= 3
            and self.killed_small_enemies >= 3
            and self.rays_collected >= 3
            and self.collectibles_collected >= 4
        ):
            msg = "You did great!!!"
        else:
            msg = "You could have done better! ;)"

        end = True
        while end:
            font = pygame.font.SysFont("comic", 40)
            text = font.render(("Total points: " + str(points)), True, (255, 255, 255))
            text1 = font.render(msg, True, (255, 255, 255))
            screen.blit(text, (100, 100))
            screen.blit(text1, (100, 200))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.display.quit()
                    end = False
            pygame.display.update()
Ejemplo n.º 32
0
class MyRobot(wpilib.SimpleRobot):
    def __init__(self):
        super().__init__()
        self.loader = Loader()
        self.shooter = Shooter()
        self.drive = Drive(config.robotDrive, config.leftJoy, config.hsButton,
                           config.alignButton)
        self.componets = [ self.loader, self.shooter, self.drive ]

    def RobotInit(self):
        wpilib.Wait(0.25)
        shooterEncoder.Start()

    def Disabled(self):
        while wpilib.IsDisabled():
            CheckRestart()
            wpilib.Wait(0.01)

    def Autonomous(self):
        while wpilib.IsAutonomous() and wpilib.IsEnabled():
            CheckRestart()
            wpilib.Wait(0.01)

    def OperatorControl(self):
        dog = self.GetWatchdog()
        dog.SetEnabled(True)
        dog.SetExpiration(0.25)

        self.drive.stop()
        shooterMotor.Set(0)
        tipperMotor.Set(0)
        rollerMotor.Set(0)

        while self.IsOperatorControl() and self.IsEnabled():
            dog.Feed()
            CheckRestart()
            for componet in self.componets:
                componet.tick()

            #Teleop Code
            #if not self.drive.aligning :
            #    self.drive.arcadeDrive(leftJoy.GetRawButton(halfSpeed))
            shooterMotor.Set(rightJoy.GetY())

            ## Alignment
            #if leftJoy.GetRawButton(allignButton) :
            #    if not self.drive.aligning:
            #        self.drive.aligning = True
            #        robotDrive.StopMotor()
            #    self.drive.align()
            #else:
            #    self.drive.aligning = False

            ## Tipper Up and Down
            if rightJoy.GetRawButton(tipperUp):
                tipperMotor.Set(-1)
            elif rightJoy.GetRawButton(tipperDown):
                tipperMotor.Set(1)
            else:
                tipperMotor.Set(0)

            ## Roller Up and Down
            if rightJoy.GetRawButton(rollerUpButton):
                rollerMotor.Set(-1)
            elif rightJoy.GetRawButton(rollerDownButton):
                rollerMotor.Set(1)
            else:
                rollerMotor.Set(0)

            ## Loading
            if rightJoy.GetRawButton(feederButton):
                self.loader.load()

            ## Shooting
            if rightJoy.GetRawButton(latchButton):
                self.shooter.unlatch()

            ## Debug & Tuning

            wpilib.Wait(0.01)
Ejemplo n.º 33
0
class AgenteReportero():
    def __init__(self,
                 imagenDeInicializacion,
                 areaProtegida,
                 areaDeConfirmacion,
                 areaDeInteresPlacas=[[0, 0], [2592, 1944]],
                 framesPorSegundo=10,
                 nombreCarpetaAlmacenamiento='casosReportados',
                 modoDebug=False):
        # REGISTROS AUTOMOVILES:
        self.numeroDePuntosASeguir = 3
        self.miReporte = MiReporte(levelLogging=logging.INFO, nombre=__name__)
        self.areaDeResguardo = AreaDeResguardo(imagenDeInicializacion,
                                               self.numeroDePuntosASeguir,
                                               areaProtegida,
                                               areaDeConfirmacion)
        self.areaDeConfirmacion = np.array(areaDeConfirmacion)
        self.poligonoProtegidoParaVisualizacion = np.array(areaProtegida)

        self.reporteVideo = []  # Minimo 9 frames Maximo 15 frames
        self.misInfracciones = []

        # Parametros auxiliares
        self.numeroDeFrame = 0
        self.framesPorSegundoEnVideo = framesPorSegundo
        self.ultimaVelocidad = 0
        self.widerVideo = 6  # aumenta el numero de frames al inicio y al final del video
        self.formaOndaDebug = []
        self.infraccionesConfirmadas = 0
        self.infraccionesDescartadasPorTiempo = 0
        self.infraccionesDescartadasPorEstacionario = 0
        self.infraccionesDescartadasGiro = 0
        self.numeroInfraccionesTotales = 0

        # Variables de reporte:
        self.reportarDebug = modoDebug
        # El directorio por defecto sera uno u otro en la memoria USB
        # Estas variables son auxiliares para definir la variable que sera de reporte en cuanto se sepa si hay unidad flash introducida

        self.nombreDirectorioLocal = os.getenv(
            'HOME') + '/trafficFlow/prototipo11'
        self.nombreDirectorioUSB = '/media/' + os.getenv('HOME').split(
            '/')[-1] + '/usbName'

        if os.path.exists(self.nombreDirectorioUSB):
            self.carpetaDeReporte = self.nombreDirectorioUSB + '/' + nombreCarpetaAlmacenamiento
            self.miReporte.info(
                'Encontrada unidad USB, guardando informacion en el medio: ' +
                self.carpetaDeReporte)
            self.carpetaDeReporteDebug = self.nombreDirectorioUSB + '/debug'
        else:
            self.carpetaDeReporte = self.nombreDirectorioLocal + '/' + nombreCarpetaAlmacenamiento
            self.miReporte.info(
                'No se detectó unidad USB, guardando archivos de forma local:'
                + self.carpetaDeReporte)
            self.carpetaDeReporteDebug = self.nombreDirectorioLocal + '/casosDebug'

        if not os.path.exists(self.carpetaDeReporte):
            try:
                os.makedirs(self.carpetaDeReporte)
            except Exception as e:
                self.miReporte.error('ERROR, No pude crear el directorio ' +
                                     self.carpetaDeReporteDebug + ' por: ' +
                                     str(e))

        if not os.path.exists(self.carpetaDeReporteDebug):
            try:
                os.makedirs(self.carpetaDeReporteDebug)
            except Exception as e:
                self.miReporte.error('ERROR, No pude crear el directorio ' +
                                     self.carpetaDeReporteDebug + ' por: ' +
                                     str(e))

        # Si estoy en el raspberry creo la clase shooter
        self.miComputadora = os.uname()[1]
        if self.miComputadora == 'raspberrypi':
            #print('ESTOY TRABAJANDO EN LA PI, CREANDO SHOOTER SHOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOTER')
            self.miCamara = Shooter(cutPoly=areaDeInteresPlacas)
            self.miReporte.debug('Creada camara de alta resolucion')

        # Creo las carpetas de reporte actual y para el debug, por ahora la misma
        self.fechaReporte = datetime.datetime.now().strftime(
            '%Y-%m-%d-%H-%M-%S')
        self.carpetaDeReporteActual = self.carpetaDeReporte + '/' + self.fechaReporte
        self.carpetaDeReporteActualDebug = self.carpetaDeReporteDebug + '/' + self.fechaReporte

    def inicializarAgente(
        self, dateToUse=datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')):
        """
		Devuelve a las condiciones iniciales, debera ser llamado en el primer Rojo
		"""
        del self.reporteVideo
        del self.misInfracciones
        del self.formaOndaDebug
        self.reporteVideo = []
        self.misInfracciones = []
        self.formaOndaDebug = []

        self.fechaReporte = dateToUse
        #Si introduzco fecha la uso, si no , empleo la actual
        self.carpetaDeReporteActual = self.carpetaDeReporte + '/' + self.fechaReporte
        self.carpetaDeReporteActualDebug = self.carpetaDeReporteDebug + '/' + self.fechaReporte
        #print(self.carpetaDeReporteActual)
        if not os.path.exists(self.carpetaDeReporteActual):
            try:
                os.makedirs(self.carpetaDeReporteActual)
            except Exception as e:
                self.miReporte.error(
                    'ERROR, No pude crear el directorio Actual por: ' + str(e))
        if not os.path.exists(self.carpetaDeReporteActualDebug):
            try:
                os.makedirs(self.carpetaDeReporteActualDebug)
            except Exception as e:
                self.miReporte.error(
                    'ERROR, No pude crear el directorio Debug por: ' + str(e))
        #print(self.fechaReporte)
        self.miReporte.moverRegistroACarpeta(self.fechaReporte)
        self.miReporte.info('Nuevo Directorio de reporte: ' +
                            self.carpetaDeReporteActual)
        return True

    def introducirImagen(self, frameActualFlujo):
        """
		Introducir la forma de onda correspondiente a la imagen de prueba
		"""
        self.reporteVideo.append(frameActualFlujo)

        numeroDeFrameActual = len(self.reporteVideo)

        vectorRuidoso, self.ultimaVelocidad, indiceFrameActual = self.areaDeResguardo.encontrarObjetosYCalcularFlujoYPaso(
            frameActualFlujo, self.misInfracciones)
        self.formaOndaDebug.append([vectorRuidoso, self.ultimaVelocidad])

        if indiceFrameActual == -1:
            dateStamp = datetime.datetime.now().strftime(
                '%Y-%m-%d-%H-%M-%S.%f')
            if self.miComputadora == 'raspberrypi':
                self.miCamara.encenderCamaraEnSubDirectorio(
                    self.fechaReporte, dateStamp)
                self.miReporte.info('Encendi Camara en ' + dateStamp)
            caracteristicasASeguir = self.areaDeResguardo.obtenerUltimosPuntosASeguir(
            )
            self.miReporte.debug(
                'Detecte Flujo y encontre los puntos de interes: ' +
                str(caracteristicasASeguir))
            # Si no encontre buenas características a seguir descarto esta infracción

            if len(caracteristicasASeguir.shape) > 1:
                self.miReporte.debug('GATILLADO DETECTADO')
                nuevaInfraccion = {
                    'name': dateStamp,
                    'momentum': indiceFrameActual,
                    'frameInicial': numeroDeFrameActual,
                    'frameFinal': 0,
                    'desplazamiento': np.array(caracteristicasASeguir),
                    'estado': 'Candidato',
                    'foto': False
                }
                self.miReporte.debug(
                    'Guardando Imagen en: ' + self.carpetaDeReporteActual +
                    '/' +
                    datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S.%f') +
                    '.jpg')
                cv2.imwrite(
                    self.carpetaDeReporteActual + '/' + dateStamp + '.jpg',
                    frameActualFlujo)
                self.misInfracciones.append(nuevaInfraccion)
            else:
                self.miReporte.warning(
                    'No pude encontrar puntos de interes en el objeto >>>>>>>>>>>>>>>>>>>>>>'
                )

        for infraction in self.misInfracciones:
            if (indiceFrameActual == -10) & (
                    self.miComputadora == 'raspberrypi') & (infraction['foto']
                                                            == False):
                self.miCamara.encenderCamara()
                tomeFoto = {'foto': True}
                infraction.update(tomeFoto)
                self.miReporte.info('Encendi Camara con parametros anteriores')
            if infraction['estado'] == 'Confirmando':
                cerrarInfraccion = {
                    'estado': 'Confirmado',
                    'frameFinal': numeroDeFrameActual
                }
                infraction.update(cerrarInfraccion)

        numeroDeInfracciones = 0
        for infraction in self.misInfracciones:
            if infraction['estado'] == 'Confirmado':
                numeroDeInfracciones += 1
        self.reporteInfracciones()

        return numeroDeFrameActual

    def reporteInfracciones(self):
        sumaInfracciones = 0
        for infraction in self.misInfracciones:
            if infraction['estado'] == 'Confirmado':
                sumaInfracciones += 1
        self.infraccionesConfirmadas = sumaInfracciones
        sumaInfracciones = 0
        for infraction in self.misInfracciones:
            if infraction['estado'] == 'Timeout':
                sumaInfracciones += 1
        self.infraccionesDescartadasPorTiempo = sumaInfracciones
        sumaInfracciones = 0
        for infraction in self.misInfracciones:
            if infraction['estado'] == 'Giro':
                sumaInfracciones += 1
        self.infraccionesDescartadasGiro = sumaInfracciones

        self.infraccionesDescartadasPorEstacionario = 0
        self.numeroInfraccionesTotales = len(self.misInfracciones)

        return [
            self.infraccionesConfirmadas, self.numeroInfraccionesTotales,
            self.infraccionesDescartadasPorTiempo,
            self.infraccionesDescartadasPorEstacionario,
            self.infraccionesDescartadasGiro
        ]

    def guardarReportes(self):
        """
		Guarda los archivos de Debug, y casos, de existir, debera ser llamado en el primer Verde
		"""
        reportadosCasos = len(self.misInfracciones)
        if reportadosCasos == 0:
            self.miReporte.info('Nada que reportar')
            return reportadosCasos
        self.miReporte.info('Reportando: ' + str(len(self.misInfracciones)) +
                            ' casos')
        numeroDeInfraccion = 0
        for infraccionActual in self.misInfracciones:
            if infraccionActual['estado'] == 'Confirmado':
                self.miReporte.info(
                    'Generando: ' +
                    str(infraccionActual['desplazamiento'].shape))
                self.generarReporteInfraccion(infraccionActual['name'], [
                    infraccionActual['frameInicial'] - self.widerVideo,
                    infraccionActual['frameFinal'] + self.widerVideo
                ])
            else:
                archivosEliminados = 0
                for filename in glob.glob(self.carpetaDeReporteActual + '/' +
                                          infraccionActual['name'] + '*'):
                    os.remove(filename)
                    archivosEliminados += 1
                    os.system('touch ' + filename + '.txt')
                self.miReporte.warning(
                    'ERASE WARNING!!!! Elimine {} archivos correspondientes a: '
                    .format(archivosEliminados) + infraccionActual['name'] +
                    ' con estado: ' + infraccionActual['estado'] +
                    ' ERASE WARNING!!!! ')

        if self.reportarDebug:
            np.save(self.carpetaDeReporteActualDebug + '/onda.npy',
                    self.formaOndaDebug)
            self.generarReporteDebug()
            self.miReporte.debug('Guardado debug')
            with open(self.carpetaDeReporteActualDebug + '/infracciones.pkl',
                      'wb') as f:
                pickle.dump(self.misInfracciones, f, pickle.HIGHEST_PROTOCOL)
        self.miReporte.info('Casos guardados')

        return reportadosCasos

    def generarReporteDebug(self):
        """
		Se crea un reporte en video con las imagenes de baja calidad con el fin de realizar mejoras futuras
		"""

        # Variables para la creacion de video:
        height, width, layers = self.reporteVideo[0].shape
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        prueba = cv2.VideoWriter(
            self.carpetaDeReporteActualDebug + '/' + self.fechaReporte +
            '-debug.avi', fourcc, self.framesPorSegundoEnVideo,
            (width, height))

        for index in range(len(self.reporteVideo)):
            prueba.write(self.reporteVideo[index])
        prueba.release()

        self.miReporte.info('Reportado: ' + self.fechaReporte + ' len: ' +
                            str(len(self.reporteVideo)))
        return True

    def generarReporteInfraccion(self, nombreInfraccion, indicesParaVideo):
        """
		Se crea un reporte para una infraccion comprendida entre indicesParaVideo[0] y indicesParaVideo[1] con gray scale en todos los frames que indique el indice para videos
		"""
        height, width, layers = self.reporteVideo[0].shape
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        prueba = cv2.VideoWriter(
            self.carpetaDeReporteActual + '/' + nombreInfraccion + '.avi',
            fourcc, self.framesPorSegundoEnVideo, (width, height))
        self.miReporte.info('Archivo guardado: ' +
                            self.carpetaDeReporteActual + '/' +
                            nombreInfraccion + '.avi')
        if indicesParaVideo[0] < 0: inicio = 0
        else: inicio = indicesParaVideo[0]
        if indicesParaVideo[1] > len(self.reporteVideo):
            final = len(self.reporteVideo)
        else:
            final = indicesParaVideo[1]
        for index in range(inicio, final):
            imagenAVideo = self.reporteVideo[index]
            prueba.write(imagenAVideo)
        prueba.release()

        self.miReporte.info('Reportado: ' + self.fechaReporte + ' len: ' +
                            str(indicesParaVideo[1] - indicesParaVideo[0]))
Ejemplo n.º 34
0
    def brain(self):
        shooter = Shooter()
        gameOver = False
        self.ships = self.getShips(self.amountOfShips)  #places ships
        print(self.allShipCoordinates)
        while (not gameOver):
            #Bots turn
            print("My turn!")
            if not shooter.currentTarget:  # if currentTarget is empty, meaning that ship hasn't been located
                coords = shooter.getRandomCoords()
                self.sendShootingCoordinatesToOpponent(coords)
                print("HIT, MISS OR SUNK?")
                answer = self.getOpponentResponse()
                if answer == "MISS":
                    shooter.missed.append(coords)
                elif answer == "HIT":
                    shooter.hits.append(coords)
                    shooter.currentTarget.append(coords)
                elif answer == "SUNK":
                    self.enemyShipsSunk += 1
                    shooter.hits.append(coords)
                    shooter.reset()
            else:  #if currentTarget isn't empty, meaning that ship has been located
                coords = shooter.getTargetCoords(shooter.shootingDirection,
                                                 shooter.currentTarget[-1])
                self.sendShootingCoordinatesToOpponent(coords)
                answer = self.getOpponentResponse()
                if answer == "MISS" and len(
                        shooter.currentTarget
                ) == 1:  #if there's only been one hit, meaning that the bot is finding out if the ship lays vertically or not
                    shooter.missed.append(coords)
                    shooter.changeDirection()  #update shootingDirection
                elif answer == "MISS" and len(
                        shooter.currentTarget
                ) > 1:  #if there's been more than one hit, meaning that the bot is shooting directly at the ship and has now found the end of it
                    if shooter.endOfShipReached == True:  #if the end of the ship has already been reached, then this is the second time, and something is wrong, since both ends have been found but there's been no SUNK
                        print(
                            "END OF SHIP HAS BEEN FOUND TWICE, SOMETHING IS WRONG!!!!!!!!"
                        )
                        sys.exit()
                    else:  #if this is the first time the end of the ship has been reached
                        shooter.endOfShipReached = True
                    shooter.missed.append(coords)
                    shooter.currentTarget = list(
                        reversed(shooter.currentTarget)
                    )  #reverse currentTarget so that next time the bot will shoot from the other end
                    shooter.reverseDirection(
                    )  #reverse the shooting direction so that next time the bot will shoot in the other direction
                elif answer == "HIT":
                    shooter.hits.append(coords)
                    shooter.currentTarget.append(coords)
                elif answer == "SUNK":
                    self.enemyShipsSunk += 1
                    shooter.hits.append(coords)
                    shooter.reset()
            #Bots turn ends, check for game over
            gameOver = self.isGameOver()
            if gameOver == True:
                print("I WIN!")
                break
            #Opponents turn
            print("Your turn. Send coords: x,y")
            opcoords = self.getOpponentCoords()
            botAnswer = self.hitMissOrSunk(opcoords)
            if botAnswer == "SUNK":
                self.myShipsSunk += 1
            print(botAnswer)
            #Opponents turn end, check for game over
            gameOver = self.isGameOver()
            if gameOver == True:
                print("I LOSE!")
                break

        print("GAME IS OVER")
Ejemplo n.º 35
0
	def setUp(self):
		self.jake = Shooter('Jake')
		print(self.mock_data)
		self.mock_data = [1, 2, 3, 4, 5]
 def shooter3(self):
     self.shooter = Shooter(self)
class SidewaysShooter:

    def __init__(self):
        """Initialize the game and create game resources."""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        pygame.display.set_caption("Sideways Shooter")

        # Create an instance to store game statistics, and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.shooter = Shooter(self)
        self.lines = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()
        self.bulletbs = pygame.sprite.Group()
        self.balls = pygame.sprite.Group()
        self.ball2s = pygame.sprite.Group()

        self._create_fleet()
        self._create_fleet2()

        # Make the play button.
        self.play_button = PlayButton(self, "Right wheel to play")

        # Make the Settings button.
        self.settings_button = SettingsButton(self, "Settings")

        # Make the setttings menu.
        self.settings_menu = SettingsMenu(self, "fast or slow press y or n")

        # Make the speed button.
        self.speed_button = SpeedButton(self, "you have selected the fast option")

        # Make the second speed button.
        self.speed_button2 = SpeedButton2(self, "You have selected the slower options")
        
    def run_game(self):
        """Start the main game loop."""
        Running, Pause = 0, 1
        state = Running
        while True:
            self._check_events()
            if self.stats.game_active:
                self._check_events()
                self.shooter.update()
                self._update_bullets()
                self._update_shooter()
                self.check_if_empty()
                

                        
            self._update_screen()

    def _check_events(self):
        LEFT = 1
        MIDDLE = 2
        RIGHT = 3
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
                #mouse_pos2 = pygame.mouse.get_pos()
                #self._check_play_button(mouse_pos2)
                #None
                self._fire_bullet()

            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == MIDDLE:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
                #pause
                
                #self._check_settings_button(mouse_pos)

            #elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos2 = pygame.mouse.get_pos()
                self.settings_button.flag = True
                #self._check_settings_button(mouse_pos2)
                
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == RIGHT:
                #mouse_pos = pygame.mouse.get_pos()
                #self._check_play_button(mouse_pos) 
                self._fire_bulletb()
                
    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        
        if button_clicked and not self.stats.game_active:
            # Reset the game statistics.
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_shooters()

            # Get rid of any remaining balss and aliens
            self.balls.empty()
            self.ball2s.empty()
            self.bullets.empty()
            self.bulletbs.empty()
            self.lines.empty()
            self.shooter3()

            # Create a new fleet.
            self._create_fleet()
            self._create_fleet2()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)
        

    def _check_settings_button(self, mouse_pos2):
        """load the settings when the player clicks settings"""
        if self.settings_button.rect.collidepoint(mouse_pos2):
            #self.settings_button.flag = True
            #self.settings_menu.check_image()
            self.settings_menu.draw_button()

    
        
                        
    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_x:
            self.shooter.moving_right = True
        elif event.key == pygame.K_c:
            self.shooter.moving_left = True
        elif event.key == pygame.K_SPACE:
            self._fire_line()
        elif event.key == pygame.K_RIGHT:
            self.settings_button.flag = True
            #self.speed_button.draw_button()
        elif event.key == pygame.K_LEFT:
            self.settings_button.flag = False
            self.settings_menu.draw_button()
            pygame.mouse.set_visible(True)
        elif event.key == pygame.K_y:
            self.speed_button.flag2 = True
            while self.speed_button.flag2 == True:
                self.speed_button2.flag3 = False
                break
            self.settings.shooter_speed2 = 0.09
        elif event.key == pygame.K_n:
            self.speed_button2.flag3 = True
            while self.speed_button2.flag3 == True:
                self.speed_button.flag2 = False
                break
            self.settings.shooter_speed2 = 0.01
        elif event.key == pygame.K_p:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
            self.settings_button.flag = False
            #self.settings_button()
            self.balls.empty()
            self.ball2s.empty()
            self.bullets.empty()
            self.bulletbs.empty()
            self.lines.empty()
            self.shooter3()
            self._create_fleet()
            self._create_fleet2()
        elif event.key == pygame.K_q:
            pygame.mouse.set_visible(True)
            sys.exit()

    def shooter3(self):
        self.shooter = Shooter(self)

    def check_if_empty(self):
        if len(self.balls) == 0 and len(self.ball2s) == 0:
            pass

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_x:
            self.shooter.moving_right = False
        elif event.key == pygame.K_c:
            self.shooter.moving_left = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the group."""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _fire_bulletb(self):
        """Create a new bullet and add it to the group."""
        if len(self.bulletbs) < self.settings.bulletbs_allowed:
            new_bulletb = Bulletb(self)
            self.bulletbs.add(new_bulletb)

    def _update_bullets(self):
        """Update position of bullerts and get rid of old bullets."""
        # Update bullet positions
        self.bullets.update()
        self.bulletbs.update()
        self.lines.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.right >= self.settings.screen_width:
                self.bullets.remove(bullet)

        for bulletb in self.bulletbs.copy():
            if bulletb.rect.right >= self.settings.screen_width:
                self.bulletbs.remove(bulletb)

        self._check_bullet_ball_collisions()
        
    def _check_bullet_ball_collisions(self):
        """Respond to bullet-ball collisions."""
        # Remove any bullets and balls that have collided.
        # Check for any bullets that have hit any balls
        #  If so, get rid of the bullets and the ball
        collisions = pygame.sprite.groupcollide(self.bullets, self.balls, True, True)
        collisions2 = pygame.sprite.groupcollide(self.bulletbs, self.ball2s, True, True)
        collisions3 = pygame.sprite.groupcollide(self.lines, self.balls, True, True)
        collisions4 = pygame.sprite.groupcollide(self.lines, self.ball2s, True, True)

        if collisions3 or collisions4 == True:
            self._shooter_hit()

        if collisions:
            for balls in collisions.values():
                self.stats.score += self.settings.ball_points * len(balls)
            self.sb.prep_score()
            self.sb.check_high_score()
            
        if collisions2:
            for ball2s in collisions2.values():
                self.stats.score += self.settings.ball_points2 * len(ball2s)
            self.sb.prep_score()
            self.sb.check_high_score()

            
    def _update_shooter(self):
        """Update the position of the shooter."""
        self.shooter.update()

        # Look for ball-shooter collisions.
        if pygame.sprite.spritecollideany(self.shooter, self.balls):
            self._shooter_hit()

        if pygame.sprite.spritecollideany(self.shooter, self.ball2s):
            self._shooter_hit()

    
    def _shooter_hit(self):
        """Respond to the shooter being hit."""
        if self.stats.shooters_left > 0:
            # Decrement ships_left, and update scoreboard.
            self.stats.shooters_left -= 1
            self.sb.prep_shooters()

            # Get rid of any remaining balls and bullets.
            self.balls.empty()
            self.ball2s.empty()
            self.bullets.empty()
            self.bulletbs.empty()
            self.lines.empty()

            # Create a new fleet
            self.shooter3()
            self._create_fleet()
            self._create_fleet2()

            # Pause.
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
                
    def _create_fleet(self):
        """Create the fleet of balls."""
        # Create a ball and find the number of balls in one row.
        # Spacing between ball is equal to one balls width.
        ball = Ball(self)
        ball_width = ball.rect.height
        ball_width, ball_height = ball.rect.size
        available_space_x = self.settings.screen_width 
        number_balls_x = available_space_x // (6 * ball_width)
 
        # Determine the number of rows of aliens that fit on the screen.
        ship_height = self.shooter.rect.height
        available_space_y = self.settings.screen_height 
        number_rows = available_space_y // (2 * ball_height)
        
        # Create the first fleet of aliens.
        for row_number in range(number_rows):
            for ball_number in range(number_balls_x):
                # Create a ball and place it in the row.
                ball = Ball(self)
                ball_width, ball_height = ball.rect.size
                ball.y = 2 * ball_width + (5 * ball_width * ball_number) 
                ball.rect.y = ball.y
                ball.rect.x =  19 *  ball_width  + (2 * ball_width * row_number) 
                self.balls.add(ball)

    def _create_fleet2(self):
        """Create the fleet of ball2s."""
        # Create a yellow ball and find the number of balls in a row.
        # Spacing between each ball is equal to one ball width.
        ball2 = Ball2(self)
        ball_width2 = ball2.rect.height
        ball_width2, ball_height2  = ball2.rect.size
        available_space_x2 = self.settings.screen_width
        number_ball2s_x = available_space_x2 // (6 * ball_width2)

        # Determine the number of balls that fit on the screen
        shooter_height = self.shooter.rect.height
        available_space_y2 = self.settings.screen_width
        number_rows2 = available_space_y2 // (2 * ball_height2)

        # Create the first fleet of balls.
        for row_number2 in range(number_rows2):
            for ball2_number in range(number_ball2s_x):
                # Create a ball and place it in the row.
                ball2 = Ball2(self)
                ball_width2, ball_height2 = ball2.rect.size
                ball2.y =  5 * ball_width2 * ball2_number
                ball2.rect.y = ball2.y
                ball2.rect.x =  19 * ball_width2 + (2 * ball_width2 * row_number2)
                self.ball2s.add(ball2)

    def _fire_line(self):
        """Create a new line and add it to the lines group."""
        for i in range(1):
            new_line = Line(self)
            self.lines.add(new_line)

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
         # Draw the play button if the game is inactive.
        #if not self.stats.game_active:
            #self.play_button.draw_button()
            
        self.screen.fill(self.settings.bg_color)
        self.shooter.blitme()
        #self._fire_line()
        
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
            

        for bulletb in self.bulletbs.sprites():
            bulletb.draw_bulletb()

        for line in self.lines.sprites():
            #self._fire_line()
            line.draw_line()
            
            
        self.balls.draw(self.screen)
        self.ball2s.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        # Draw the play button if the game is inactive.
        if not self.stats.game_active:
            self.play_button.draw_button()

        # Draw the settings if the game is inactive.
        if not self.stats.game_active:
            self.settings_button.draw_button()

        if self.settings_button.flag == True and not self.stats.game_active:
            #self.settings_menu.check_image()
            self.settings_menu.draw_button()

        if self.speed_button.flag2 == True and not self.stats.game_active:
            self.speed_button2.flag3 = False
            self.speed_button.draw_button3()
            
            

        if self.speed_button2.flag3 == True and not self.stats.game_active:
            self.speed_button.flag2 = False
            self.speed_button2.draw_button4()
            
            

        #self.speed_button2.flag3 = False
        #self.speed_button.flag2 = False
            
        pygame.display.flip()
Ejemplo n.º 38
0
class Ventana(QtGui.QFrame):
    def __init__(self):
        super().__init__()
        self.setObjectName("Ventana")
        self.setMouseTracking(True)
        self.setGeometry(200, 100, 800, 600)
        self.setStyleSheet("#Ventana {background-image: url('img/bg.gif');background-color:green;}")
        self.setWindowTitle("Zombitch")
        self.shooter = Shooter(parent=self, x=400, y=300)
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.create_zombie)
        self.timer.setInterval(1000)
        self.timer.start()
        self.zombies = [Zombie(parent=self, x=0, y=0, target=self.shooter)]
        self.packages = []
        self.__kills = 0
        self.start_time = datetime.now()
        self.status = Status(parent=self)
        self.overlay = Overlay(parent=self)
        self.message = Message(parent=self)

    @property
    def kills(self):
        return self.__kills

    @kills.setter
    def kills(self, value):
        self.__kills = value
        self.status.update_kills()

    def actualizarImagen(self, myImageEvent):
        label = myImageEvent.image
        label.move(myImageEvent.x, myImageEvent.y)

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == QtCore.Qt.Key_Z:
            vehicle = Vehicle(parent=self, x=100, y=600)
            vehicle.summon()
        elif QKeyEvent.key() == QtCore.Qt.Key_Space:
            self.message.set_text("Paused")
            self.message.show()
            self.pause()
        else:
            self.shooter.move(QKeyEvent.key())

    def mouseMoveEvent(self, QMouseEvent):
        x = QMouseEvent.x()
        y = QMouseEvent.y()
        self.shooter.guide((x,y))

    def mousePressEvent(self, QMouseEvent):
        x = QMouseEvent.x()
        y = QMouseEvent.y()
        self.shooter.shoot((x,y))
        self.shooter.guide((x,y))

    def send_care_package(self):
        if random.random() > 0.93 and len(self.packages) <= 1:
            care = CarePackage(parent=self, shooter=self.shooter)
            care.summon()
            self.packages.append(care)

    def zombie_interval(self):
        if (datetime.now() - self.start_time).total_seconds() > 200:
            interval = random.expovariate(1/250)
        else:
            interval = 1000 - 50*self.kills
            interval = random.expovariate(1/max(interval, 500))
        self.timer.setInterval(interval)

    def create_zombie(self):
        choice = random.randint(0,1)
        if choice == 0:
            x = random.randint(0,1)*800
            y = random.randint(0,60)*10
        elif choice == 1:
            x = random.randint(0,80)*10
            y = random.randint(0,1)*600
        if len(self.zombies) < 20:
            if random.random() > 0.60:
                self.zombies.append(SuperZombie(parent=self, x=x, y=y, target=self.shooter))
            else:
                self.zombies.append(Zombie(parent=self, x=x, y=y, target=self.shooter))
            self.zombie_interval()

        if (datetime.now() - self.start_time).total_seconds() > 20:
            self.send_care_package()

    def pause(self):
        self.timer.stop()
        for event in ["mouseMoveEvent", "mousePressEvent", "keyPressEvent"]:
            setattr(self, event, self.pass_event)
        for zombie in self.zombies:
            zombie.pause()

    def play(self):
        self.timer.start()

    def pass_event(self, *args):
        pass

    def end(self):
        self.message.set_text("Game Over")
        self.message.show()
        self.pause()
Ejemplo n.º 39
0
class Robot(wpilib.TimedRobot):
    def robotInit(self):
        """
        This function is called upon program startup and
        should be used for any initialization code.
        """
        self.driver_stick = wpilib.Joystick(0)
        self.codriver_stick = wpilib.Joystick(1)

        self.left_shooter_motor = ctre.WPI_TalonSRX(0)
        self.left_drivetrain_motor = ctre.WPI_TalonSRX(1)
        self.right_drivetrain_motor = ctre.WPI_TalonSRX(2)
        self.right_shooter_motor = ctre.WPI_TalonSRX(3)

        self.intake_motor = wpilib.Spark(8)
        self.arm_pivot_motor = wpilib.Spark(6)
        self.arm_lock_motor = wpilib.Spark(5)

        self.timer = wpilib.Timer()
        #self.navx       = navx.AHRS.create_spi()

        self.duration = 20

        self.drivetrain = DriveTrain(self.left_drivetrain_motor,
                                     self.right_drivetrain_motor)
        self.shooter = Shooter(self.intake_motor, self.left_shooter_motor,
                               self.right_shooter_motor)
        self.arm = Arm(self.arm_pivot_motor, self.arm_lock_motor)

    def autonomousInit(self):
        pass

    def autonomousPeriodic(self):
        self.teleopPeriodic()

    def teleopInit(self):
        pass

    def teleopPeriodic(self):
        """This function is called periodically during operator control."""
        start = self.timer.getMsClock()

        self.drivetrain.drive(self.driver_stick)
        self.shooter.shoot(self.codriver_stick)
        self.arm.lift(self.codriver_stick)
        """
        wpilib.SmartDashboard.putNumber("NavX", self.navx.getAngle())
        """
        wpilib.SmartDashboard.putNumber(
            "Left drivetrain speed",
            self.left_drivetrain_motor.getQuadratureVelocity())
        wpilib.SmartDashboard.putNumber(
            "Right drivetrain speed",
            self.right_drivetrain_motor.getQuadratureVelocity())
        """
        wpilib.SmartDashboard.putNumber("Left shooter position", self.left_shooter_motor.getQuadraturePosition())
        wpilib.SmartDashboard.putNumber("Right shooter position", self.right_shooter_motor.getQuadraturePosition())
        """
        wpilib.SmartDashboard.putNumber(
            "Left shooter", self.left_shooter_motor.getQuadratureVelocity())
        wpilib.SmartDashboard.putNumber(
            "Right shooter", self.right_shooter_motor.getQuadratureVelocity())
        """
        wpilib.SmartDashboard.putNumber("Left shooter RPM error", self.left_shooter_motor.getClosedLoopError(0) * 600/4096)
        wpilib.SmartDashboard.putNumber("Right shooter RPM error", self.right_shooter_motor.getClosedLoopError(0) * 600/4096)
        """

        self.duration = self.timer.getMsClock() - start

        wpilib.SmartDashboard.putNumber("Loop duration", self.duration)
Ejemplo n.º 40
0
    win = window.Window(width=500, height=500, vsync=False, resizable=True)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    # needed so that egi knows where to draw
    egi.InitWithPyglet(win)
    # prep the fps display
    fps_display = clock.ClockDisplay()
    # register key and mouse event handlers
    win.push_handlers(on_key_press)
    win.push_handlers(on_resize)

    # create a world for agents
    world = World(500, 500)
    # add one agent
    world.target = Target(world, 10, 10)
    world.shooter = Shooter(world, 10, 0.01)
    # unpause the world ready for movement
    world.paused = False

    shooter_controller = StateMachineAgent(world.shooter)

    while not win.has_exit:
        win.dispatch_events()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        # show nice FPS bottom right (default)
        delta = clock.tick()
        world.update(delta)
        world.render()
        shooter_controller.change_state()
        fps_display.draw()
        # swap the double buffer