Skip to content
This repository was archived by the owner on Jul 8, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 49 additions & 6 deletions project/reproducer.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,26 @@ def reproduce(self, dry_run=False):

table = Table()
for tag in self.round_content:
if player_draw_regex.match(tag) and 'UN' not in tag:
print('Player draw')
tile = self.decoder.parse_tile(tag)
table.player.draw_tile(tile)

if dry_run:
print(tag)
if self._is_draw(tag):
print('<-', TilesConverter.to_one_line_string([self._parse_tile(tag)]), tag)
elif self._is_discard(tag):
print('->', TilesConverter.to_one_line_string([self._parse_tile(tag)]), tag)
elif self._is_init_tag(tag):
hands = {
0: [int(x) for x in self._get_attribute_content(tag, 'hai0').split(',')],
1: [int(x) for x in self._get_attribute_content(tag, 'hai1').split(',')],
2: [int(x) for x in self._get_attribute_content(tag, 'hai2').split(',')],
3: [int(x) for x in self._get_attribute_content(tag, 'hai3').split(',')],
}
print('Initial hand:', TilesConverter.to_one_line_string(hands[self.player_position]))
else:
print(tag)

if not dry_run and tag == self.stop_tag:
break
Expand Down Expand Up @@ -72,10 +90,6 @@ def reproduce(self, dry_run=False):

table.player.init_hand(hands[self.player_position])

if player_draw_regex.match(tag) and 'UN' not in tag:
tile = self.decoder.parse_tile(tag)
table.player.draw_tile(tile)

if discard_regex.match(tag) and 'DORA' not in tag:
tile = self.decoder.parse_tile(tag)
player_sign = tag.upper()[1]
Expand Down Expand Up @@ -198,6 +212,35 @@ def _parse_rounds(self, log_content):

return rounds[1:]

def _is_discard(self, tag):
skip_tags = ['<GO', '<FURITEN', '<DORA']
if any([x in tag for x in skip_tags]):
return False

match_discard = re.match(r"^<[defgDEFG]+\d*", tag)
if match_discard:
return True

return False

def _is_draw(self, tag):
match_discard = re.match(r"^<[tuvwTUVW]+\d*", tag)
if match_discard:
return True

return False

def _parse_tile(self, tag):
result = re.match(r'^<[defgtuvwDEFGTUVW]+\d*', tag).group()
return int(result[2:])

def _is_init_tag(self, tag):
return tag and 'INIT' in tag

def _get_attribute_content(self, tag, attribute_name):
result = re.findall(r'{}="([^"]*)"'.format(attribute_name), tag)
return result and result[0] or None


class SocketMock(object):
"""
Expand Down Expand Up @@ -292,7 +335,7 @@ def parse_args_and_start_reproducer():
reproducer = TenhouLogReproducer(opts.online_log, opts.tag)
reproducer.reproduce(opts.dry_run)
else:
set_up_logging()
set_up_logging(save_to_file=False)

client = TenhouClient(SocketMock(opts.local_log))
try:
Expand Down
26 changes: 14 additions & 12 deletions project/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,38 @@
from utils.settings_handler import settings


def set_up_logging():
def set_up_logging(save_to_file=True):
"""
Logger for tenhou communication and AI output
"""
logs_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'logs')
if not os.path.exists(logs_directory):
os.mkdir(logs_directory)

# we shouldn't be afraid about collision
# also, we need it to distinguish different bots logs (if they were run in the same time)
name_hash = hashlib.sha1(settings.USER_ID.encode('utf-8')).hexdigest()[:5]

logger = logging.getLogger('tenhou')
logger.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

file_name = '{}_{}.log'.format(name_hash, datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S'))
fh = logging.FileHandler(os.path.join(logs_directory, file_name), encoding='utf-8')
fh.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)

logger.addHandler(ch)
logger.addHandler(fh)

logger = logging.getLogger('ai')
logger.setLevel(logging.DEBUG)
logger.addHandler(ch)
logger.addHandler(fh)

if save_to_file:
# we need it to distinguish different bots logs (if they were run in the same time)
log_prefix = settings.LOG_PREFIX
if not log_prefix:
log_prefix = hashlib.sha1(settings.USER_ID.encode('utf-8')).hexdigest()[:5]

file_name = '{}_{}.log'.format(log_prefix, datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S'))
fh = logging.FileHandler(os.path.join(logs_directory, file_name), encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(fh)