Пример #1
0
    def handle_shot(self, laser_color, x, y):	
        if (self._pause_shot_detection):
            return 

        timestamp = 0

        # Start the shot timer if it has not been started yet,
        # otherwise get the time offset
        if self._shot_timer_start is None:
            self._shot_timer_start = time.time()
        else:
            timestamp = time.time() - self._shot_timer_start

        tree_item = None

        if "green" in laser_color:
            tree_item = self._shot_timer_tree.insert("", "end",
                values=[timestamp, "green"])
        else:
            tree_item = self._shot_timer_tree.insert("", "end",
                values=[timestamp, laser_color])
        self._shot_timer_tree.see(tree_item)

        new_shot = Shot((x, y), self._webcam_canvas,
            self._preferences[configurator.MARKER_RADIUS],
            laser_color, timestamp)
        self._shots.append(new_shot)
        new_shot.draw_marker()

        # Process the shot to see if we hit a region and perform
        # a training protocol specific action and any if we did
        # command tag actions if we did
        self.process_hit(new_shot, tree_item)
Пример #2
0
    def __init__(self,x,y,angle,time):
        Shot.__init__(self,x,y,angle)

        self._start = time
        self._speed  = SHOT_DOUBLE_MOVE_SPEED
        self._radius = SHOT_DOUBLE_RADIUS
        self._color  = SHOT_DOUBLE_COLOR
Пример #3
0
 def shoot(self, now, all_sprites, bullets):
     self.snd_player_shoot.play()
     self.last_shot = now
     new_shot1 = Shot((self.pos[0] + 8, self.pos[1]), self.firing_speed)
     new_shot2 = Shot((self.pos[0] + 24, self.pos[1]), self.firing_speed)
     all_sprites.add(new_shot1)
     all_sprites.add(new_shot2)
     bullets.add(new_shot1)
     bullets.add(new_shot2)
Пример #4
0
    def mushroom_attack_loop(self):
        g = self.g
        if self.health <= 0:
            if self.feeling != 'dead':
                self.feeling = 'dead'
                self.timer = 0
                
        if self.feeling == 'dead':
            if self.timer > 70:
                self.image = pygame.Surface((1, 1), SRCALPHA)
                self.dead = 1
                return
            if self.timer % 10 == 0:
                self.exp2.play()
            if self.timer % 3 == 0:
                # flash on and off
                self.image = pygame.Surface((1, 1), SRCALPHA)
            else:
                x = random.randint(0, 256)
                y = random.randint(0, 256)
                e = Effect(self.g, 'explosion', (self.rect.x + x, self.rect.y + y))
            return


        if self.timer % 20 == 1:
            if self.timer % 200 < 100:
                c = random.randint(0, 20)
                s = Shot(self.g, self.direction, (self.rect.x + 128, self.rect.y + 128 + c), 'shot5', 'enemy')
                s.callback = self.create_slime_monster
                self.squirt2.play()

        s = Rect(self.rect)
        s.x += 80
        s.width -= 100
        s.y += 100
        s.height -= 180
        if s.colliderect (g.player.rect):
            g.player.touch(self)

        for b in g.bullets:
            if b.owner == 'player':
                drect = (b.rect.x + 30, b.rect.y )
                if s.collidepoint(drect):
                    b.destroy()
                    self.health -= b.get_damage()
                    e = Effect(self.g, 'health', (self.rect.x, self.rect.y))
                    e.healthchange = -b.get_damage()
                    tmp = pygame.Surface((256, 256), SRCALPHA)
                    tmp.blit(self.image, (0,0))
                    tmp.blit(self.secondImage, (0,0))
                    self.image = tmp
                    self.hitme.play()
                    
        speed = 2
        self.rect.x += (1 - (self.direction * 2)) * speed
        self.draw_health_meter()
    def run(self):
        while True:
            self.fpsCounter.update();
            input(pygame.event.get());
            if self.network(): break;
            Shot.updates(self.shots);
            self.draw();

        print "Lost connection to server";
        self.sock.close();
Пример #6
0
 def __init__(self, x: int, y: int, game_ref: 'Game', cam_ref: 'Camera',
              spd: int) -> None:
     self.x = x
     self.y = y
     self.update = self.idle
     self.cam_ref = cam_ref
     self.max_timer = spd * FREQ
     self.timer = self.max_timer
     self.shot = Shot(self.x, self.y)
     game_ref.game_objects["shot"].append(self.shot)
Пример #7
0
def enemy_shoot(hero, shots):
    if hero.weapon.ammo > 0 and hero.shoot_count < 0:
        x, y, = hero.rect.center
        y1 = -6
        s = True
        shoots = []
        hero.weapon.sound.play()
        if hero.direction:
            s = Shot((x + 100, y + y1), (x + hero.wx_l, y + y1), hero.weapon.hit)
            if hero.weapon.bullet_num != 1:
                for i in range(hero.weapon.bullet_num):
                    shoot = Shot((x + 100, y - 20 + 10 * i), (x + hero.wx_l, y + y1), hero.weapon.hit)
                    shoot.image = pygame.image.load('bullit_r.png').convert()
                    shoots.append(shoot)
            s.image = pygame.image.load('bullit_r.png').convert()
        else:
            s = Shot((x - 100, y + y1), (x + hero.wx_r, y + y1), hero.weapon.hit)
            if hero.weapon.bullet_num != 1:
                for i in range(hero.weapon.bullet_num):
                    shoots.append(Shot((x - 100, y - 20 + 10 * i), (x + hero.wx_r, y + y1), hero.weapon.hit))

        if type(s) == Shot:
            hero.weapon.shoot()
            hero.shoot_count = 50
            shots.append(s)
            if shoots != []:
                shots += shoots
            return True
        else:
            return False
Пример #8
0
def test_debug_mv_file_exists(tmp_path):
    """
    should fail because src and dst are the same.
    latest file will be foo, will fail to copy since it already exists.
    """
    src_dir, dst_dir, src_file = setup_dirs(tmp_path)
    with pytest.raises(Exception) as context:
        s = Shot(src=str(src_dir), dst=str(src_dir), mv=True, debug=True)
        s._confirm = lambda: True  # avoid capturing stdin during test
        s()
    assert f"Destination path '{src_file}' already exists" in context.value.args
Пример #9
0
def test_cp_file_exists(tmp_path):
    """
    should fail because src and dst are the same.
    print error and systemexist.
    """
    src_dir, dst_dir, src_file = setup_dirs(tmp_path)
    with pytest.raises(SystemExit) as context:
        s = Shot(src=str(src_dir), dst=str(src_dir))
        s._confirm = lambda: True  # avoid capturing stdin during test
        s()
    assert (1, ) == context.value.args
Пример #10
0
	def take_screenshot(self, widget):
		shot = Shot()
		shot.start()
		time.sleep(0.5)
		screenshot = gtk.gdk.Pixbuf.get_from_drawable(
			gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, shot.width, shot.height),
			gtk.gdk.get_default_root_window(),
			gtk.gdk.colormap_get_system(),
			shot.sX, shot.sY, 0, 0, shot.width, shot.height)
		filename = "/tmp/droplr.png"
		screenshot.save(filename, "png")
		self.upload_file_and_notify(filename)
Пример #11
0
 def take_screenshot(self, widget):
     shot = Shot()
     shot.start()
     time.sleep(0.5)
     screenshot = gtk.gdk.Pixbuf.get_from_drawable(
         gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, shot.width,
                        shot.height), gtk.gdk.get_default_root_window(),
         gtk.gdk.colormap_get_system(), shot.sX, shot.sY, 0, 0, shot.width,
         shot.height)
     filename = "/tmp/droplr.png"
     screenshot.save(filename, "png")
     self.upload_file_and_notify(filename)
 def fire (self, pos):
     # Is this a hit
     for this_ship in self.ships:
         if (this_ship.fire(pos)):
             # Hit
             self.shots.append(Shot("hit",self.grid.grid_pos_to_screen_pos(pos)))
             #check if this ship sunk
             if this_ship.is_sunk():
                 # Ship sunk so make it visible
                 this_ship.hidden = False
             return True
     self.shots.append(Shot("miss",self.grid.grid_pos_to_screen_pos(pos)))
     return False
    def start(self):
        thread.start_new_thread(self.listen, ());
        while True:
            if self.fpsLimit.update() and len(self.ships):

                for i in self.run:
                    self.run[i] = 1;
                Ship.updates(self.ships, self.shoot);
                Ship.collide(self.ships, self.shots, self.explosions);
                Shot.updates(self.shots);
                self.data = (Ship.to_data(self.ships));
            else:
                time.sleep(0.0005);
Пример #14
0
 def get_shots(self):
     shots = []
     i = 0
     s = 0
     for frame in self.cutting_list:
         shot = Shot(num=s, start=i, end=frame)
         shots.append(shot)
         s += 1
         i = frame
     if i < 16200:
         shot = Shot(num=s, start=i, end=16200)
         shots.append(shot)
     self.shots = shots
Пример #15
0
def test_cp_to_file(tmp_path):
    """
    dst dir exists but dst/bar.txt does not.
    shot should create it by copying src/foo1.txt to dst/bar.txt
    """
    src_dir, dst_dir, src_file = setup_dirs(tmp_path)
    expected_output_path = dst_dir / "bar.txt"
    assert os.path.exists(src_file) == True
    assert os.path.exists(expected_output_path) == False
    s = Shot(src=str(src_dir), dst=str(expected_output_path))
    s._confirm = lambda: True  # avoid capturing stdin during test
    s()
    assert os.path.exists(src_file) == True
    assert os.path.exists(expected_output_path) == True
Пример #16
0
    def add_shot(self, for_player):
        if len(self.shots) > self.maxShots:
            return
        shot_left = bool(random.getrandbits(1))

        pos_x = for_player.position_x
        if shot_left:
            pos_x += (for_player.image.get_width() / 2)

        pos_y = for_player.position_y
        new_shot = Shot(start_pos_x=pos_x, start_pos_y=pos_y)
        new_shot.speed_y = -self.shotSpeed
        self.shots.append(new_shot)
        self.bulledSound.play()
Пример #17
0
 def test_src(self):
     s = Shot(src="dir/that/does_not/exist")
     s.console.print = MagicMock()
     s()
     s.console.print.assert_called_with(
         "src must be a directory. got:dir/that/does_not/exist\n",
         style="red")
Пример #18
0
    def test_start_and_num(self, check_output_mock, copy_mock, glob_mock):
        """
        should copy the 2 latest screenshots, starting from the 2nd latest
        """
        check_output_mock.side_effect = [b"/tmp/tests\n"]
        glob_mock.side_effect = [[
            "/tmp/tests/1", "/tmp/tests/2", "/tmp/tests/3", "/tmp/tests/4"
        ]]

        check_output_calls = [
            call(["defaults", "read", "com.apple.screencapture", "location"])
        ]
        copy_mock_calls = [
            call("/tmp/tests/2", "."),
            call("/tmp/tests/3", ".")
        ]

        s = Shot(start=2, num=2)
        s.console.print = MagicMock()
        s()
        s.console.print.assert_called_with(
            "Copied the following files from /tmp/tests to . successfully!\n['2', '3']",
            style="green",
        )
        check_output_mock.assert_has_calls(check_output_calls)
        copy_mock.assert_has_calls(copy_mock_calls)
Пример #19
0
def compile_shots(data, total_len, shot_len, heat_table):
    shot_list = []
    for i in range(min(heat_table.shape[0], total_len)):
        new_shot = Shot(i, i * shot_len, shot_len, heat_table)
        shot_list.append(new_shot)
        #print(new_shot.anchor)
    return shot_list
Пример #20
0
    def test_changing_extension_yes(self, check_output_mock, copy_mock,
                                    glob_mock):
        """
        should warn the user the extension is being changed
        """
        # make sure dst is treated as file
        # self.mock_isdir.return_value = True
        self.mock_isdir.side_effect = [False, False]
        check_output_mock.side_effect = [b"/tmp/tests\n"]
        glob_mock.side_effect = [["/tmp/tests/first.txt"]]
        print_mock_calls = [
            call(
                "Warning: src and dst extensions don't match. {'src': '.txt', 'dst': '.md'}",
                style="yellow",
            ),
            call(
                "Copied the following files from /tmp/tests to ./first.md successfully!\n['first.txt']",
                style="green",
            ),
        ]

        copy_mock_calls = [call("/tmp/tests/first.txt", "./first.md")]
        s = Shot(yes=True, dst="./first.md")
        s.console.print = MagicMock()
        s()
        s.console.print.assert_has_calls(print_mock_calls)
        copy_mock.assert_has_calls(copy_mock_calls)
Пример #21
0
 def update(self, enemies, on_screen_shots, register):
     if self.t_num != 0 and self.t_num != 7:
         aim_spot = (0, 0)
         for e in enemies:
             if is_in_circle(e.center(), self.box.center, self.range()):
                 aim_spot = e.pos()
                 if self.coolness <= 0:
                     on_screen_shots.append(
                         Shot(self.box.center, e.id, self.color(),
                              self.speed(), self.power()))
                     register(on_screen_shots[
                         len(on_screen_shots) -
                         1])  # register this bullet to be drawn
                     if self.t_num == 1:
                         on_screen_shots[len(on_screen_shots) -
                                         1].poison = True
                     if self.t_num == 2:
                         on_screen_shots[len(on_screen_shots) -
                                         1].ice = True
                     self.coolness = self.cooldown()
                     break
         if self.coolness > 0:
             self.coolness -= 1
         # point at the first enemy in range
         self.gun.update(aim_spot)
Пример #22
0
	def take_screenshot(self, widget):
		shot = Shot()
		shot.start()
		time.sleep(0.5)
		screenshot = gtk.gdk.Pixbuf.get_from_drawable(
			gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, shot.width, shot.height),
			gtk.gdk.get_default_root_window(),
			gtk.gdk.colormap_get_system(),
			shot.sX, shot.sY, 0, 0, shot.width, shot.height)
		filename = "/tmp/droplr.png"
		screenshot.save(filename, "png")
		try:
			t = Thread(target=self.upload_file_and_notify, args=(filename,)).start()
		except Exception as e:
			print e
			print "Failed to start thread"
    def communicate(self, index):
        print "Connected to ", index;

        conn = self.connections[index];
        data = conn.recv(256);
        if not data: return;
        data = eval(data);

        time.sleep(1);

        conn.send(repr(((self.data), ())));

        while True:
            if self.run[index]:
                self.run[index] = 0;
                conn = self.connections[index];
                data = None;
                try: data = conn.recv(256);
                except: break;
                if not data: break;
                data = eval(data);
                if not data[0]: self.ships[index].set_keys(data[1], data[2], data[3], data[4], data[5]);
                else: self.ships[index].set_mouse((data[1], data[2]), data[3]);

                shots = Shot.net_pack(self.queueShots[index]);
                self.queueShots[index] = list();
                #shots = list();
                #while len(self.queueShots) > 1:
                #    shots.append(self.queueShots.pop());
                conn.send(repr((self.data, shots)));
        print "Client disconnected";
        self.connections[index].close();
        self.remove_player(index);
Пример #24
0
 def test_dst(self):
     s = Shot(dst="dir/that/does_not/exist", num=2)
     s.console.print = MagicMock()
     s()
     s.console.print.assert_called_with(
         "dst must be a directory when num > 1. got:dir/that/does_not/exist\n",
         style="red")
Пример #25
0
    def test_not_enough_files_yes(self, check_output_mock, copy_mock,
                                  glob_mock):
        """
        should warn the user there are not enough files, but still copy the ones available
        """
        check_output_mock.side_effect = [b"/tmp/tests\n"]
        glob_mock.side_effect = [["/tmp/tests/1"]]

        check_output_calls = [
            call(["defaults", "read", "com.apple.screencapture", "location"])
        ]
        copy_mock_calls = [call("/tmp/tests/1", ".")]
        print_mock_calls = [
            call(
                "Warning: there are not enough files to copy with {'start': 1, 'num': 2}",
                style="yellow",
            ),
            call(
                "Copied the following files from /tmp/tests to . successfully!\n['1']",
                style="green",
            ),
        ]

        s = Shot(num=2, yes=True)
        s.console.print = MagicMock()
        s()
        s.console.print.assert_has_calls(print_mock_calls)
        check_output_mock.assert_has_calls(check_output_calls)
        copy_mock.assert_has_calls(copy_mock_calls)
Пример #26
0
    def run(self):

        # Running loop
        while self.player.alive:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()

            #added functionality to shot
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        Shot.append(Shot(self.player))

            #added functionality to move
            move = pygame.K_a - pygame.K_d
            self.player.move(move)
Пример #27
0
	def update(self):
		dx = 0
		dy = 0
		keys = self._context._system_state.inputs[self.id]
		if keys[INDEX_RIGHT]:
			dx += 1
		if keys[INDEX_LEFT]:
			dx -= 1
		if keys[INDEX_UP]:
			dy += 1
		if keys[INDEX_DOWN]:
			dy -= 1
		self.x += dx*PLAYER_SPEED
		self.y += dy*PLAYER_SPEED
		self.frame += 1
	
		if self._context.collision:
			for i in range(self._context.array_fill - 1, -1, -1):
				if (int(self._context.bullet_array[ARRAY_COLLIDE_MASK,i]) & (1 << self.id)):
					self._context.delete_bullet(i)
					self.vanish()
		
		if self._context.collisionML:
			for i in range(self._context.array_ml_fill - 1, -1, -1):
				if (int(self._context.bullet_array_ml[ARRAY_ML_COLLIDE_MASK,i]) & (1 << self.id)):
					self._context.bullet_list[i].vanish()
					self.vanish()
		
		
		if keys[INDEX_SHOT]:
			
			foe_aimed_list = []
			for foe in self._context.foe_list:
				if foe.y > self.y and abs(foe.x - self.x) < SHOT_WIDTH / 2:
					foe_aimed_list.append(foe)

			if foe_aimed_list:
				foe_choosen = random.randint(0,len(foe_aimed_list) - 1)
				shot = Shot(self._context)
				shot.x = self.x
				shot.y = self.y
				shot.aimed_foe = foe_aimed_list[foe_choosen]


		return self
Пример #28
0
    def update(self):
        dx = 0
        dy = 0
        keys = self._context._system_state.inputs[self.id]
        if keys[INDEX_RIGHT]:
            dx += 1
        if keys[INDEX_LEFT]:
            dx -= 1
        if keys[INDEX_UP]:
            dy += 1
        if keys[INDEX_DOWN]:
            dy -= 1
        self.x += dx * PLAYER_SPEED
        self.y += dy * PLAYER_SPEED
        self.frame += 1

        if self._context.collision:
            for i in range(self._context.array_fill - 1, -1, -1):
                if (int(self._context.bullet_array[ARRAY_COLLIDE_MASK, i]) &
                    (1 << self.id)):
                    self._context.delete_bullet(i)
                    self.vanish()

        if self._context.collisionML:
            for i in range(self._context.array_ml_fill - 1, -1, -1):
                if (int(self._context.bullet_array_ml[ARRAY_ML_COLLIDE_MASK,
                                                      i]) & (1 << self.id)):
                    self._context.bullet_list[i].vanish()
                    self.vanish()

        if keys[INDEX_SHOT]:

            foe_aimed_list = []
            for foe in self._context.foe_list:
                if foe.y > self.y and abs(foe.x - self.x) < SHOT_WIDTH / 2:
                    foe_aimed_list.append(foe)

            if foe_aimed_list:
                foe_choosen = random.randint(0, len(foe_aimed_list) - 1)
                shot = Shot(self._context)
                shot.x = self.x
                shot.y = self.y
                shot.aimed_foe = foe_aimed_list[foe_choosen]

        return self
Пример #29
0
 def doShoot(self):
     # Get ranom number to decide if aliens shoot in this tick.
     # The higher the level the smaller the range for the random number
     rand = randint(1, int(100 / (self.level * 2)))
     # if randint is one, a random alien shoots
     if rand == 1:
         if len(self.alienList) > 0:
             randAlien = self.alienList[randint(0, len(self.alienList) - 1)]
             shotPosx = self.getx(randAlien.id) + (randAlien.sizex / 2) - 3
             shotPosy = self.gety(randAlien.id) + randAlien.sizey
             self.shotList.append(Shot(7, 6, 0, 4, self.create_rectangle(shotPosx, shotPosy, shotPosx + 6, shotPosy + 7, width=1, tag="alienShot", fill="red")))
     # if randint is two, the bomber shoots, but only if there is no shot
     # on the pitch yet
     elif rand == 2 and len(self.find_withtag("bomber")) > 0 and len(self.find_withtag("bomberShot")) <= 1 and self.getx(self.bomber.id) > BORDER and self.bomberCooldown == 0:
         self.shotList.append(Shot(12, 12, 0, 3, self.create_image(self.getx(self.bomber.id) + (self.bomber.sizex / 2), self.gety(self.bomber.id) + self.bomber.sizey, image=self.bomber_shot_img, tag="bomberShot", anchor="nw")))
         self.bomberCooldown = 100
     elif self.bomberCooldown > 0:
         self.bomberCooldown -= 1
Пример #30
0
def events():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                new_shot = Shot(shots_group, WINDOW_SIZE)
                new_shot.rect.center = player.rect.center
Пример #31
0
 def shoot(self, e):
     if self.overheatTime == 0:
         shotPos = self.getx(self.spaceship) + SHIPSIZE / 2
         self.shotList.append(Shot(4, 10, 0, -20, self.create_rectangle(shotPos - 2, HEIGHT - SHIPSIZE, shotPos + 2, HEIGHT - SHIPSIZE - 10, width=0, fill="blue", tag="SpaceShipShot")))
         self.accShots += 1
         self.cooldown += 60
         if self.cooldown >= 200:
             self.cooldown = 199
             self.overheatTime = 70
Пример #32
0
def test_cp_multiple(tmp_path):
    src_dir, dst_dir, src_file = setup_dirs(tmp_path, nfiles=2)
    expected_output_path_one = dst_dir / "foo1.txt"
    expected_output_path_two = dst_dir / "foo2.txt"
    assert os.path.exists(expected_output_path_one) == False
    assert os.path.exists(expected_output_path_two) == False
    Shot(src=str(src_dir), dst=str(dst_dir), num=2)()
    assert os.path.exists(expected_output_path_one) == True
    assert os.path.exists(expected_output_path_two) == True
Пример #33
0
    def fire(self, rate, target=None):
        if self.fire_rate > 0:
            self.fire_rate -= 1
            return
        self.fire_rate = rate

        shot = Shot(self.screen, self.x, self.y + 40, self, target)

        player = self.screen.player

        dx = player.x - self.x
        dy = player.y - self.y - 15

        total = sqrt(dx ** 2 + dy ** 2)
        shot.xvel = dx / total * 15
        shot.yvel = dy / total * 15

        shot.range = 100
Пример #34
0
    def detect_shots(self):
        if (self._webcam_frame is None):
            self._window.after(self._preferences[DETECTION_RATE], self.detect_shots)
            return

        # Makes feed black and white
        frame_bw = cv2.cvtColor(self._webcam_frame, cv2.cv.CV_BGR2GRAY)

        # Threshold the image
        (thresh, frame_thresh) = cv2.threshold(frame_bw, 
            self._preferences[LASER_INTENSITY], 255, cv2.THRESH_BINARY)
	
        # Determine if we have a light source or glare on the feed
        if not self._seen_interference:
            self.detect_interfence(frame_thresh)     

        # Find min and max values on the black and white frame
        min_max = cv2.minMaxLoc(frame_thresh)

        # The minimum and maximum are the same if there was
        # nothing detected
        if (min_max[0] != min_max[1]):
            x = min_max[3][0]
            y = min_max[3][1]

            laser_color = self.detect_laser_color(x, y)

            # If we couldn't detect a laser color, it's probably not a 
            # shot
            if (laser_color is not None and 
                preferences[IGNORE_LASER_COLOR] not in laser_color):
  
                new_shot = Shot((x, y), self._preferences[MARKER_RADIUS],
                    laser_color)
                self._shots.append(new_shot)
                new_shot.draw_marker(self._webcam_canvas)

                # Process the shot to see if we hit a region and perform
                # a training protocol specific action and any if we did
                # command tag actions if we did
                self.process_hit(new_shot)

        if self._shutdown == False:
            self._window.after(self._preferences[DETECTION_RATE], self.detect_shots)
Пример #35
0
 def test_no_files(self, check_output_mock, glob_mock):
     """
     should warn the user no files were found
     """
     check_output_mock.side_effect = [b"/tmp/tests/empty\n"]
     glob_mock.side_effect = [[]]
     s = Shot()
     s.console.print = MagicMock()
     s()
     s.console.print.assert_called_with(
         "No files found in /tmp/tests/empty", style="red")
Пример #36
0
def test_mv(tmp_path):
    """
    src file should not exist after running shot, dst file should
    """
    src_dir, dst_dir, src_file = setup_dirs(tmp_path)
    expected_output_path = dst_dir / "foo1.txt"
    assert os.path.exists(src_file) == True
    assert os.path.exists(expected_output_path) == False
    Shot(src=str(src_dir), dst=str(dst_dir), mv=True)()
    assert os.path.exists(src_file) == False
    assert os.path.exists(expected_output_path) == True
Пример #37
0
class Laser:
    anim_frame = NORMAL

    is_check = False
    is_bad = True
    is_solid = False
    is_switch = False

    def __init__(self, x: int, y: int, game_ref: 'Game', cam_ref: 'Camera',
                 spd: int) -> None:
        self.x = x
        self.y = y
        self.update = self.idle
        self.cam_ref = cam_ref
        self.max_timer = spd * FREQ
        self.timer = self.max_timer
        self.shot = Shot(self.x, self.y)
        game_ref.game_objects["shot"].append(self.shot)

    def draw(self, cam: 'Camera'):
        pyxel.blt(self.x - cam.x, self.y - cam.y, 0, self.anim_frame * 8, ROW,
                  8, 8, 0)

    def idle(self):
        self.timer -= 1
        if self.timer <= 0 and not self.shot.is_alive:
            self.anim_frame = SHOOTING
            self.timer = 5
            self.update = self.shooting
            self.shot.fire()

            if is_on_screen(self.x, self.y, self.cam_ref):
                pyxel.play(0, 21)

    def shooting(self):
        self.shot.update()
        self.timer -= 1
        if self.timer <= 0:
            self.timer = self.max_timer
            self.update = self.idle
            self.anim_frame = NORMAL
Пример #38
0
def test_cp(tmp_path):
    """
    src file should be unchanged, dst file should exist after running shot
    """
    src_dir, dst_dir, src_file = setup_dirs(tmp_path)
    expected_output_path = dst_dir / "foo1.txt"
    assert os.path.exists(src_file) == True
    assert os.path.exists(expected_output_path) == False
    Shot(src=str(src_dir), dst=str(dst_dir))()
    assert os.path.exists(src_file) == True
    assert os.path.exists(expected_output_path) == True
    tear_down_dirs(tmp_path)
Пример #39
0
def test_mv_to_file(tmp_path):
    """
    dst dir exists but dst/bar.txt does not.
    shot should create it by copying src/foo1.txt to dst/bar.txt
    """
    src_dir, dst_dir, src_file = setup_dirs(tmp_path)
    expected_output_path = dst_dir / "bar.txt"
    assert os.path.exists(src_file) == True
    assert os.path.exists(expected_output_path) == False
    Shot(src=str(src_dir), dst=str(expected_output_path), mv=True)()
    assert os.path.exists(src_file) == False
    assert os.path.exists(expected_output_path) == True
Пример #40
0
	def FirePrimary(self):
		for i in range(6):
			shot = Shot(self.root, self.x, self.y)
			shot.owner = self.owner
			shot.direction = self.direction + (7 - random.randint(0, 15))

			shot.speed = 100 + (20 - random.randint(0, 40))

			radDirection = math.radians(shot.direction)
			shot.hspeed = math.cos(radDirection) * shot.speed + self.owner.hspeed/2
			shot.vspeed = math.sin(radDirection) * -shot.speed

			shot.speed = math.hypot(shot.hspeed, shot.vspeed)
			self.refireAlarm = self.refireTime
			
    def fire_shot(self):
        """
        Creates a shot according toa power value given
        Then creates the effects that follow a shot being fired
        """
        
        self.change_mode(Modes.Draw_Shot)

        enemy_tank = self.enemy_team
        current_tank = self.cur_team

        self.current_shot = Shot(self.current_power, current_tank.get_angle(), current_tank, enemy_tank, self._map_resolution[1], self._map_resolution[0])
        self.shot_path = self.current_shot.get_path()
        self.shot_path_index = 0 

        #play shot sound
        self.sound_controller.play("TankFire");
Пример #42
0
    def doctor_attack_loop(self):
        speed = 6
        self.feeling = 'walking'
        g = self.g

        if self.health <= 0:
            #destoryed walking too 813
            targntx = self.rect.x
            if targntx > 813 + speed * 2: # walked too far left left
                self.dx -= .5
                if self.dx < -speed:
                    self.dx = -speed
                self.rect.x += int(self.dx)
                self.timer = self.timer % 10
            elif targntx < 813 - speed * 2:# walked too far right
                self.dx += .5
                if self.dx > speed:
                    self.dx = speed
                self.rect.x += int(self.dx)
                self.timer = self.timer % 10
            else:
                if self.spawnedspecialnurse == 0:
                    print 'spawn special nurse'
                    self.spawnedspecialnurse = 1
                    s = Shot(self.g, self.direction, (self.rect.x + 128, self.rect.y + 80 ), 'shot6', 'enemy')
                    s.callback = self.create_nurse_character
                    s.xvel = 0
            if self.timer < 70:
                if self.timer % 3 == 0:
                    # flash on and off
                    self.image = pygame.Surface((1, 1), SRCALPHA)
                else:
                    x = random.randint(0, 256)
                    y = random.randint(0, 256)
                    Effect(self.g, 'explosion', (self.rect.x + x, self.rect.y + y))
            return
        #self.timer += 1
        dx = (self.rect.x + self.rect.width/2) - g.player.rect.x
        dy = (self.rect.y + self.rect.height) - g.player.rect.y
        pdrect = 100
        if self.timer % 1000 > 400:
            pdrect = 400
            if self.dx < 0 and self.dx > -speed:
                self.dx += -.5
            if self.dx > 0 and self.dx < speed:
                self.dx += .5
        if dx > pdrect: # walked too far left left
            self.dx -= .5
            if self.dx < -speed:
                self.dx = -speed
        elif dx < -pdrect:# walked too far right
            self.dx += .5
            if self.dx > speed:
                self.dx = speed

        # attck with arms
        if dx > 70 and dx < 140:
            if dy <50 and dy > 0:
                if self.attackleft == 0:
                    self.attackleft = 1
                if self.attackleft == 5:
                    g.player.touch(self)
        # attack with the right arm
        if dx < -70 and dx > -140:
            if dy <50 and dy > 0:
                if self.attackright == 0:
                    self.attackright = 1
                if self.attackright == 5:
                    g.player.touch(self)
        # scratching self to stop continius shooting
        if self.timer % 1000 > 600:
            self.attackright = 10
        # tracks hittin the player
        #if dx > -40 and dx < 40:
        #    if dy < 40 and dy > 0:
        #        g.player.touch(self)
        # like the monotane, it shits out little babies
        if self.timer % 20 == 1:
            if self.timer % 400 < 200:
                c = random.randint(0, 20)
                s = Shot(self.g, self.direction, (self.rect.x + 128, self.rect.y + 80 + c), 'shot6', 'enemy')
                s.callback = self.create_nurse_monster
                self.squirt.play()


        self.rect.x += int(self.dx)
        self.draw_health_meter()
Пример #43
0
    def fox_attack_loop(self):
        g = self.g

        if self.health <= 0:
            self.feeling = 'sad'
            self.health = 0
            if self.attacking == 3:
                self.feeling = 'dead'
                self.rect.y += 3
            else:
                self.attacking = 0
            self.walking = 0
            self.jumping = 0
            self.walktopos = (self.rect.x, self.rect.y)
            return
        
        self.timer += 1

        if self.jumping == 1:
            self.rect.y += self.jumpvec
            self.jumpvec += 1

        # if timer is in the minus, you're firing for a while
        if self.timer < 0:
            self.walking = 0
            if self.timer < -10:
                self.feeling = 'shooting'
                if self.attacking == 1:# first battle
                    if self.timer % 2 == 0:
                        s = Shot(g, self.direction, (self.rect.x + 44, self.rect.y + 35), 'shot3', 'enemy')
                elif self.attacking == 2: # second battle
                    if self.timer % 4 == 0:
                        s = Shot(g, self.direction, (self.rect.x + 44, self.rect.y + 35), 'shot3', 'enemy')
                        s.keep_alive = 6
                elif self.attacking == 3: # last
                    if self.timer % 10 == 0:
                        s = Shot(g, self.direction, (self.rect.x + 44, self.rect.y + 35), 'shot8', 'enemy')
        else:
            self.feeling = 'normal'
            speed = 4
            if self.attacking == 2:
                speed = 5
            self.rect.x += (1 - (self.direction * 2)) * speed
            self.rect.y += 2 # gravity
            if self.walktopos == (self.rect.x, self.rect.y) : # walking into something
                self.jumping = 1
                self.jumpvec = -10
            if self.attacking == 1: # first battle with fox
                if self.timer == 2:
                    self.jumping = 1
                    self.jumpvec = -10
                # shooting every random interval
                if random.randint(0, 70) == 0 and self.framecount > 10:
                    self.timer = -30
            if self.attacking == 2 or self.attacking == 3: # second battle with Fox
                dv = self.rect.x - self.g.player.rect.x
                if dv > 200:
                    self.direction = 1
                if dv < -200:
                    self.direction = 0
                if self.jumping == 0:
                    # jumping every 30 frames
                    if self.framecount % 40 == 0 and self.jumping == 0:
                        self.jumping = 1
                        self.jumpvec = -10
                        if self.attacking == 3:
                            self.jumpvec = -15
                    # shooting every random interval
                    elif random.randint(0, 15) == 0 and self.framecount > 10:
                        self.timer = -30
            self.framecount += 1
            self.walking = 1
            self.walktopos = (self.rect.x, self.rect.y)
        
        # hitting the bullets and player
        s = Rect(self.rect)
        if s.colliderect (g.player.rect):
            g.player.touch(self)
        for b in g.bullets:
            if b.owner == 'player':
                drect = (b.rect.x + 30, b.rect.y )
                if s.collidepoint(drect):
                    b.destroy()
                    self.health -= b.get_damage()
                    e = Effect(self.g, 'health', (self.rect.x, self.rect.y))
                    e.healthchange = -b.get_damage()
                    if self.feeling != 'sad':
                        self.hitme.play()
                    self.feeling = 'sad'
                    self.image = g.make_image_white(self.image, (96, 64))
class Interface():
    """
    """
    def __init__(self, level, bg_color, pygame):
        """
        Initialize the game's interface
        """
        # Setup variables
        self._level = level
        self._pygame = pygame
        self._bg_color = bg_color

        #Start in player 1 move mode
        self.mode = Modes.Move

        # Load the level information
        # This method also initialize the screen size
        #   according to the map size
        self._loadLevel()

        #Load all the sounds
        self.sound_controller = SoundsController()

        # The status bar
        self.status_bar = pygame.Rect(0, self._map_resolution[1],
                                     self._screen_resolution[0],
                                     STATUS_BAR_HEIGHT)

        # The power bar
        self.power_bar = pygame.Rect(COLUMN_WIDTH + (COLUMN_WIDTH - 100)/2 , self._map_resolution[1] + 80,
                                     100,
                                     POWER_BAR_HEIGHT)

        self.power_outline = self.power_bar.copy()
        self.power_outline.w -= 1
        self.power_outline.h -= 1

        #Set friendly fire
        self.friendly_fire = True

        # Current power
        self.current_power = 20
        self.current_power_increasing = True

        #Initialize tanks
        self.p1_tank = Tank([70, 560], 1)
        self.p2_tank = Tank([1110, 560], 2)

        #Initilize turn number
        self.turn = 1
        #The first one to play is random (not always player 1)
        self.players_turn = randrange(2)+1

        #Set the number of turns
        self.num_teams = 2

        #Load the map information
        self._map = Map(level, bg_color)

        #Initialize the screen
        self._windowSurfaceObj = pygame.display.set_mode(self._screen_resolution)
        self._windowSurfaceObj.fill(bg_color)

        self._map.paintMountain(self._windowSurfaceObj)
        self.draw_bar()
        self.draw_tank(self.p1_tank)
        self.draw_tank(self.p2_tank)

    def _loadLevel(self):
        """
        Load the level information
        """
        #gets the filename
        filename = "maps/" + self._level + ".lvl"
        
        map_file = open(filename, 'r')
        
        # Move up to the line with the size of the map
        line = map_file.readline()
        while line.find("Size: ") < 0:
            line = map_file.readline()
            if line == "":
                raise Exception ("Expected Map Size.")

        # Get the size of the map
        line = line.lstrip("Size: ")
        line = line.strip()
        size = line.split('x')
        map_width, map_height = size
        map_width = int(map_width)
        map_height = int(map_height)

        # Move up to the line with the tank area
        line = map_file.readline()
        while line.find("TankArea: ") < 0:
            line = map_file.readline()
            if line == "":
                raise Exception ("Expected Tank Area.")

        # Get the size of the map
        line = line.lstrip("TankArea: ")
        self._tank_area = line.strip()

        self._map_resolution = (map_width, map_height)
        self._screen_resolution = (map_width, map_height+STATUS_BAR_HEIGHT)

    def update(self):
        """
        Update the interface. This method is called on every frame.
        """
        #Update the display
        self._pygame.display.update()

        # draw the bar
        self.draw_bar()

        #Check if we are supposed to draw the shot
        if self.mode == Modes.Draw_Shot:

            if self.shot_path_index < len(self.shot_path):
                
                #Erase old bullet
                if self.shot_path_index > 0:
                    pos = self.shot_path[self.shot_path_index-1]
                    x = pos[0]
                    y = pos[1]
                    self.erase_shot(x,y)

                #Draw current shot position
                pos = self.shot_path[self.shot_path_index]
                x = pos[0]
                y = pos[1]

                #Check for bounds
                if x >= 0 and y >= 0 and x < self._map_resolution[0] and   y < self._map_resolution[1]:

                    #Get the circle inside the rectangle
                    circle_rect = self.draw_shot(x,y)

                    #Check if the shot hit an obstacle
                    #  For example: if it hit the mountain or a tank
                    if self.shot_path_index > 2 and circle_rect.colliderect(self.p1_tank.get_rect()):
                        self.erase_shot(x,y)
                        self.finish_shot_firing(False, did_hit_team=1)
                    elif self.shot_path_index > 2 and circle_rect.colliderect(self.p2_tank.get_rect()):
                        self.erase_shot(x,y)
                        self.finish_shot_firing(False, did_hit_team=2)
                    elif self._map.didShotHitMountain(circle_rect, self.current_power, self._windowSurfaceObj):
                        self.erase_shot(x,y)
                        self.finish_shot_firing(True, pos=(x,y))



                #Increase the index
                self.shot_path_index += 1

            #If this is the last time, erase the shot
            elif self.shot_path_index == len(self.shot_path) and self.shot_path_index > 0:
                pos = self.shot_path[self.shot_path_index-1]
                x = pos[0]
                y = pos[1]
                self.erase_shot(x,y)

                self.finish_shot_firing(False)

            #Redraw both tanks (just in case the shot hit the tank)
            self.erase_tank(self.p1_tank)
            self.draw_tank(self.p1_tank)
            self.erase_tank(self.p2_tank)
            self.draw_tank(self.p2_tank)

            #If game over
            if self.mode == Modes.GameOver:
                #Call animation to destroy the tank
                self.explode_tank(self.enemy_team)


    def draw_bar(self):
        """
        Draws the info bar on the bottom of the screen. 
        """        
        #draw the background of the bar
        pygame.draw.rect(self._windowSurfaceObj, STATUS_BAR_COLOR, self.status_bar)
        
        #draw the outline of the bar
        outlineRect = self.status_bar.copy()
        outlineRect.w -= 1
        outlineRect.h -= 1
        pygame.draw.rect(self._windowSurfaceObj, OUTLINE_COLOR, outlineRect, 2)

        #draw lines between players information
        pygame.draw.line(
            self._windowSurfaceObj,
            OUTLINE_COLOR,
            (COLUMN_WIDTH, self._map_resolution[1]),
            (COLUMN_WIDTH, self._map_resolution[1]+STATUS_BAR_HEIGHT))

        pygame.draw.line(
            self._windowSurfaceObj,
            OUTLINE_COLOR,
            (2*COLUMN_WIDTH, self._map_resolution[1]),
            (2*COLUMN_WIDTH, self._map_resolution[1]+STATUS_BAR_HEIGHT))

        #draw player 1's information
        y = 0
        y += 5 + self.draw_info_text('Player 1', MEDIUM_FONT, MEDIUM_FONT_SIZE, y, 0)
        y += self.draw_info_text('HP:        {:10.1f}%'.format(self.p1_tank.get_hp_as_percentage()), FONT, FONT_SIZE, y, 0)
        y += self.draw_info_text('Angle:    {:10.1f}°'.format(self.p1_tank.get_angle()), FONT, FONT_SIZE, y, 0)
        self.draw_info_text('Power:  {:10.1f}%'.format(self.p1_tank.get_power_as_percentage()), FONT, FONT_SIZE, y, 0)

        #draw game information
        y = 0
        if self.mode == Modes.GameOver:
            y += 5 + self.draw_info_text('Game Over!', BIG_FONT, BIG_FONT_SIZE, y, 1)
            y += self.draw_info_text('Player {} won!'.format(self.players_turn), MEDIUM_FONT, MEDIUM_FONT_SIZE, y, 1)
        else:
            y += 5 + self.draw_info_text('Day {}'.format(self.turn), BIG_FONT, BIG_FONT_SIZE, y, 1)
            y += self.draw_info_text('Player {}\'s turn'.format(self.players_turn), FONT, FONT_SIZE, y, 1)


        #If we are firing, draw the power bar
        if self.mode == Modes.Firing:
            
            self.calculate_power()
            self.power_bar.w = self.current_power
            
            pygame.draw.rect(self._windowSurfaceObj, (POWER_BAR_COLOR[0]+self.current_power,POWER_BAR_COLOR[1]-self.current_power,POWER_BAR_COLOR[2]) , self.power_bar)
            pygame.draw.rect(self._windowSurfaceObj, OUTLINE_COLOR, self.power_outline, 2)


        #draw player 2's information
        y = 0
        y += 5 + self.draw_info_text('Player 2', MEDIUM_FONT, MEDIUM_FONT_SIZE, y, 2)
        y += self.draw_info_text('HP:        {:10.1f}%'.format(self.p2_tank.get_hp_as_percentage()), FONT, FONT_SIZE, y, 2)
        y += self.draw_info_text('Angle:    {:10.1f}°'.format(abs(self.p2_tank.get_angle())), FONT, FONT_SIZE, y, 2)
        self.draw_info_text('Power:  {:10.1f}%'.format(self.p2_tank.get_power_as_percentage()), FONT, FONT_SIZE, y, 2)



    def draw_info_text(self, text, font, font_size, y, column):
        """
        Draws given text with given information.
        """
        line_text = font.render(text, True, FONT_COLOR)
        self._windowSurfaceObj.blit(
            line_text,
            (column*COLUMN_WIDTH + PAD, self._map_resolution[1] + y + PAD))
        return font_size + PAD

    def draw_tank(self, tank):
        """
        Draws given tank
        """
        pos = tank.get_position()
        barrel_pos = tank.get_barrel_position()

        #Rotate the barrel image
        barrel_img = pygame.transform.rotate(tank.image_barrel, tank.get_angle())

        #Calculate the barrel's fixed position - because of the rotation
        y = math.sin(math.radians(abs(tank.get_angle())))*44

        #Defines the x according to the tank and update the initial shot position
        if tank.team == 1:
            x = 0
            tank.set_shot_start_position(barrel_pos[0] + barrel_img.get_width(), barrel_pos[1]-y)
        else: 
            x = 56 - barrel_img.get_width()
            tank.set_shot_start_position(barrel_pos[0] + x, barrel_pos[1]-y)

        #Draw the tank and the barrel
        self._windowSurfaceObj.blit(tank.image, (pos[0],pos[1]))
        self._windowSurfaceObj.blit(barrel_img, (barrel_pos[0] + x,barrel_pos[1]-y))
        pygame.display.flip()

    def draw_shot(self, x,y):
        """
        Draw a shot on given positon
        """
        return pygame.draw.circle(self._windowSurfaceObj, SHOT_COLOR, (x,y), SHOT_RADIUS)

    def erase_shot(self, x,y):
        """
        Erase a shot on given position
        """
        pygame.draw.circle(self._windowSurfaceObj, self._bg_color, (x,y), SHOT_RADIUS)


    def calculate_power(self):
        """
        Calculates the new power.

        It should increase every frame until it reaches 100.
        After, it decreases until 20 - and keeps going like this until
        the user hits space again
        """
        if self.current_power > 80:
            rate = 3.5
        elif self.current_power > 60:
            rate = 2.3
        elif self.current_power > 40:
            rate = 1.8
        elif self.current_power > 20:
            rate = 1.1
        else:
            rate = 0.5

        if self.current_power_increasing:
            self.current_power += rate

            if self.current_power >= 100:
                self.current_power = 100
                self.current_power_increasing = False

        else:
            self.current_power -= rate

            if self.current_power <= 0:
                self.current_power = 0
                self.current_power_increasing = True

        self.cur_team.update_power(self.current_power)

    def erase_tank(self, tank):
        """
        Erases tank
        """
        pygame.draw.rect(self._windowSurfaceObj, self._bg_color, (tank.position[0],tank.position[1]-45,103,85))
        #pygame.draw.rect(self._windowSurfaceObj, self._bg_color, tank.get_rect())
    
    def explode_tank(self, tank):
        """
        Animation to destroy tank
        """
        self.erase_tank(tank)

    @property
    def cur_team(self):
        """
        Returns the string name of the tank who's turn it currently is. 
        """
        if self.players_turn == 1:
            return self.p1_tank
        else:
            return self.p2_tank
       
    @property
    def enemy_team(self):
        """
        Returns the string name of the tank who's turn it currently is. 
        """
        if self.players_turn == 1:
            return self.p2_tank
        else:
            return self.p1_tank


    def move_tank(self, value):
        """
        Move the tank according to if the left or right arrow was pressed

        """
        if self.mode != Modes.Move:
            return
        
        #Get the current tank
        current_tank = self.cur_team

        #Erase it
        self.erase_tank(current_tank)

        #Move it accordingly
        if value == "left":
            current_tank.move_tank([-3,0])

        else:
            current_tank.move_tank([3,0])
        
        #Redraw it
        self.draw_tank(current_tank)

    def change_angle(self, value):
        """
        Change the angle of the tank barrel according to if the up 
        or down arrow key was pressed
        """
        if self.mode != Modes.Move:
            return

        #Get the current tank
        current_tank = self.cur_team

        #Erase it
        self.erase_tank(current_tank)

        #Change the angle accordingly
        if value == "up":
            current_tank.change_barrel_angle(1)

        else:
            current_tank.change_barrel_angle(-1)
            
        #Redraw the tank
        self.draw_tank(current_tank)


    def select_power(self):
        """
        After hitting space to fire, we need to use a timer or somthing
        between events to calculate how hard the shot should be.
        This will eventually read from the arduino potentiometer value and pass that 
        to the shot class. 
        So maybe for now we will hard code it to be (0-100)

        """
        if self.mode != Modes.Move:
            return

        self.change_mode(Modes.Firing)
        
        #self.draw_power_bar()
        #self.


    def release_power(self):
        if self.mode != Modes.Firing:
            return

        self.fire_shot()
        self.current_power = 20
        self.current_power_increasing = True


    def fire_shot(self):
        """
        Creates a shot according toa power value given
        Then creates the effects that follow a shot being fired
        """
        
        self.change_mode(Modes.Draw_Shot)

        enemy_tank = self.enemy_team
        current_tank = self.cur_team

        self.current_shot = Shot(self.current_power, current_tank.get_angle(), current_tank, enemy_tank, self._map_resolution[1], self._map_resolution[0])
        self.shot_path = self.current_shot.get_path()
        self.shot_path_index = 0 

        #play shot sound
        self.sound_controller.play("TankFire");
        #self.sound_controller.play("BombDrop");
         

    def finish_shot_firing(self, didHitMountain, did_hit_team=0, pos=None):
        """
        This method is called after we finish drawing the shot and need to finish the player's turn
        """

        enemy_tank = self.enemy_team
        current_tank = self.cur_team


        if self.players_turn == 1:
            enemy_team_number = 2
        else:
            enemy_team_number = 1

        if pos:
            self.explosion(pos[0], pos[1], 15)
        elif did_hit_team != 0:
            if did_hit_team == 1:
                pos = [(self.p1_tank.get_rect().x + (self.p1_tank.get_rect().w/2)),(self.p1_tank.get_rect().y + (self.p1_tank.get_rect().h/2))]
            elif did_hit_team == 2:
                pos = [(self.p2_tank.get_rect().x + (self.p2_tank.get_rect().w/2)),(self.p2_tank.get_rect().y + (self.p2_tank.get_rect().h/2))]

            self.explosion(pos[0], pos[1], 25)
            

        #If we didn't hit the mountain and did hit the other tank, decrease his hp
        if not didHitMountain and did_hit_team == enemy_team_number:
            enemy_tank.take_damage(self.current_power*HIT_PERCENTAGE)

            #If the enemy was killed, game over!
            if not enemy_tank.active:
                self.change_mode(Modes.GameOver)
                self.erase_tank(enemy_tank)
                return

        #If we didn't hit the mountain, friendly fire is on and we did hit ourselves
        if not didHitMountain and self.friendly_fire and did_hit_team == self.players_turn:
            current_tank.take_damage(self.current_power*HIT_PERCENTAGE)

            #If the played killed himself, game over!
            if not current_tank.active:
                if self.players_turn == 1:
                    self.players_turn = 2
                else:
                    self.players_turn = 1

                self.change_mode(Modes.GameOver)
                self.erase_tank(current_tank)
                return

        self.change_mode(Modes.Move)
        self.next_turn()


    def next_turn(self):
        self.turn +=1

        #Updates the the player's turn variable
        # Which is, whoever turn is it
        if self.players_turn == 1:
            self.players_turn = 2
        else:
            self.players_turn = 1


    def change_mode(self, mode):
        if self.mode == mode:
            return

        self.mode = mode

    def explosion(self, x, y, radius):
        """
        Creates an explosion animation centered at x,y with a radius
            Note: the animation is poorly done, but it's better than nothing.
                   and there's no time to improve it, unfortunatelly
        """
        self.sound_controller.play("Explosion")

        for i in range(1,10):
            pygame.draw.circle(self._windowSurfaceObj, ( round(100+(i*10)),round(100-(i*10)),0) , (round(x),round(y)), round((radius/10)*i))
            self._pygame.display.update()

        for i in range(10,1):
            pygame.draw.circle(self._windowSurfaceObj, ( round(100+(i*10)),round(100-(i*10)),0) , (round(x),round(y)), round((radius/10)*i))
            self._pygame.display.update()
        
        pygame.draw.circle(self._windowSurfaceObj, self._bg_color, (round(x),round(y)), round(radius))
Пример #45
0
    def loop(self, g, r):
        if g.dead == 1:
            self.image = self.orginalImage.subsurface((0, 0, 0, 0))
            return

        keys = pygame.key.get_pressed()
        dy = 0
        self.pos = g.screen_to_tile((g.player.rect.x - g.view.x + 8, g.player.rect.y - g.view.y + 16))
        faced = 0
        aimup, aimdown = 0, 0
        shooting = 0

        # move the player
        if g.intermission == 0:
            jumpkeydown = 0
            if keys[K_DOWN]:
                faced = 1
                if g.infobox:
                    self.staylooking = 1
                if self.jumpshoot:
                    aimdown = 1
            if keys[K_UP]:
                faced = 2
                # jump
                aimup = 1
            if keys[K_LEFT]:
                faced = 0
                self.staylooking = 0
                self.dx -= SPEED
                self.direction = 1
                if g.player.canjump:
                    self.framecount += 1
            if keys[K_RIGHT]:
                faced = 0
                self.staylooking = 0
                self.dx += SPEED
                self.direction = 0
                if g.player.canjump:
                    self.framecount += 1
            if keys[K_LEFT] and keys[K_RIGHT]:
                self.framecount = 0
            if keys[K_z]:
                if g.player.canjump == 1 and g.player.gravity == 0 and g.disable_fire == 0:
                    g.player.canjump = 0
                    g.player.gravity += self.jump_gravity
                    g.player.jumping = 1
                    self.jumpsound.play()
            if keys[K_x]:
                # firing code
                shooting = 1
                if g.level.weapon_gui == 0 and g.level.inventory_gui == 0:
                    if "weapon" in g.saveData and g.disable_fire == 0:
                        if self.shotcounter <= 0 and g.saveData["weapon"] > 0:
                            xoffset = (not self.direction) * 2
                            shottype = "shot" + str(g.saveData["weapon"])
                            sdirection = self.direction
                            if aimup:
                                sdirection = 2
                            if aimdown:
                                sdirection = 3
                            s = None
                            if shottype == "shot2":
                                s = Shot2(g, sdirection, (self.rect.x - xoffset, self.rect.y + 20))
                            elif shottype == "shot4":
                                s = Shot4(g, sdirection, (self.rect.x - xoffset, self.rect.y + 20))
                            else:
                                s = Shot(g, sdirection, (self.rect.x - xoffset, self.rect.y + 20), shottype)
                            s.invisible_timer = 1
                            self.shotcounter += s.get_reload_time()
            self.jumpshoot = 0
            if jumpkeydown == 0 and self.canjump == 0:
                self.jumpshoot = 1
            if g.disable_fire != 0:
                g.disable_fire += 1
                if g.disable_fire > 3:
                    g.disable_fire = 0
            # the gui disables firing
            # if not keys[K_z]:
            #    g.disable_fire = 0
            # if not keys[K_x]:
            #    g.disable_fire = 0
        # not walking
        if not keys[K_LEFT] and not keys[K_RIGHT]:
            self.framecount = 0

        # not going anywhere
        if keys[K_LEFT] and keys[K_RIGHT]:
            if self.dx > 0:
                self.dx -= SPEED
            if self.dx < 0:
                self.dx += SPEED
        if g.intermission:
            self.dx = 0

        if not keys[K_RIGHT] and self.dx > 0:
            self.dx -= SPEED
        if not keys[K_LEFT] and self.dx < 0:
            self.dx += SPEED

        if self.dx > self.maxspeed:
            self.dx = self.maxspeed
        if self.dx < -self.maxspeed:
            self.dx = -self.maxspeed

        # move camera with player
        if not g.intermission:
            if g.player.rect.x - g.view.x > SW - 200 and self.dx > 0:
                g.view.x += self.dx
            if g.player.rect.x - g.view.x < 200 and self.dx < 0:
                g.view.x += self.dx
            if g.player.rect.y - g.view.y > SH - 180:

                if self.maxspeed < dy - g.player.gravity:

                    g.view.y += dy - g.player.gravity
                else:
                    g.view.y += self.maxspeed
            if g.player.rect.y - g.view.y < 100:
                g.view.y -= self.maxspeed

        weaponvisible = 0
        if "weapon" in g.saveData:
            if g.saveData["weapon"] != 0:
                weaponvisible = 1

        # animation
        iw, ih = g.player.image.get_width(), g.player.image.get_height()
        if weaponvisible == 0 or self.dieanimation == 1:
            g.player.image = g.player.orginalImage.subsurface((iw * ((self.framecount / 3) % 5), 0, 32, 32))

            if g.following:
                # draw hand
                if g.connected == 1 and self.direction == 1:
                    g.player.image = pygame.Surface((32, 32), SRCALPHA)
                    g.player.image.blit(
                        g.player.orginalImage.subsurface((iw * ((self.framecount / 3) % 5), 6 * 32, 32, 32)), (0, 0)
                    )
                    g.player.image.blit(g.player.orginalImage.subsurface((2 * 32, 4 * 32, 32, 32)), (7, 0))
                    g.player.image = pygame.transform.flip(g.player.image, self.direction, 0)

            # looking forward
            if faced == 1 or self.staylooking:
                g.player.image = g.player.orginalImage.subsurface((5 * 32, 0, 32, 32))
            if faced == 2:
                g.player.image = g.player.orginalImage.subsurface((1 * 32, 32, 32, 32))
            # animations...
            if self.animation == 1:
                g.player.image = g.player.orginalImage.subsurface((6 * 32, 0, 32, 32))
            elif self.animation == 2:
                g.player.image = g.player.orginalImage.subsurface((7 * 32, 0, 32, 32))
            elif self.animation == 3:
                g.player.image = g.player.orginalImage.subsurface((0 * 32, 32, 32, 32))
            g.player.image = pygame.transform.flip(g.player.image, self.direction, 0)
        else:
            if self.direction == 0:
                g.player.image = g.player.orginalImage.subsurface((iw * ((self.framecount / 3) % 5), 2 * 32, 32, 32))
            else:
                if g.following:
                    g.player.image = pygame.Surface((32, 32), SRCALPHA)
                    g.player.image.blit(
                        g.player.orginalImage.subsurface((iw * ((self.framecount / 3) % 5), 5 * 32, 32, 32)), (0, 0)
                    )

                    # draw hand
                    if g.connected == 1 and self.direction == 1:
                        g.player.image.blit(g.player.orginalImage.subsurface((2 * 32, 4 * 32, 32, 32)), (7, 0))
                else:
                    g.player.image = g.player.orginalImage.subsurface(
                        (iw * ((self.framecount / 3) % 5), 3 * 32, 32, 32)
                    )
            # looking forward
            if (faced == 1 or self.staylooking) and not shooting and not self.jumping:
                if self.direction == 0:
                    g.player.image = g.player.orginalImage.subsurface((5 * 32, 2 * 32, 32, 32))
                else:
                    g.player.image = g.player.orginalImage.subsurface((5 * 32, 3 * 32, 32, 32))
            if faced == 2:
                if self.direction == 0:
                    g.player.image = g.player.orginalImage.subsurface((4 * 32, 1 * 32, 32, 32))
                else:
                    g.player.image = g.player.orginalImage.subsurface((5 * 32, 1 * 32, 32, 32))
            if self.jumping == 1:
                if self.direction == 0:
                    g.player.image = g.player.orginalImage.subsurface((6 * 32, 2 * 32, 32, 32))
                else:
                    g.player.image = g.player.orginalImage.subsurface((6 * 32, 3 * 32, 32, 32))
            if aimup:
                if self.direction:
                    self.image = g.player.orginalImage.subsurface((5 * 32, 1 * 32, 32, 32))
                else:
                    self.image = g.player.orginalImage.subsurface((4 * 32, 1 * 32, 32, 32))
            if aimdown:
                if self.direction:
                    self.image = g.player.orginalImage.subsurface((7 * 32, 1 * 32, 32, 32))
                else:
                    self.image = g.player.orginalImage.subsurface((6 * 32, 1 * 32, 32, 32))
        if g.player.gravity == 0:
            self.jumping = 0
        self.looking = faced
        g.infobox = 0

        if self.hidden == 1:
            self.image = self.orginalImage.subsurface((0, 0, 0, 0))

        # getting shot
        for b in g.bullets:
            if b.owner == "enemy":
                drect = (b.rect.x, b.rect.y)
                if self.rect.collidepoint(drect):
                    self.touch(b)

        # edge
        g.player.gravity -= GRAVITY
        if g.player.gravity < MAXVEL:
            g.player.gravity = MAXVEL
        self.rect.x += self.dx
        self.rect.y += dy - g.player.gravity
        # self.rect.clamp_ip(g.view)

        # dead ...
        if self.health <= 0 and not g.dead:
            g.dead = 1
            g.exp2.play()
        if self.imortal > 0:
            if self.imortal / 5 % 2 == 0:
                g.player.image = g.make_image_white(g.player.image)
            self.imortal -= 1

        # getting demoted
        if self.g.saveData["weapon"] > 1:
            shottype = "shot" + str(self.g.saveData["weapon"])
            if self.g.saveData[shottype] == 0:
                if self.g.saveData["weapon"] == 2:
                    self.g.saveData["weapon"] = 1
                elif self.g.saveData["weapon"] == 4:
                    self.g.saveData["weapon"] = 2
                elif self.g.saveData["weapon"] == 7:
                    self.g.saveData["weapon"] = 4
                else:
                    print "weapon not down graded"

        # reloading the gun
        if self.shotcounter > 0:
            self.shotcounter -= 1