class JRPGAttackTests(unittest.TestCase): def setUp(self): self.p1 = Character() self.p2 = Character() self.mwfar = rules.JRRPGRules.attack_resolution # d20 = MagicMock(return_value=19) just not to forget def test_main_weapon_full_attack_resolution_barehands(self): rules.d20 = object() rules.d20 = 3 self.assertEqual(self.mwfar(self.p1, self.p2), (-7, "miss")) rules.d20 = 10 self.assertEqual(self.mwfar(self.p1, self.p2), (0, "hit")) rules.d20 = 20 self.assertEqual(self.mwfar(self.p1, self.p2), (10, "critical hit")) rules.d20 = 1 # mocking self.assertEqual(self.mwfar(self.p1, self.p2), (-9, "critical miss")) def test_dagger_full_attack(self): self.p1.equip_primary_weapon(dagger) rules.d20 = 19 self.assertEqual(self.mwfar(self.p1, self.p2), (9, "critical hit")) def test_long_sword_full_attack(self): self.p1.equip_primary_weapon(long_sword) rules.d20 = 19 self.assertEqual(self.mwfar(self.p1, self.p2), (10, "hit"))
class TestServer(object): def __init__(self, coordinator): self.output_dir = coordinator.checkpoints_dir() self.decoder = Character().from_txt(cfg.CHARACTER_TXT) def evaluate(self, data_loader): with tf.device('/cpu:0'): input_images, input_labels, input_widths = data_loader.read_with_bucket_queue( batch_size=cfg.TEST.BATCH_SIZE, num_threads=cfg.TEST.THREADS, num_epochs=1, shuffle=False) with tf.device('/gpu:0'): logits = get_models(cfg.MODEL.BACKBONE)(cfg.MODEL.NUM_CLASSES).build(input_images, False) seqlen = tf.cast(tf.floor_div(input_widths, 2), tf.int32, name='sequence_length') softmax = tf.nn.softmax(logits, dim=-1, name='softmax') decoded, log_prob = tf.nn.ctc_greedy_decoder(softmax, seqlen) distance = tf.reduce_mean(tf.edit_distance(tf.cast(decoded[0], tf.int32), input_labels)) saver = tf.train.Saver(tf.global_variables()) gpu_options = tf.GPUOptions(allow_growth=True) with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True)) as sess: saver.restore(sess, tf.train.latest_checkpoint(self.output_dir)) sess.run(tf.local_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) try: cnt = 0 dm = 1e-5 while not coord.should_stop(): dt = sess.run([distance, ])[0] cnt += 1 dm = (dm + dt) / cnt if cfg.TEST.VIS: dd, il, ii = sess.run([decoded, input_labels, input_images]) gts = self.decoder.sparse_to_strlist(il.indices, il.values, cfg.TEST.BATCH_SIZE) pts = self.decoder.sparse_to_strlist(dd[0].indices, dd[0].values, cfg.TEST.BATCH_SIZE) tb = PrettyTable() tb.field_names = ['Index', 'GroundTruth', 'Predict', '{:.3f}/{:.3f}'.format(dt, dm)] for i in range(len(gts)): tb.add_row([i, gts[i], pts[i], '']) print(tb) else: print('EditDistance: {:.3f}/{:.3f}'.format(dt, dm)) except tf.errors.OutOfRangeError: print('Epochs Complete!') finally: coord.request_stop() coord.join(threads)
def testAttackEnemy(self): plop = Character("Plop", 10, 20, 30, 40) yup = Character("Yup", 10, 20, 30, 40) plop_xp_before_attack = plop.xp yup_health_before_attack = yup.health plop.attack(yup) self.assertGreater(plop.xp, plop_xp_before_attack) self.assertLess(yup.health, yup_health_before_attack)
def __init__(self, coordinator, images_dir, **kwargs): self.images_dir = images_dir self.output_dir = coordinator.checkpoints_dir() self.decoder = Character().from_txt(cfg.CHARACTER_TXT) self._allow_soft_placement = kwargs.get('allow_soft_placement', True) self._log_device_placement = kwargs.get('log_device_placenebt', False) self.device = kwargs.get('device', '/cpu:0') self.model_path = kwargs.get('model_path', None) self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph, config=tf.ConfigProto(allow_soft_placement=self._allow_soft_placement, log_device_placement=self._log_device_placement)) self.model = self._load_weights(self.model_path)
def testCharacterConstructor(self): c = Character("Toto", 10, 20, 30, 40) self.assertEqual(c.name, "Toto") self.assertEqual(c.health, 10) self.assertEqual(c.mana, 20) self.assertEqual(c.power, 30) self.assertEqual(c.xp, 40) self.assertListEqual(c.inventory, [])
class InferServer(object): def __init__(self, coordinator, images_dir, **kwargs): self.images_dir = images_dir self.output_dir = coordinator.checkpoints_dir() self.decoder = Character().from_txt(cfg.CHARACTER_TXT) self._allow_soft_placement = kwargs.get('allow_soft_placement', True) self._log_device_placement = kwargs.get('log_device_placenebt', False) self.device = kwargs.get('device', '/cpu:0') self.model_path = kwargs.get('model_path', None) self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph, config=tf.ConfigProto(allow_soft_placement=self._allow_soft_placement, log_device_placement=self._log_device_placement)) self.model = self._load_weights(self.model_path) def _load_weights(self, weights=None): with self.graph.as_default(): with tf.device(self.device): input_images = tf.placeholder(tf.uint8, shape=[None, 32, None, 3], name='input_images') input_widths = tf.placeholder(tf.uint8, shape=[None], name='input_widths') with tf.device('/gpu:0'): logits = get_models(cfg.MODEL.BACKBONE)(cfg.MODEL.NUM_CLASSES).build(input_images, False) seqlen = tf.cast(tf.floor_div(input_widths, 2), tf.int32, name='sequence_length') softmax = tf.nn.softmax(logits, dim=-1, name='softmax') decoded, log_prob = tf.nn.ctc_greedy_decoder(softmax, seqlen) prob = -tf.divide(tf.cast(log_prob, tf.int32), seqlen[0]) saver = tf.train.Saver(tf.global_variables()) if weights is None: saver.restore(self.sess, tf.train.latest_checkpoint(self.output_dir)) else: saver.restore(self.sess, weights) return {'input_images': input_images, 'input_widths': input_widths, 'decoded': decoded, 'prob': prob} @staticmethod def resize_images_and_pad(images): ws = list(map(lambda x: int(np.ceil(32.0 * x.shape[1] / x.shape[0])), images)) wmax = max(ws) wmax = wmax if wmax % 32 == 0 else (wmax // 32 + 1) * 32 data = np.zeros(shape=(len(ws), 32, wmax, 3), dtype=np.uint8) for i, img in enumerate(images): tmp = cv2.resize(img, (ws[i], 32)) data[i, :32, : ws[i], :] = tmp length = np.array([wmax], dtype=np.int32).repeat(len(ws)) return data, length def predict(self, images): imgs, widths = self.resize_images_and_pad(images) output, prob = self.sess.run([self.model['decoded'], self.model['prob']], feed_dict={self.model['input_images']: imgs, self.model['input_widths']: widths}) context = self.decoder.sparse_to_strlist(output.indices, output.values, len(imgs)) return context, prob.reshape(-1)
def setup(): import os os.environ['DIANJING_TEST'] = '1' import dianjing.wsgi teardown() from core.mongo import MongoCharacter from core.character import Character Character.create(1, 1, "one", "club_one", 1) MongoCharacter.db(1).update_one( {'_id': 1}, {'$set': { 'club.gold': 0, 'club.diamond': 0 }} )
class WeaponEquippedTest(unittest.TestCase): def setUp(self): self.p1 = Character() w = Weapon("melee", 1, (1, 2)) self.p1.equip_primary_weapon(w) def testEquip(self): self.assertEqual(self.p1.attack_bonus, 1) self.assertNotEqual(self.p1.attack_bonus, self.p1.base_attack_bonus) def testUnequipWrongWay(self): self.assertNotEqual(self.p1.base_attack_bonus, self.p1.attack_bonus) # self.assertRaises(InvalidEquipmentError, self.p1.equip_primary_weapon, None) self.assertNotEqual(self.p1.base_attack_bonus, self.p1.attack_bonus) def testUnequip(self): self.p1.unequip_primary_weapon() self.assertEqual(self.p1.base_attack_bonus, self.p1.attack_bonus)
def testPickItem(self): plop = Character("Plop", 10, 20, 30, 40) item = Item("Poo", 50) item2 = Item("Yak", 50) item3 = Item("Prout", 50) plop.pick(item) self.assertListEqual(plop.inventory, [item]) plop.pick(item2) plop.pick(item3) self.assertListEqual(plop.inventory, [item, item2, item3])
import sys, pygame from core.character import Character from core.location import Location from core.walkman import Walkman pygame.init() size = width, height = 800, 600 FPS = 60 current_frame = 0 MAX_FRAMES = 60 ANIMATION_SPEED = 15 clock = pygame.time.Clock() location = Location() character = Character() walkman = Walkman(character.get_tapes()) walkman.load_songs() time = 0 FULLTIME = 60 screen = pygame.display.set_mode(size) while True: keys = pygame.key.get_pressed() if keys[ord('w')]: character.move('up') elif keys[ord('s')]: character.move('down')
def setup_class(cls): # 建立一个 id 为2 的角色 Character.create(1, 2, "two", "club_two", 1)
print("write tfrecords using time: {} s".format(end - start)) if __name__ == '__main__': from core.character import Character # TODO: windows platform has some bug if os.name == 'nt': SENTINEL = ("", []) SAMPLE_QUEUE = Manager().Queue() labels = char_count( ['/code/disk1/xupeichao/data/OCR/wecrash/rec/sim/0806_trainval.txt'], '\t') character = Character(labels) data = txt_anno_to_data( imgs_dir='/code/disk1/xupeichao/data/OCR/wecrash/rec/sim/imgs_0806', label_file= '/code/disk1/xupeichao/data/OCR/wecrash/rec/sim/0806_trainval.txt', character=character) # tfrecords_write(data, '/code/disk1/xupeichao/data/OCR/wecrash/rec/sim/tftest', 'train') multi_tfrecords_write( data, '/code/disk1/xupeichao/data/OCR/wecrash/rec/sim/tftest', 'train', num_process=10, each_split=2000)
def setUp(self): self.p1 = Character() self.p2 = Character() self.mwfar = rules.JRRPGRules.attack_resolution
def setUp(self): self.p1 = Character() w = Weapon("melee", 1, (1, 2)) self.p1.equip_primary_weapon(w)
def __init__(self, coordinator): self.output_dir = coordinator.checkpoints_dir() self.decoder = Character().from_txt(cfg.CHARACTER_TXT)