Exemplo n.º 1
0
 def __init__(self, loop=None, post=False):
     self._loop = loop or asyncio.get_event_loop()
     self._method = 'POST' if post else 'GET'
     self.finished = 0
     self.sem = asyncio.Semaphore(100, loop=self._loop)
     self.https_judge = Judge('https://httpbin.skactor.tk/anything')
     self.http_judge = Judge('http://httpbin.skactor.tk:8080/anything')
Exemplo n.º 2
0
    def get_content(self):
        # 1.提取基本文本块
        self.parser = Parser(self.url)
        ns_list = self.parser.ns()
        self.title = self.parser.get_title()
        # 2.文本串分块
        self.partitioner = Partitioner()
        blocks = self.partitioner.partition(ns_list)

        # 3.抽取正文块,副产品为分析信息
        self.judge = Judge(self.title.string, ns_list)
        res = self.judge.select(blocks, ns_list)

        flag = res['flag']
        cblock = res['block']
        confidence = res['confidence']
        detail = res['detail']
        #if flag:
        content = cblock.to_str()
        (srcs, images) = self.get_images(cblock)
        cblock = self.insert_images(cblock, images)
        content_with_format = cblock.to_str_with_format()
        #else:
        #    content = ""
        #    content_with_format = ""
        #    srcs = None
        return (flag, self.title.string.strip(), content, content_with_format,
                srcs, confidence, detail)
Exemplo n.º 3
0
def main():
    if len(sys.argv) <= 1:
        raise Exception("Check your arguments please!")

    project_dir = sys.argv[1]
    user_dataset = []

    def get_user_dataset():
        sort_input_path = sys.argv[2]
        sort_output_path = sys.argv[3]
        freq_input_path = sys.argv[4]
        freq_output_path = sys.argv[5]
        matmul_input_path = sys.argv[6]
        matmul_output_path = sys.argv[7]
        user_dataset.append(sort_input_path)
        user_dataset.append(sort_output_path)
        user_dataset.append(freq_input_path)
        user_dataset.append(freq_output_path)
        user_dataset.append(matmul_input_path)
        user_dataset.append(matmul_output_path)

    get_user_dataset()

    server_dataset = []

    def get_server_dataset():
        server_sort_input_file = "./datasets/sorting/sort.in"
        server_sort_output_file = "./datasets/sorting/sort.out"
        server_freq_input_file = "./datasets/freq/freq.in"
        server_freq_output_file = "./datasets/freq/freq.out"
        server_matmul_input_file = "./datasets/matmul/matmul.in"
        server_matmul_output_file = "./datasets/matmul/matmul.out"
        server_dataset.append(server_sort_input_file)
        server_dataset.append(server_sort_output_file)
        server_dataset.append(server_freq_input_file)
        server_dataset.append(server_freq_output_file)
        server_dataset.append(server_matmul_input_file)
        server_dataset.append(server_matmul_output_file)

    get_server_dataset()

    if len(server_dataset) != len(user_dataset):
        raise Exception("User and Server datasets aren't equal size!")

    for i in range(len(server_dataset)):
        judge = Judge(server_dataset[i], user_dataset[i])

        if not judge.check():
            raise Exception("Files ", server_dataset[i], "and",
                            user_dataset[i], "aren't matched!")
Exemplo n.º 4
0
def test_judge_part2():
    judge = Judge()

    stop = 5000000
    genA = generatorAPart2(65, stop)
    genB = generatorBPart2(8921, stop)

    for _ in range(stop):
        valueA = next(genA)
        valueB = next(genB)

        judge.compare(valueA, valueB)

    assert judge.getCount() == 309
Exemplo n.º 5
0
def main():
    judge = Judge()

    stop = 40000000
    genA = generatorA(512, stop)
    genB = generatorB(191, stop)

    for _ in range(stop):
        valueA = next(genA)
        valueB = next(genB)

        judge.compare(valueA, valueB)

    print(judge.getCount())
Exemplo n.º 6
0
    def judge(self, submission):
        logging.info(
            "Starting to judge submission: "
            "id {id} pid {problem} language {language}.".format(**submission)
        )
        task = self.get_task(submission['problem'])
        judge = Judge(task, submission)
        judge.start()
        judge.join()

        logging.info("Judging of submission {id} finished.".format(
            **submission
        ))

        return (judge.results, judge.compilation_log)
Exemplo n.º 7
0
def test_RPSXGame():
    p1 = Player('p1', bot=True)
    bot = Player('p2', bot=True)
    game = RPSXGame(p1, bot, Judge())
    for i in range(10):
        game.play()
    plp('test_RPSXGame()')
Exemplo n.º 8
0
    def get_content(self):
         # 1.提取基本文本块
        self.parser = Parser(self.url)
        ns_list = self.parser.ns()
        self.title = self.parser.get_title()
        # 2.文本串分块
        self.partitioner = Partitioner()
        blocks = self.partitioner.partition(ns_list) 

        # 3.抽取正文块,副产品为分析信息
        self.judge = Judge( self.title.string,ns_list )
        res = self.judge.select( blocks,ns_list )   

        flag = res['flag']
        cblock = res['block']
        confidence = res['confidence']
        detail = res['detail']
        #if flag:
        content = cblock.to_str()
        (srcs,images) = self.get_images( cblock )
        cblock = self.insert_images(cblock,images)
        content_with_format = cblock.to_str_with_format()
        #else:
        #    content = ""
        #    content_with_format = ""
        #    srcs = None
        return (flag,self.title.string.strip(),content,content_with_format,srcs,confidence,detail)
Exemplo n.º 9
0
def daemon():
    def callback(ch, method, properties, body):
        print " [x] Received judge request %r" % (body,) # for debug
        s = Sub()
        try:
            s.getSub(body)
            c = Compile()
            c.compile(s)
        except Exception, e:
            print 'compile err| ', Exception, ':', e # for debug

        if s.status == jcnf.SUB_STATUS['judging']:
            try:
                j = Judge()
                j.judge(s)
            except Exception, e:
                print 'judge err| ', Exception, ':', e # for debug
Exemplo n.º 10
0
def daemon():
    def callback(ch, method, properties, body):
        print " [x] Received judge request %r" % (body, )  # for debug
        s = Sub()
        try:
            s.getSub(body)
            c = Compile()
            c.compile(s)
        except Exception, e:
            print 'compile err| ', Exception, ':', e  # for debug

        if s.status == jcnf.SUB_STATUS['judging']:
            try:
                j = Judge()
                j.judge(s)
            except Exception, e:
                print 'judge err| ', Exception, ':', e  # for debug
Exemplo n.º 11
0
class GatekeeperHandler(ProxyHandler):
	"""
	Uses classifiers and judges to modify HTTP requests before they are
	passed on (to the browser or to the web).
	"""
	judge = Judge()
	update_filename = path.join(path.dirname(path.dirname(path.realpath(__file__))), 'precommitment', 'has_changed')
	print "\nReady to start processing requests.\n"

	def mitm_request(self, data):
		"""Modifies requests."""

		# NOTE we always allow requests through -- we only categorize and judge responses
		# this could be changed

		url = self.headers['Host'] + self.path
		trimmed_url = trim_to(url, 40)

		log_request(url, self.command)

		s_print('>> to: %s' % trimmed_url)

		# check for updates
		if path.isfile(self.update_filename):
			new_access_level = open(self.update_filename, "r").read().strip()
			system("rm -f " + self.update_filename)
			s_print("\n\nUPDATING ACCESS LEVEL: %s\n" % new_access_level)
			self.judge.load_access_rules(new_access_level)
			global CLASSIFIER
			CLASSIFIER.reload() # throw away old classifier, create a new one (because e.g. maybe we added a temporarily_blocked entry)

		return data

	def mitm_response(self, data):
		"""Modifies responses."""

		url = self.headers['Host'] + self.path
		trimmed_url = trim_to(url, 40)

		s_print('<< judging: %s' % trimmed_url)

		global CLASSIFIER
		categories = CLASSIFIER.classify(self, data)
		judgment, info = self.judge.render_judgment(categories)

		log_response(url, categories, judgment, info, self.command)

		s_print("<< %s\nJudged:\t%s => %s (%s)\n" % (trimmed_url, categories, judgment, info))

		if judgment == "BLOCK":
			return refuse(categories, info)
		elif judgment == "DELAY":
			sleep(float(info))
			return data
		elif judgment == "ALLOW":
			return data
		else:
			raise Exception("Unrecognized judgment: %s (%s)" % (judgment, info))
Exemplo n.º 12
0
    def play_game(self):
        log.info("Game started")
        
        current_player, prev_player = 'W', 'B'
        incorrect_move_attempted = False
        not_all_moves_requested = False

        while not incorrect_move_attempted and \
                Judge.return_winner(self.board) == None:
            log.info(current_player + ' players turn')
            dice_results = self.double_dice()
            log.info("Dice results : " + str(dice_results))

            if not Judge.has_possible_moves(self.board, current_player,
                    dice_results):
                log.info("no possible moves with this dice results, " \
                    "skipping player")
                current_player, prev_player = prev_player, current_player
                continue

            board_copy = deepcopy(self.board)
            dices_copy = deepcopy(dice_results)
            moves = self.players[current_player].make_moves(board_copy,
                    dices_copy)
            
            log.info("Player wants to make moves: " + str(moves))

            for move in moves:
                if Judge.check_move(self.board, move):
                    dice_results.remove(move[2])
                    Judge.execute_move(self.board, move)
                else:
                    log.error(str(move) + " is invalid")
                    incorrect_move_attempted = True
                    break
            
            if Judge.has_possible_moves(self.board,
                                        current_player,
                                        dice_results):
                log.error("Player did not make all the possible moves")
                not_all_moves_requested = True
                break

            current_player, prev_player = prev_player, current_player

        if incorrect_move_attempted:
            log.error(str(prev_player) + " player has won, due to " \
                "incorrect move of the opponent")
            winner = prev_player
        elif not_all_moves_requested:
            log.error(str(prev_player) + " player has won, due to " \
                "opponent not requesting all possible moves")
            winner = prev_player
        else: 
            winner = Judge.return_winner(self.board)
            log.info(str(winner) + " player has won")
        
        log.info("Game ended")

        return winner
Exemplo n.º 13
0
 def post(self):
     try:
         payload = json.loads(self.request.body)
     except ValueError:
         raise
     if "id" not in payload or 'src' not in payload:
         raise Exception("Argument missing")
     pid = int(payload['id'])
     src = payload['src']
     judge = Judge(pid, src, mode="inline")
     ok, msg = judge.run_tests()
 
     if not ok:
         ret = json.dumps({"pass":False, "msg": msg})
     else:
         ret = json.dumps({"pass":True})
     self.set_header("content-type", "application/json")
     self.write(ret)
Exemplo n.º 14
0
def set_content():
    content_valid = False
    content_type, content = None, None
    while not content_valid:
        content_input = input(
            "\nPlease type in the absolute path of the "
            "file/directory\nIf you want to select "
            "multiple files, please add four colons(::::) "
            "between the file paths.\nDo not choose multiple"
            " directories or a combination of files and "
            "directories.\nYou can type in 'exit()' to exit.")
        check_user_exit(content_input)
        content = content_input.split("::::")
        judge = Judge(content)
        content_type, content = judge.judge_content()
        if content_type <= 0:
            print(
                "Wrong value received!\nDetails: {} Please Try again.".format(
                    content))
        else:
            content_valid = True
    return content_type, content
Exemplo n.º 15
0
class GameManager(object):
    
    @classmethod
    def for_options(cls, options):
        subclasses = LeafSubclassRetriever(cls).value()
        manager_class = filter(lambda subclass: subclass.handles(options),
                               subclasses)[0]
        return manager_class(options)
    
    @classmethod
    def handles(cls, options):
        raise NotImplementedError('Subclass responsibility')    
    
    def __init__(self, options):
        self.options = options
        self.judge = Judge(self)
        
    def get_programs(self):
        return [self.options.prog1, self.options.prog2]      
        
    def start(self):
        self.judge.run()
        
    def end(self):
        logging.log(logging.INFO,
                    'Batalla finalizada! Mostrando resultados...')        
        self.display_results()        
    
    def process_actions(self, actions):
        raise NotImplementedError('Subclass responsibility')
    
    def process_soldiers(self, soldiers):
        raise NotImplementedError('Subclass responsibility')
    
    def display_results(self):
        raise NotImplementedError('Subclass responsibility')
Exemplo n.º 16
0
    def get_timeline(self, api, t_name):
        judge = Judge()
        try:

            for tweet in api.user_timeline(id=t_name, count=self.__num):
                #for tweet in api.user_timeline(id = Twitterkey.id, count = self.__num):
                if judge.my_timeline_multi(tweet):
                    try:
                        self.__status_media[self.__count] = tweet
                        self.__count += 1
                    except:
                        pass

                elif judge.my_timeline_single(tweet):
                    try:
                        self.__status_media[self.__count] = tweet
                        self.__count += 1
                    except:
                        pass
        except tp.error.TweepError:
            for _ in tqdm(range(15 * 60)):
                time.sleep(1)

        return self.__status_media
Exemplo n.º 17
0
def create_judge_roster(csv_filename):
    with open(csv_filename, encoding="utf-8") as csvfile:
        judge_roster = list()
        csvreader = csv.DictReader(csvfile)

        # Create an entry in the roster for each judge with their contact details, preferred categories, and availability
        for row in csvreader:
            if not any(row.values()):
                continue

            new_presentation_availability = list()
            for column_name, times_selected in row.items():
                if column_name not in JudgeColumnNames.JUDGE_AVAILABILITY_COLUMN_NAMES:
                    continue
                column_date = column_name_to_date(column_name)
                if times_selected:
                    for time_slot in times_selected.split(","):
                        if not time_slot:
                            continue
                        index_at_00_min = date_and_time_to_index(
                            column_date,
                            time_slot_to_time(time_slot),
                        )
                        new_presentation_availability.append(index_at_00_min)
                        new_presentation_availability.append(index_at_00_min +
                                                             0.5)

            new_judge = Judge(
                judge_id=csvreader.
                line_num,  # using the line number as a sequential ID field for each judge
                first=row[JudgeColumnNames.FIRST_NAME],
                last=row[JudgeColumnNames.LAST_NAME],
                email=row[JudgeColumnNames.EMAIL],
                phone=row[JudgeColumnNames.PHONE],
                preferred_categories=[
                    JUDGE_CATEGORIES[category] for category in JUDGE_CATEGORIES
                    if category in row[JudgeColumnNames.PREFERRED_CATEGORIES]
                ],
                is_paper_reviewer=row[
                    JudgeColumnNames.IS_PAPER_REVIEWER] == "Yes",
                presentation_availability=new_presentation_availability,
            )
            judge_roster.append(new_judge)

    return judge_roster
Exemplo n.º 18
0
def main(args):
    """main man"""
    # reproducibility
    if args.seed is not None:
        torch.manual_seed(
            args.seed)  # unsure if this works with SparseMNIST right now
        np.random.seed(args.seed)

    # cuda
    args.use_cuda = not args.no_cuda and torch.cuda.is_available()
    args.device = torch.device("cuda" if args.use_cuda else "cpu")

    # data
    dataset = MNIST('./data/', train=False, transform=ToTensor())
    kwargs = {'num_workers': 1}
    if args.use_cuda:
        kwargs['pin_memory'] = True
    data_loader = DataLoader(dataset, args.batch_size, shuffle=True, **kwargs)
    if args.rounds is None:
        args.rounds = len(dataset) // args.batch_size

    # load judge
    judge_state = torch.load(args.checkpoint)['state_dict']

    # debate game
    judge = Judge().to(args.device)
    judge.load_state_dict(judge_state)
    judge.eval()
    helper = Agent(honest=True, args=args)
    liar = Agent(honest=False, args=args)
    debate = Debate((helper, liar), data_loader, args)

    total_meter = AverageMeter()
    class_meters = [AverageMeter() for i in range(10)]

    # TODO precommit logic
    for _ in range(args.rounds):
        print("starting round {}".format(_))
        helper.precommit_(None, None)
        liar.precommit_(None, None)
        result = debate.play(judge, args.device)
        track_stats_(total_meter, class_meters, result['helper']['preds'],
                     result['helper']['wins'], result['labels'],
                     args.precommit)

    print('Total accuracy: {}'.format(total_meter.avg))
    print('Accuracy per class\n==============================================')
    for i in range(10):
        print('Digit {}: {}'.format(i, class_meters[i].avg))
Exemplo n.º 19
0
        def start_judge(self):
            if self.bot1_path and self.bot2_path:
                try:
                    self.play_thread_alive[0] = True
                    if self.judge:
                        self.judge.__del__()

                    tp = self.get_turn_pause()
                    rp = self.get_round_pause()
                    if not (tp is None) and not(rp is None):
                        self.judge = Judge(self.bot1_path, self.bot2_path,
                                       tp,
                                       rp,
                                       self.lock,
                                       self.play_thread_alive)
                        self.bot1_name = self.judge.bot1.name
                        wx.CallAfter(self.l_bot1_name.SetLabel, self.bot1_name + " (1)")
                        self.bot2_name = self.judge.bot2.name
                        wx.CallAfter(self.l_bot2_name.SetLabel, self.bot2_name + " (2)")
                except:
                    self.flush_all_to_default()
                    self.str_for_statusbar = "Error! You choose wrong file or file isn't a Bot program"
Exemplo n.º 20
0
class Sudoku(object):
	def __init__(self):
		self.board = Board()
		self.input_reader = InputReader()
		self.judge = Judge(self.board)


	def start_game(self):
		print "Welcome to Sudoku!"

		while not self.board.is_game_over():
			self.board.print_board()
			move = self.input_reader.read_move()
			
			if move.is_quit():
				quit()

			if self.judge.is_valid_move(move.row_index, move.col_index, move.number):
				self.board.place_number(move.row_index, move.col_index, move.number)

			else:
				print "That is not a valid movement. Try again!"
Exemplo n.º 21
0
    def handle_match_request(self, cs, p):
        pl('handling match request from {}'.format(str(p)))
        if self.has_players():
            pl('setting up normal match...')
            raise Exception(NotImplemented)
        else:
            pl('setting up bot match...')
            p2 = Player("Gunhilda", bot=True)

            ## Whos responsibility is this?
            # probably servers, right?
            # - think so, since it is the one serving the match and rules etc.
            if not p.has_moves_left():
                p.reset_moves()

            match = RPSXGame(p, p2, Judge(), bot=True)
            # One more match
            self.stats.add_match()

            self.send_cmd(cs, Command.OK)

            pl('match set up')
            self.handle_bot_match(cs, match, p2)
Exemplo n.º 22
0
def test():
    print("Testing game")
    print("0 = draw, -1 = p1 won, +1 = p2 won")
    p1 = Player('p1')
    p2 = Player('p2')
    match = RPSXGame(p1, p2, Judge())
    match.set_p1_move(Move.ROCK)
    match.set_p2_move(Move.PAPER)
    match.play()  # P2 should win
    score = match.get_snapshot().split(':')[2]
    pl(score)
    match.set_p1_move(Move.ROCK)
    match.set_p2_move(Move.ROCK)
    match.play()  # Should be a tie
    score = match.get_snapshot().split(':')[2]
    pl(score)
    match.set_p1_move(Move.ROCK)
    match.set_p2_move(Move.SCISSORS)
    match.play()  # P1 should win
    score = match.get_snapshot().split(':')[2]
    pl(score)
    match.finish()
    winner = match.get_winner()
    pl("Winner is: {}".format(winner))
Exemplo n.º 23
0
def main():
    trainIndex = 2
    rootPath = '../../exam_map/train' + str(trainIndex)
    carPath = os.path.join(rootPath, 'car.txt')
    roadPath = os.path.join(rootPath, 'road.txt')
    crossPath = os.path.join(rootPath, 'cross.txt')
    answerPath = os.path.join(rootPath, 'answer.txt')
    presetAnswerPath = os.path.join(rootPath, 'presetAnswer.txt')
    start = time.time()

    carsDict = read_car(carPath)
    roadsDict = read_road(roadPath)
    crossesDict = read_cross(crossPath, roadsDict)
    read_answer(carsDict, answerPath, presetAnswerPath)
    judge = Judge(carsDict, roadsDict, crossesDict)
    judge.init()
    judge.judge()

    print("total run time: ", time.time() - start)
    print("map {} done!".format(trainIndex))
Exemplo n.º 24
0
 def __init__(self, options):
     self.options = options
     self.judge = Judge(self)
Exemplo n.º 25
0
    with open(os.path.join(options.contest_dir, 'config.txt'), 'r') as in_file:
        contest_cfg = eval(in_file.read())
        
        seconds = contest_cfg['duration'] % 60
        minutes = contest_cfg['duration'] / 60 % 60
        hours = contest_cfg['duration'] / 60 / 60 % 60

        logger.debug("Duration: %02d:%02d:%02d" % (hours, minutes, seconds))
        logger.debug("Problems: " + str(contest_cfg['prob_ids']))
        logger.debug("Penalty: %d points / wrong submission" % contest_cfg['penalty'])

    problems = {prob_id: Problem(prob_id, options.contest_dir, logger)
                        for prob_id in contest_cfg['prob_ids']}
    contest = Contest(options.delay, contest_cfg['duration'], options.minutes_in,
                      contest_cfg['prob_ids'], contest_cfg['penalty'], logger)
    judge = Judge(contest, problems, options.contest_dir, options.num_judges, logger)

    application = web.Application(
        [
            (r'/', IndexHandler),
            (r'/index.html', IndexHandler),
            (r'/auth/login', AuthLoginHandler),
            (r'/auth/logout', AuthLogoutHandler),
            (r'/api/v1/admin/(.*)', AdminHandler),
            (r'/api/v1/log/(.*)', LogHandler),
            (r'/api/v1/metadata', MetadataHandler),
            (r'/api/v1/updates', UpdatesHandler),
            (r'/api/v1/submit/(.*)/solution', SubmitSolutionHandler),
            (r'/api/v1/submit/(.*)/clarification', SubmitClarificationHandler),
            (r'/api/v1/outputs/(.*)', OutputFileHandler),
            (r'/api/v1/errors/(.*)', ErrorFileHandler),
Exemplo n.º 26
0
import os
import sys
from judge import Judge
from constants import *
import json

#team_id, sub_id, lang_id, q_no, time_limit

try:
    if len(sys.argv) != 6:
        raise ValueError("Invalid number of arguments!")
    team_id = str(sys.argv[1])
    sub_id = int(sys.argv[2])
    lang_id = int(sys.argv[3])
    q_no = int(sys.argv[4])
    time_limit = int(sys.argv[5])
    judge_obj = Judge(team_id, sub_id, lang_id, q_no, time_limit)
    result = judge_obj.generate_result()
    if result is None:
        raise Exception("Invalid result generated")
    path_to_team = os.path.join(PATH_TO_SUBMISSION, str(team_id))
    path_to_sub_id = os.path.join(path_to_team, str(sub_id))
    path_to_result = os.path.join(path_to_sub_id, RESULT_FILE)
    json.dump(result, open(path_to_result, 'w'))

except Exception as e:
    print(e)
Exemplo n.º 27
0
#!/usr/bin/env python

import sys, os

try:
    from judge import Judge
    from judge import STDIO, FILE
except:
    path = os.path.realpath(__file__)
    path = os.path.split(path)[0]
    path = os.path.join(path, "..")
    path = os.path.join(path, "..")
    sys.path.append(path)
    from judge import Judge
    from judge import STDIO, FILE

if __name__ == "__main__":
    judge = Judge()
    judge.add_test(["sh", "1.sh", "yes"], "yesyes", style=STDIO)
    judge.add_test([
        "sh",
        "1.sh",
    ], "error", style=STDIO)
    judge.run()
Exemplo n.º 28
0
def main(args):
    # reproducibility
    if args.seed is not None:
        torch.manual_seed(
            args.seed)  # don't think this works with SparseMNIST right now
        np.random.seed(args.seed)
    if not os.path.isdir(args.checkpoint):
        mkdir_p(args.checkpoint)
    if args.checkpoint_filename is None:
        checkpoint_file = args.checkpoint + str(datetime.now())[:-10]
    else:
        checkpoint_file = args.checkpoint + args.checkpoint_filename

    # cuda
    args.use_cuda = not args.no_cuda and torch.cuda.is_available()
    device = torch.device("cuda" if args.use_cuda else "cpu")

    # eval?
    args.evaluate = args.val_batches > 0

    # prep sparse mnist
    if not args.evaluate:
        train_loader, _, test_loader = prepare_data(args)
    else:
        train_loader, val_loader, test_loader = prepare_data(args)

    # machinery
    model = Judge().to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)

    # setup validation metrics we want to track for tracking best model over training run
    best_val_loss = float('inf')
    best_val_acc = 0

    print('\n================== TRAINING ==================')
    model.train()  # set model to training mode

    # set up training metrics we want to track
    correct = 0
    train_num = args.batches * args.batch_size

    # timer
    time0 = time.time()

    for ix, (
            sparse, img,
            label) in enumerate(train_loader):  # iterate over training batches
        sparse, label = sparse.to(device), label.to(
            device)  # get data, send to gpu if needed
        optimizer.zero_grad(
        )  # clear parameter gradients from previous training update
        logits = model(sparse)  # forward pass
        loss = F.cross_entropy(logits, label)  # calculate network loss
        loss.backward()  # backward pass
        optimizer.step(
        )  # take an optimization step to update model's parameters

        pred = logits.max(1, keepdim=True)[1]  # get the index of the max logit
        correct += pred.eq(
            label.view_as(pred)).sum().item()  # add to running total of hits

        if ix % args.log_interval == 0:  # maybe log current metrics to terminal
            print('Train: [{}/{} ({:.0f}%)]\tLoss: {:.6f}\t\
                Accuracy: {:.2f}%\tTime: {:0f} min, {:.2f} s'.format(
                (ix + 1) * len(sparse), train_num,
                100. * ix / len(train_loader), loss.item(),
                100. * correct / ((ix + 1) * len(sparse)),
                (time.time() - time0) // 60, (time.time() - time0) % 60))

    print(
        'Train Accuracy: {}/{} ({:.2f}%)\tTrain Time: {:0f} minutes, {:2f} seconds\n'
        .format(correct, train_num, 100. * correct / train_num,
                (time.time() - time0) // 60, (time.time() - time0) % 60))

    if args.evaluate:
        print('\n================== VALIDATION ==================')
        model.eval()

        # set up validation metrics we want to track
        val_loss = 0.
        val_correct = 0
        val_num = args.eval_batch_size * args.val_batches

        # disable autograd here (replaces volatile flag from v0.3.1 and earlier)
        with torch.no_grad():
            for sparse, img, label in val_loader:
                sparse, label = sparse.to(device), label.to(device)
                logits = model(sparse)

                val_loss += F.cross_entropy(logits, label,
                                            size_average=False).item()

                pred = logits.max(1, keepdim=True)[1]
                val_correct += pred.eq(label.view_as(pred)).sum().item()

        # update current evaluation metrics
        val_loss /= val_num
        val_acc = 100. * val_correct / val_num
        print(
            '\nValidation set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'
            .format(val_loss, val_correct, val_num, val_acc))

        is_best = val_acc > best_val_acc
        if is_best:
            best_val_acc = val_acc
            best_val_loss = val_loss  # note this is val_loss of best model w.r.t. accuracy,
            # not the best val_loss throughout training

        # create checkpoint dictionary and save it;
        # if is_best, copy the file over to the file containing best model for this run
        state = {
            'state_dict': model.state_dict(),
            'optimizer_state': optimizer.state_dict(),
            'val_loss': val_loss,
            'val_acc': val_acc,
        }
        save_checkpoint(state, is_best, checkpoint_file)

    print('\n================== TESTING ==================')
    check = torch.load(checkpoint_file + '-best.pth.tar')
    model.load_state_dict(check['state_dict'])
    model.eval()

    test_loss = 0.
    test_correct = 0
    test_num = args.eval_batch_size * args.test_batches

    # disable autograd here (replaces volatile flag from v0.3.1 and earlier)
    with torch.no_grad():
        for sparse, img, label in test_loader:
            sparse, label = sparse.to(device), label.to(device)
            logits = model(sparse)
            test_loss += F.cross_entropy(logits, label,
                                         size_average=False).item()
            pred = logits.max(
                1, keepdim=True)[1]  # get the index of the max logit
            test_correct += pred.eq(label.view_as(pred)).sum().item()

    test_loss /= test_num
    print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
        test_loss, test_correct, test_num, 100. * test_correct / test_num))

    print('Final model stored at "{}".'.format(checkpoint_file +
                                               '-best.pth.tar'))
Exemplo n.º 29
0
def create_tree(verbose=False):
    """
    Parameters
    ----------
    verbose: boolean
    Returns
    -------
    tree: DecisionTree
    """
    # Load the data.
    trips = load_data()  #loads data
    arrival_times_df = load_arrival_times(trips)

    # Assume nan means that the train is late.
    arrival_times_df.fillna(value=30, inplace=True)

    # Split the data into training and testing sets.
    training_dates = []
    tuning_dates = []
    testing_dates = []

    last_training_day = datetime.datetime.strptime('2016-04-30', '%Y-%m-%d')
    last_tuning_day = datetime.datetime.strptime('2017-04-30', '%Y-%m-%d')

    for datestr in arrival_times_df.columns:
        this_date = datetime.datetime.strptime(datestr, '%Y-%m-%d')
        if this_date <= last_training_day:
            training_dates.append(datestr)
        if this_date <= last_tuning_day:
            tuning_dates.append(datestr)
        else:
            testing_dates.append(datestr)

    training_df = arrival_times_df.loc[:, training_dates]
    tuning_df = arrival_times_df.loc[:, tuning_dates]
    testing_df = arrival_times_df.loc[:, testing_dates]

    training_features_df = create_features(list(training_df.columns))
    judge = Judge(training_df)

    # Tune our hyperparameter.
    # Iterate over values for n_min.
    best_tuning_score = 1e10
    best_n_min = 0
    best_tree = None
    for n_min in range(10, 100, 10):

        tree = DecisionTree(err_fn=judge.find_total_absolute_deviation,
                            n_min=n_min)
        tree.fit(training_features_df)
        training_score = evaluate(tree, training_df)
        tuning_score = evaluate(tree, tuning_df)

        if tuning_score < best_tuning_score:
            best_tuning_score = tuning_score
            best_n_min = n_min
            best_tree = tree

        if verbose:
            print('n_min', n_min)
            print('training', training_score)
            print('tuning', tuning_score)
            tree.render()

    testing_score = evaluate(best_tree, testing_df)

    if verbose:
        print('best_n_min', best_n_min)
        print('best_tuning', best_tuning_score)
        print('testing score', testing_score)

    return best_tree
Exemplo n.º 30
0
#!/usr/bin/env python

import sys, os

try:
    from judge import Judge
    from judge import STDIO, FILE
except:
    path = os.path.realpath(__file__)
    path = os.path.split(path)[0]
    path = os.path.join(path, "..")
    path = os.path.join(path, "..")
    sys.path.append(path)
    from judge import Judge
    from judge import STDIO, FILE

if __name__ == "__main__":
    judge = Judge()
    judge.add_test([
        "sh",
        "1.sh",
    ], "11", style=STDIO)
    judge.add_test([
        "sh",
        "2.sh",
    ], "17", style=STDIO)
    #judge.add_test(["sh", "3.sh",], "b\ne",     style=STDIO)
    #judge.add_test(["sh", "4.sh",], "4.out",    style=FILE)
    judge.run()
Exemplo n.º 31
0
#!/usr/bin/env python
import time
from compile import Compile
from sub import Sub
from judge import Judge
c = Compile()
s = Sub()
s.sid = 1
s.lang = 'g++'
c.compile(s)
print 'ce:'+s.ce
print 'status:'+str(s.status)
s.pid = 15
s.case_cnt = 1
s.time_lim = 1000
s.mem_lim = 10240
s.case_lim = [{'time':1000, 'mem':4000},]
j = Judge()
j.judge(s)
print 'status:'+str(s.status)
print s.case_res

Exemplo n.º 32
0
 def _get_params_form_class(self, task_type_name):
     task_type = Judge.get_judge().get_task_type(task_type_name)
     return task_type.get_parameters_form()
Exemplo n.º 33
0
 def load_judge_file(self, judge_path="judge1.json"):
     try:
         self.judge = Judge(judge_path)
     except Exception as ex:
         logger.error(ex)
Exemplo n.º 34
0
        minutes = contest_cfg['duration'] / 60 % 60
        hours = contest_cfg['duration'] / 60 / 60 % 60

        logger.debug("Duration: %02d:%02d:%02d" % (hours, minutes, seconds))
        logger.debug("Problems: " + str(contest_cfg['prob_ids']))
        logger.debug("Penalty: %d points / wrong submission" %
                     contest_cfg['penalty'])

    problems = {
        prob_id: Problem(prob_id, options.contest_dir, logger)
        for prob_id in contest_cfg['prob_ids']
    }
    contest = Contest(options.delay, contest_cfg['duration'],
                      options.minutes_in, contest_cfg['prob_ids'],
                      contest_cfg['penalty'], logger)
    judge = Judge(contest, problems, options.contest_dir, options.num_judges,
                  logger)

    application = web.Application(
        [
            (r'/', IndexHandler),
            (r'/index.html', IndexHandler),
            (r'/auth/login', AuthLoginHandler),
            (r'/auth/logout', AuthLogoutHandler),
            (r'/api/v1/admin/(.*)', AdminHandler),
            (r'/api/v1/log/(.*)', LogHandler),
            (r'/api/v1/metadata', MetadataHandler),
            (r'/api/v1/updates', UpdatesHandler),
            (r'/api/v1/submit/(.*)/solution', SubmitSolutionHandler),
            (r'/api/v1/submit/(.*)/clarification', SubmitClarificationHandler),
            (r'/api/v1/errors/(.*)', ErrorFileHandler),
        ],
    #由于cv2.imwrite不支持保存图片到中文路径,用以下方法代替cv2.imwrite
    cv2.imencode('.jpg', general_crop)[1].tofile(general_img)

    #返回零件号的精确截图
    accurate_crop = extract_part(general_crop)
    name_img = os.path.join(os.path.dirname(__file__), "accurate_crop",
                            'part' + str(index) + '.jpg')

    #保存零件号截图
    #cv2.imwrite(name_img,accurate_crop)
    #由于cv2.imwrite不支持保存图片到中文路径,用以下方法代替cv2.imwrite
    cv2.imencode('.jpg', accurate_crop)[1].tofile(name_img)

    #识别图片零件号
    part_num = tran_text(name_img)
    models = Judge(part_num)
    part_nums.append([part_num, models])

output = os.path.join(path, "output")
#清空所有文件夹及其内部的文件
shutil.rmtree(os.path.join(output, "2GW"))
os.mkdir(os.path.join(output, "2GW"))
shutil.rmtree(os.path.join(output, "2HX"))
os.mkdir(os.path.join(output, "2HX"))
shutil.rmtree(os.path.join(output, "2LD"))
os.mkdir(os.path.join(output, "2LD"))
shutil.rmtree(os.path.join(output, "2QJ"))
os.mkdir(os.path.join(output, "2QJ"))
shutil.rmtree(os.path.join(output, "2SV"))
os.mkdir(os.path.join(output, "2SV"))
shutil.rmtree(os.path.join(output, "2YS"))
Exemplo n.º 36
0
 def __init__(self):
     self.judge = Judge() #need to pause it
     self.initGame()
import shutil
from config import config
from judge import Judge
import logging
import math
import inspect
import ctypes
import time
from tkinter import messagebox

logging.basicConfig(
    level=logging.ERROR,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='log/error.log')
logger = logging.getLogger(__name__)
judge_handler = Judge()


def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
                                                     ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
Exemplo n.º 38
0
#!/usr/bin/env python

import sys, os

try:
    from judge import Judge
    from judge import STDIO, FILE
except:
    path = os.path.realpath(__file__)
    path = os.path.split(path)[0]
    path = os.path.join(path, "..")
    path = os.path.join(path, "..")
    sys.path.append(path)
    from judge import Judge
    from judge import STDIO, FILE

if __name__=="__main__":
    judge = Judge()
    judge.add_test(["sh", "1.sh",], "11",       style=STDIO)
    judge.add_test(["sh", "2.sh",], "17",       style=STDIO)
    judge.add_test(["sh", "3.sh",], "b\ne",     style=STDIO)
    judge.add_test(["sh", "4.sh",], "4.out",    style=FILE)
    judge.run()
Exemplo n.º 39
0
#!/usr/bin/env python

import sys, os

try:
    from judge import Judge
    from judge import STDIO, FILE
except:
    path = os.path.realpath(__file__)
    path = os.path.split(path)[0]
    path = os.path.join(path, "..")
    path = os.path.join(path, "..")
    sys.path.append(path)
    from judge import Judge
    from judge import STDIO, FILE

if __name__ == "__main__":
    judge = Judge()
    judge.add_test(["sh", "1.sh"], "11", style=STDIO)
    judge.add_test(["sh", "2.sh"], "17", style=STDIO)
    # judge.add_test(["sh", "3.sh",], "b\ne",     style=STDIO)
    # judge.add_test(["sh", "4.sh",], "4.out",    style=FILE)
    judge.run()
    sources = list({"lastfm", "discogs", "tagtraum"} - {target})
    dataset_path = os.path.join(utils.FOLDS_DIR,
                                "{0}_4-fold_by_artist.tsv".format(target))
    dhelper = DataHelper(sources, target, dataset_path=dataset_path)
    print(dhelper.dataset_df)

    source_tags = [
        f"{source}:{el}" for source in sources
        for el in utils.corpus_genres_for_source(dhelper.dataset_df, source)
    ]
    target_tags = [
        f"{target}:{el}"
        for el in utils.corpus_genres_for_source(dhelper.dataset_df, target)
    ]
    tm = TagManager.get(sources, target, source_tags, target_tags)
    judge = Judge()
    print("The judge was initialized")

    translators = {}
    tr = DbpMappingTranslator(
        tm, ''.join([
            utils.ISMIR2019_TRANSLATION_TABLES_DIR, "distance_table_dbpedia_",
            target
        ]))
    translators['baseline'] = tr

    models = {}
    models['avg_init'] = ''.join(
        [utils.ACOUSTICBRAINZ_EMBS_DIR, "/avg_initial_embs.csv"])
    models['avg_retro_unweighted'] = ''.join(
        [utils.ACOUSTICBRAINZ_EMBS_DIR, "/avg_retro_unweighted_embs.csv"])
Exemplo n.º 41
0
class Prog(QtGui.QMainWindow):
    """This is the MAIN program, this is the start point,
     nothing should be calle from doutside of this class.
    
    Arguments:
        QtGui.QMainWindow {QMainWindow object } -- QMainWindow legacy
    
    Returns:
        [None] -- Just run until it closed
    """
    def __init__(self):
        super().__init__(None)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.timer = QtCore.QTimer(self)

        #set up the log tab
        logTextBox = QTextEditLogger(self)

        logTextBox.setFormatter(
            logging.Formatter(
                '"%(asctime)s - %(levelname)s \t- %(module)s \t- %(funcName)s ::  %(message)s"'
            ))
        logging.getLogger().addHandler(logTextBox)
        layout_log = QtWidgets.QVBoxLayout()
        layout_log.addWidget(logTextBox.widget)
        self.ui.tab_log.setLayout(layout_log)
        logger.info("--- Start ---")
        logger.info("Python : " + str(sys.version))
        logger.info("Prog  version : " + str(__version__))
        logger.info("-------")

        #Set up variable
        self.flight = None
        self.visualizer_3d = None
        self.judge = None
        self.load_judge_file()

        #add Action
        self.ui.actionOpen.triggered.connect(self.open_pickle_file)
        self.ui.actionSave_as.triggered.connect(self.save_pickle_file)
        self.ui.actionimport.triggered.connect(self.import_log_window)
        self.ui.actionVersion.triggered.connect(self.about_popup)
        self.ui.actionHelp.triggered.connect(self.openUrl_help)
        self.ui.actiondebug_open.triggered.connect(self.debug)

        self.ui.treeWidget.itemClicked.connect(self.onTreeItemClicked)
        self.ui.treeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #setup Qtree
        self.ui.treeWidget.setHeaderLabels(["Name", "Kind", "Id"])

        #setup table view detail section
        self.ui.model = QtGui.QStandardItemModel(self)
        self.ui.tableView.setModel(self.ui.model)
        self.ui.model.dataChanged.connect(self.on_datachange_model)

        #setup iteractive console
        ## build an initial namespace for console commands to be executed in (this is optional;
        ## the user can always import these modules manually)
        namespace = {'prog': self, "Kind": Kind}
        ## initial text to display in the console
        text = " This is an interactive python console \n the following namespace are imported:\n" + str(
            list(namespace.keys())) + " \n  Go, play."

        self.c = pyqtgraph.console.ConsoleWidget(namespace=namespace,
                                                 text=text)
        mainLayout_console = QtWidgets.QVBoxLayout()
        mainLayout_console.addWidget(self.c)
        self.ui.tab_console.setLayout(mainLayout_console)
        logger.info(" interactive console ready")

    def debug(self):
        ''' only use for speed up de developement
        '''
        self.open_pickle_file(
            "samples/Flight2_gourdon_v0-2-0.pkl")  #linux path

    def load_judge_file(self, judge_path="judge1.json"):
        try:
            self.judge = Judge(judge_path)
        except Exception as ex:
            logger.error(ex)

    def open_pickle_file(self, filename=None):
        """Function to import a file already saved, format is classic python pickle .pkl
        
        Keyword Arguments:
            filename {[str]} -- if a path is given the browse dialog do not open ( use for debug function) (default: {None})
        
        Returns:
            [None] -- But saved the nex loaded flight in the main self.Flight object.
        """

        if filename == False:
            filename = QtGui.QFileDialog.getOpenFileName(
                self, 'Open pickler File', "", 'Pickle Files (*.pkl)')

        if isinstance(filename, tuple):
            filename = filename[0]
        if filename:
            try:
                logger.info(" importing : " + str(filename))
                self.file_name = filename
                self.id = 0
                with open(filename, 'rb') as pickle_file:
                    self.flight = pickle.load(pickle_file)

                #Check for version of the opened file
                if hasattr(self.flight, 'flight_version'):
                    if int(self.flight.flight_version
                           ) < __pickle_file_version__:
                        logger.info(" !! Importing Old file format: " +
                                    str(self.flight.flight_version) +
                                    " current is: " +
                                    str(__pickle_file_version__))
                else:
                    logger.info(
                        " !! Importing a file without flight_version info: version can not be checked "
                    )

                self.update_project_tree()

            except Exception as ex:
                logger.error(ex)

    def save_pickle_file(self):
        """Save the current self.Flight object to a pickle file. (.pkl)
        """
        try:
            tuple_saved_file = QtGui.QFileDialog.getSaveFileName(
                self, 'Save File', '', 'Pickle(*.pkl)')
            name_saved_file = tuple_saved_file[0] + '.pkl'
            logger.info("Saving as : " + name_saved_file[0] + '.pkl')
            with open(name_saved_file, "wb") as f:
                pickle.dump(self.flight, f)

        except Exception as ex:
            logger.error(ex)

    def import_log_window(self):
        """Function will display a other dialog to fill for loading a raw  log file
        the dialog will auto close when the import is finish.
        """
        widget_import_new = import_log_diaglog()
        widget_import_new.exec_()
        logger.debug("back in main prog")
        try:  # try to copy the flight object from the dialog windows to the main Flight object
            self.flight = widget_import_new.imported_Flight
            self.update_project_tree()
        except Exception as ex:
            logger.warning(ex)

    def about_popup(self):
        """ About section 
        Display various info for debug and system details
        TODO ; having a better list of the enviroment module and their version.
        """

        # from https://stackoverflow.com/questions/54447535/how-to-fix-typeerror-in-qtwidgets-qmessagebox-for-popup-messag
        cwd = os.path.dirname(os.path.abspath(__file__))

        log_content = getSystemInfo()

        msg = QtWidgets.QMessageBox()
        msg.setIcon(QtWidgets.QMessageBox.Information)
        msg.setText("Version : " + str(__version__) + "\n"
                    "pkl file version: " + str(log_file_name) + "\n"
                    "Log file name: " + str(__pickle_file_version__) + "\n"
                    "curent working directory: " + str(cwd))
        msg.setInformativeText(
            "More info on :\nhttps://github.com/fredvol/paralogger ")
        msg.setWindowTitle("About")
        msg.setDetailedText(log_content)
        msg.setStandardButtons(
            QtWidgets.QMessageBox.Ok)  #| QtWidgets.QMessageBox.Cancel)

        retval = msg.exec_()

    def openUrl_help(self):
        """Open github page in browser
        """
        url = QtCore.QUrl('https://github.com/fredvol/paralogger')
        if not QtGui.QDesktopServices.openUrl(url):
            QtGui.QMessageBox.warning(self, 'Open Url', 'Could not open url')

    ### TREE VIEW  ###
    # Tree view will display the flight and all the sections attach to.

    def update_project_tree(self):
        """repopulated the tree view , to show modif.
        """
        logger.info("update_project_tree")
        tw = self.ui.treeWidget
        tw.clear()
        if self.flight != None:
            l1 = QtWidgets.QTreeWidgetItem(
                [self.flight.glider, "--", self.flight.id])

            for sect in self.flight.sections:
                l1_child = QtWidgets.QTreeWidgetItem([
                    str(sect.start) + " - " + str(sect.end),
                    str(sect.kind.value), sect.id
                ])
                l1.addChild(l1_child)

            tw.addTopLevelItem(l1)
            tw.expandAll()
        else:
            logger.info(" Flight  is empty, nothing to display")

    def get_level_from_index(self, indexes):
        """Return the level in the treeview
        level 0 = Flight
        level 1 = Section
        
        Arguments:
            indexes {[QModelIndex]} -- not realy clear for me !
        
        Returns:
            level [Int]  -- The level of the cliked item
        """

        if len(indexes) > 0:
            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level += 1
        else:
            level = -1

        return level

    @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
    def onTreeItemClicked(self, it, col):
        """function trigered when an object is cliked on the tree view
        This a central function which dispath the work to the other objects .
        
        Arguments:
            it {QTreeWidgetItem} -- item cliked
            col {int} -- index of  columns cliked
        """

        indexes = self.ui.treeWidget.selectedIndexes()

        level = self.get_level_from_index(indexes)

        if level >= 0:  # if a Flight or a Section
            uid = it.text(2)  # The text of the node.
            logger.debug("clicked: " + str(it) + ", " + str(col) + ", " +
                         str(uid) + " level: " + str(level))
        else:
            uid = None

        #Job dispatching
        if level == 0:  # flight  level
            self.populate(uid, level)
            self.display_tab_Table(None)

        elif level == 1:  # section level
            #update all tabs
            self.display_tab_graph(uid)
            self.display_tab_Table(uid)
            self.display_tab_3D(uid)
            self.display_tab_analysis(uid)

            self.populate(uid, level)

    def openMenu(self, position):
        """Open contextual menu in tree View widget
        
        Arguments:
            position {[type]} -- [description]
        """
        indexes = self.ui.treeWidget.selectedIndexes()
        item = self.ui.treeWidget.itemAt(position)

        menu = QtWidgets.QMenu()

        level = self.get_level_from_index(indexes)
        if level > 0 and item != None:
            uid = item.text(2)  # The UId of teh object

        if level == 0:  # Flight
            action_add = menu.addAction(self.tr("Add Section"))
            action_add.triggered.connect(self.add_section)
            action_refresh = menu.addAction(self.tr("Refresh"))
            action_refresh.triggered.connect(self.update_project_tree)

            action_export_csv = menu.addAction('Export CSV')
            action_export_csv.triggered.connect(
                lambda: self.export_df(expformat="csv"))

            action_export_xls = menu.addAction('Export XLSX')
            action_export_xls.triggered.connect(
                lambda: self.export_df(expformat="xlsx"))

            action_export_xls = menu.addAction('Export device parameters')
            action_export_xls.triggered.connect(self.export_device_param)

        elif level == 1:  #Section
            action_export_csv = menu.addAction('Export CSV')
            action_export_csv.triggered.connect(
                lambda: self.export_df(uid, expformat="csv"))

            action_export_xls = menu.addAction('Export XLSX')
            action_export_xls.triggered.connect(
                lambda: self.export_df(uid, expformat="xlsx"))

            action_del = menu.addAction('Delete')
            action_del.triggered.connect(lambda: self.delete_section(uid))

            action_refresh = menu.addAction(self.tr("Refresh"))
            action_refresh.triggered.connect(self.update_project_tree)

        menu.exec_(self.ui.treeWidget.viewport().mapToGlobal(position))

    def delete_section(self, uid):
        """Delete the a Section from the self.Flight and refresh
        
        Arguments:
            uid {Str} -- Uid of the Section to delete
        """
        logger.info("delete section :" + str(uid))
        self.flight.delete_section(uid)
        self.update_project_tree()

    def add_section(self):
        """Add a section in self.Flight
        By default  there start from 0 to the end.
        """
        logger.info("add section")
        self.flight.add_general_section()
        self.update_project_tree()

    def export_device_param(self):
        """ Export the internal parameters of the PX4 
        TODO  not avaible if not PX4 filter
        """

        df_param = self.flight.data[0].device_param
        tuple_export_file = QtGui.QFileDialog.getSaveFileName(
            self, 'csv_file', '', '.csv')
        name_export_file = tuple_export_file[0] + '.csv'
        with open(name_export_file, 'w', newline="") as csv_file:
            writer = csv.writer(csv_file)
            for key, value in df_param.items():
                writer.writerow([key, value])

        logger.info("Device parameters exported : " + str(name_export_file))

    def export_df(self, uid=None, expformat="csv"):
        """Export Dataframe  in different format
        
        Keyword Arguments:
            uid {str} -- Uid of the Section to export (default: {None})
            expformat {str} -- Format to export [csv , xlsx] (default: {"csv"})
        
        If UID is None then export the flight ( maybe change to use the level info, to be consitent)
        """
        # TODO add multi sheet( xlsx) or file (csv) if multi data_file in flight
        if uid != None:  # if it is a section
            df_to_export = self.flight.apply_section(uid)
        else:  # if not section passed , then export main df
            df_to_export = self.flight.get_df_by_position(Position.PILOT)[0]
        try:
            tuple_export_file = QtGui.QFileDialog.getSaveFileName(
                self, 'Export Dataframe File', '', '.' + str(expformat))
            name_export_file = tuple_export_file[0] + '.' + str(expformat)
            if expformat == 'csv':
                df_to_export.to_csv(name_export_file)
            elif expformat == 'xlsx':
                logger.info(
                    "Exporting to Excel can take a while, coffee time ...")
                df_to_export.to_excel(name_export_file)
            logger.info("Exported as : " + name_export_file)
        except Exception as ex:
            logger.error(ex)

    #### TAB WIDGET ACTIONS ###
    # This section manage all the Tab ins the view part of the main windows.

    def display_tab_3D(self, uid):
        """Call the Tab_3d.py  and generated a 3D view .
        
        Arguments:
            uid {str} -- id of the Section to display
        Nothing append if Flight is selected, only for Sections

        TODO reload data when other section are cliked ( only display the first cliked one)
        """

        df_to_plot = self.flight.apply_section(uid)
        ####

        self.visualizer_3d = Visualizer3D(self.ui.tab_3d)
        self.visualizer_3d.animation(df_to_plot, True, timer=self.timer)
        #empty actual area if exist
        if len(self.ui.tab_3d.children()) > 0:
            layout = self.ui.tab_3d.children()[0]
            deleteItemsOfLayout(layout)

            layout.addWidget(self.visualizer_3d.area)

        else:
            mainLayout = QtWidgets.QVBoxLayout()
            mainLayout.addWidget(self.visualizer_3d.area)
            self.ui.tab_3d.setLayout(mainLayout)

    def display_tab_analysis(self, uid):
        logger.debug(" in display_tab_analysis")
        logger.debug(self.judge)

        df_to_analysis = self.flight.apply_section(uid)
        section = self.flight.section_by_id(uid)

        logger.debug(section)
        logger.debug(df_to_analysis.info())

        if self.judge != None:
            hash_judge, hash_dict_crit = self.judge.hash_state()
            self.ui.label_judge_file.setText(str(self.judge))
            self.ui.label_hash_judge_value.setText(hash_judge)
            self.ui.label_hash_crit_value.setText(hash_dict_crit)

            table_analysis = self.ui.tableWidget_analysis

            result_section = self.judge.run(df_to_analysis, section.kind.value)

            column_name = ["Test", "Value", "unit", "Grade"]
            column_count = (len(column_name))

            table_analysis.setColumnCount(column_count)

            table_analysis.setHorizontalHeaderLabels(column_name)

            for key, value in result_section.items():
                currentRowCount = table_analysis.rowCount()

                table_analysis.insertRow(currentRowCount)
                table_analysis.setItem(currentRowCount, 0,
                                       QtGui.QTableWidgetItem(str(key)))
                table_analysis.setItem(
                    currentRowCount, 1,
                    QtGui.QTableWidgetItem(str(value["value"])))
                table_analysis.setItem(
                    currentRowCount, 2,
                    QtGui.QTableWidgetItem(str(value["unit"])))
                table_analysis.setItem(
                    currentRowCount, 3,
                    QtGui.QTableWidgetItem(str(value["grade"])))

    def display_tab_Table(self, uid):
        """ Display the Pilot dataframe  in a table
        
        Arguments:
            uid {str} -- id of the Section to display

        For Flight and Section.
        ! only for dataframe  at pilot position
        TODO : Manage if no pilot position is available
        """
        try:
            if uid != None:  # if it is a section
                df_to_plot = self.flight.apply_section(uid)
            else:  # if not section passed , then plot main df
                df_to_plot = self.flight.get_df_by_position(Position.PILOT)[0]

            model = pandasTableModel(df_to_plot)
            if len(self.ui.tab_table.children()) > 0:
                self.ui.tab_table.children()[1].setModel(model)
            else:
                mainLayout = QtWidgets.QVBoxLayout()

                view = QtWidgets.QTableView()
                view.setModel(model)

                mainLayout.addWidget(view)

                self.ui.tab_table.setLayout(mainLayout)
        except Exception as ex:
            logger.warning(ex)
            pass

    def display_tab_graph(self, uid):
        """PLot different Graph 

        Arguments:
            uid {str} -- id of the Section to display
        
        Work only for Section
        TODO: Display full Flight with the section part Highlighted.
        """

        df_to_plot = self.flight.apply_section(uid)
        inside_widget = generated_layout(df_to_plot)

        #empty actual area if exist
        if len(self.ui.tab_graph.children()) > 0:
            print("layout not empty")
            layout = self.ui.tab_graph.children()[0]
            deleteItemsOfLayout(layout)
            # Old code for deleting item
            # for i in reversed(range(layout.count())):
            #     widgetToRemove = layout.itemAt(i).widget()
            #     # remove it from the layout list
            #     layout.removeWidget(widgetToRemove)
            #     # remove it from the gui
            #     widgetToRemove.setParent(None)

            layout.addWidget(inside_widget)

        else:
            mainLayout = QtWidgets.QVBoxLayout()
            mainLayout.addWidget(inside_widget)
            self.ui.tab_graph.setLayout(mainLayout)

    ## DETAILS OBJECT

    def on_datachange_model(self, signal):
        """Function use to update the self.Flight object  when a value is changed in the Detail table view
        
        Arguments:
            signal {QModelIndex} -- Index of the modified cell

        TODO block the edition of enum type ( kind , device , position) or even better implement combobox on GUI
        """
        row = signal.row()  # retrieves row of cell that was double clicked
        column = signal.column(
        )  # retrieves column of cell that was double clicked
        cell_dict = self.ui.model.itemData(
            signal)  # returns dict value of signal
        cell_value = cell_dict.get(0)  # retrieve value from dict

        uid = self.ui.model.itemData(signal.sibling(0, 1)).get(0)

        index = signal.sibling(row, 0)
        index_dict = self.ui.model.itemData(index)
        index_value = index_dict.get(0)
        logger.debug(
            'Edited Row {}, Col {} value: {} index_value: {}, uid: {}'.format(
                row, column, cell_value, index_value, uid))

        ## Update the Data model ( self.flight) from the changed done in self.ui_model
        if self.flight.id == uid:
            setattr(self.flight, index_value, cell_value)
        else:
            for sect in self.flight.sections:
                if sect.id == uid:
                    setattr(sect, index_value, cell_value)

        ## Update tree view:
        self.update_project_tree()

    def populate(self, uid, level):
        """ Add data in the Table view , via model 
        Exxtract a Dict of of a object properties.
        ! model only accepts strings - must convert.
 
        Arguments:
            uid {str} -- ID of the object to display
            level {int} -- object cliked level ( FLight or Section)
        """

        logger.debug("display_properties of: " + str(uid))
        self.ui.model.clear()  # Clear th UI model notthe self.Flight

        if level == 0:
            dict_to_display = vars(self.flight)
        elif level == 1:
            dict_to_display = vars(self.flight.section_by_id(uid))

        for name, value in dict_to_display.items():
            row = []
            cell_name = QtGui.QStandardItem(str(name))

            if isinstance(value, Kind):
                cell_value = QtGui.QStandardItem(str(value))
                # TODO  display combobox with a list of option (QItemDelegate? )

            else:
                cell_value = QtGui.QStandardItem(str(value))

            row.append(cell_name)
            row.append(cell_value)

            self.ui.model.appendRow(row)
Exemplo n.º 42
0
 def get_judge(self):
     return Judge.get_judge()
Exemplo n.º 43
0
	def __init__(self):
		self.board = Board()
		self.input_reader = InputReader()
		self.judge = Judge(self.board)
Exemplo n.º 44
0
class Scraper:
    def __init__(self,url):
        self.url = url          # 要分析的url
        self.block_li = []      # 网页所包含的文本块列表
        self.title = ''
        #重置记录
        self.recorder = Recorder()
        self.recorder.reset()
        
    # 从正文前后和其中中提取图片,只取第一个
    # 只取图片大小足够大的
    def get_images(self,block):
        imgs = []
        
        # 设定image搜索起点
        if self.title != self.parser.soup.title:
            start = self.title
        else:
            # title不在正文中,向上扩展image搜索范围
            # 向下扩展image搜索范围
            start = block.text_list()[0]        
            while start.previous:
                start = start.previous
                if not isinstance(start,NavigableString) and start.name in BLOCK_TAGS:
                    break
                
        # 设定image搜索终点
        end = block.text_list()[-1]
        while end.next:
            end = end.next
            if not isinstance(end,NavigableString) and end.name in BLOCK_TAGS:
                break

        while start!=end:
            if not isinstance(start,NavigableString) and start.name=='img':
                imgs.append( start ) 
            start = start.next
        return self.filter_images( imgs )

    def filter_images( self,imgs ):
        srcs = []
        images = []
        for img in imgs:
            if img.has_key('src'):
                src = img['src']
                if not src.lower().startswith('http://'):
                    src = relative2absolute( self.url,src )
                    # 判断图片大小,太小不要
                try:
                    im = urlopen( src ).read()
                    if len(im)>MIN_IMG_SIZE:
                        srcs.append( src )
                        #img['src'] = src
                        images.append( img )
                except IOError:
                    pass
        return (srcs,images)
    # 如果图像出现在block中,则添加图像和图像p内的ns
    def insert_images(self,block,images):
        start = self.title
        end = block.text_list()[-1]
        behind_img = False
        #block.print_ns()

        i = 0                   # 记录block中文本编号
        while start!=end:
            if not isinstance(start,NavigableString) :
                if start.name=='img' and start in images:
                    src = start['src']
                    if not src.lower().startswith('http://'):
                        start['src'] = relative2absolute( self.url,src )
                    #print i,":",str(start),"[]"
                    block.insert( i,start ) 
                    #block.print_ns()
                    i += 1
                    behind_img = True
                elif start.name=='br':
                    #print i,":",str(start),"[]"
                    # 加入换行符
                    block.insert( i,start ) 
                    #block.print_ns()
                    i += 1
                elif start.name in BLOCK_TAGS:
                    behind_img = False
            # NavigableString
            elif start.string.strip():
                # 已经在正文块中
                if start in block.text_list():
                    #print i,":",start.string
                    i += 1 
                    behind_img = False
                # 不在正文块中,在图片后的兄弟文本
                elif behind_img:
                    #print i,":",start.string,"[]"
                    block.insert( i,start )
                    #block.print_ns()
                    i += 1
            start = start.next
    
        return block
    # 执行流程,返回提取到的正文
    def get_content(self):
         # 1.提取基本文本块
        self.parser = Parser(self.url)
        ns_list = self.parser.ns()
        self.title = self.parser.get_title()
        # 2.文本串分块
        self.partitioner = Partitioner()
        blocks = self.partitioner.partition(ns_list) 

        # 3.抽取正文块,副产品为分析信息
        self.judge = Judge( self.title.string,ns_list )
        res = self.judge.select( blocks,ns_list )   

        flag = res['flag']
        cblock = res['block']
        confidence = res['confidence']
        detail = res['detail']
        #if flag:
        content = cblock.to_str()
        (srcs,images) = self.get_images( cblock )
        cblock = self.insert_images(cblock,images)
        content_with_format = cblock.to_str_with_format()
        #else:
        #    content = ""
        #    content_with_format = ""
        #    srcs = None
        return (flag,self.title.string.strip(),content,content_with_format,srcs,confidence,detail)
Exemplo n.º 45
0
import sys, os

try:
    from judge import Judge
    from judge import STDIO, FILE
except:
    path = os.path.realpath(__file__)
    path = os.path.split(path)[0]
    path = os.path.join(path, "..")
    path = os.path.join(path, "..")
    sys.path.append(path)
    from judge import Judge
    from judge import STDIO, FILE

if __name__ == "__main__":
    judge = Judge()
    judge.add_test([
        "sh",
        "1.sh",
    ], "11", style=STDIO)
    judge.add_test([
        "sh",
        "2.sh",
    ], "17", style=STDIO)
    judge.add_test([
        "sh",
        "3.sh",
    ], "b\ne", style=STDIO)
    judge.add_test([
        "sh",
        "4.sh",
Exemplo n.º 46
0
class MyFrame(wx.Frame):

        def __init__(self):
            wx.Frame.__init__(self, None, -1, size=(790, 620), title = "SeaWar Judge", pos = (300, 60))
            self.panel = wx.Panel(self, -1)
            self.judge = None
            self.field_top = 30
            self.field_left = 30
            self.field_down = self.field_top + 400
            self.field1 = Field( Map(), self.panel, (self.field_left, self.field_top), 30)
            self.field2 = Field( Map(), self.panel, (400, self.field_top), 30)


            self.b_add_bot1 = wx.Button(self.panel, -1, "Choose bot 1", pos = (self.field_left + 30,
                                                                               self.field_down),
                                        size = (300, 40))

            self.Bind(wx.EVT_BUTTON, self.on_add_bot1, self.b_add_bot1)

            self.b_add_bot2 = wx.Button(self.panel, -1, "Choose bot 2", pos = (430,
                                                                               self.field_down),
                                        size = (300, 40))

            self.Bind(wx.EVT_BUTTON, self.on_add_bot2, self.b_add_bot2)


            wildcard = "Python files (*.py)|*.py|All files (*.*)|*.*"
            self.dialog = wx.FileDialog(None, "Choose a bot executable", os.getcwd(),
                                   "", wildcard, wx.OPEN)

            self.bot1_path = None
            self.bot2_path = None

            self.bot1_name = None
            self.bot2_name = None

            self.l_bot1_name = wx.StaticText(self.panel, -1, "?BOT1?", pos = (self.field_left + self.field1.size,
                                                                               self.field_top - 20))

            self.l_bot2_name = wx.StaticText(self.panel, -1, "?BOT2?", pos = (400 + self.field2.size,
                                                                               self.field_top - 20))

            self.big_font = wx.Font(18, wx.DEFAULT, wx.DEFAULT, wx.DEFAULT)
            self.small_font = wx.Font(8, wx.DEFAULT, wx.DEFAULT, wx.DEFAULT)
            self.bold_font = wx.Font(40, wx.DEFAULT, wx.DEFAULT, wx.BOLD)
            self.l_bot1_name.SetForegroundColour("Green")
            self.l_bot2_name.SetForegroundColour("Red")
            self.l_bot1_name.SetFont(self.big_font)
            self.l_bot2_name.SetFont(self.big_font)


            self.l_bot1_wins = wx.StaticText(self.panel, -1, "0", pos = (self.field_left + 70,
                                                                               self.field_down - 70))

            self.l_wins = wx.StaticText(self.panel, -1, ":", pos = (390, self.field_down - 70))
            self.l_wins.SetFont(self.bold_font)
            self.l_wins.SetForegroundColour("Blue")

            self.l_bot2_wins = wx.StaticText(self.panel, -1, "0", pos = (470, self.field_down - 70))
            self.l_bot1_wins.SetFont(self.bold_font)
            self.l_bot2_wins.SetFont(self.bold_font)
            self.l_bot1_wins.SetForegroundColour("Green")
            self.l_bot2_wins.SetForegroundColour("Red")

            self.winlist = [0, 0, 0]
            self.maplist = [Map(), Map(), 0]

            self.b_start_chemp = wx.Button(self.panel, -1, "START!", pos = (self.field_left + 240,
                                                                               self.field_down + 60),
                                                                        size = (250, 100))

            self.b_start_chemp.SetFont(self.bold_font)

            self.Bind(wx.EVT_BUTTON, self.on_start_chemp, self.b_start_chemp)



            self.c_rounds = wx.SpinCtrl(self.panel,
                                        -1,
                                        value = '',
                                        pos = (self.field_left + 630, self.field_down + 55),
                                        size = (70, 30),
                                        style = wx.SP_ARROW_KEYS,
                                        min = 1,
                                        max = 10000,
                                        initial = 1)

            self.l_rounds = wx.StaticText(self.panel, -1, "How many rounds:",
                                          pos = (self.field_left + 500, self.field_down + 65))

            self.c_round_pause = wx.TextCtrl(self.panel, -1, value = "0",
                                             pos = (self.field_left + 630, self.field_down + 95),
                                             size = (70, 30),
                                             validator = Is_Float_and_time())

            self.l_round_pause = wx.StaticText(self.panel, -1, "Pause between rounds:",
                                          pos = (self.field_left + 500, self.field_down + 105))

            self.l_round_pause.SetFont(self.small_font)

            self.l_turn_pause = wx.StaticText(self.panel, -1, "Pause between turns:",
                                          pos = (self.field_left + 500, self.field_down + 145))

            self.l_turn_pause.SetFont(self.small_font)

            self.c_turn_pause = wx.TextCtrl(self.panel, -1, value = "0",
                                             pos = (self.field_left + 630, self.field_down + 135),
                                             size = (70, 30),
                                             validator = Is_Float_and_time())

            self.b_pause_play = wx.Button(self.panel, -1, "Pause", pos = (self.field_left + 30,
                                                                               self.field_down + 120),
                                                                        size = (65, 40))

            self.Bind(wx.EVT_BUTTON, self.on_pause_play, self.b_pause_play)

            self.b_stop = wx.Button(self.panel, -1, "STOP", pos = (self.field_left + 95,
                                                                               self.field_down + 120),
                                                                        size = (65, 40))

            self.Bind(wx.EVT_BUTTON, self.on_stop, self.b_stop)

            self.b_flush = wx.Button(self.panel, -1, "Default", pos = (self.field_left + 165,
                                                                               self.field_down + 120),
                                                                        size = (65, 40))

            self.Bind(wx.EVT_BUTTON, self.on_default, self.b_flush)

            self.g_progress = wx.Gauge(self.panel, -1, 100,
                                        pos = (self.field_left + 30, self.field_down + 70),
                                        size = (200, 40),
                                        style = wx.GA_HORIZONTAL)

            self.status_bar = self.CreateStatusBar()
            self.status_bar.SetStatusText('Hello there! Choose bots and click "START!"')

            self.lock = threading.Lock()
            self.running = True


            self.Bind(wx.EVT_CLOSE, self.on_close, self)

            self.enable_disable_set = [self.b_add_bot1,
                                       self.b_add_bot2,
                                       self.b_start_chemp,
                                       self.b_flush,
                                       self.c_round_pause,
                                       self.c_rounds,
                                       self.c_turn_pause]

            self.play_thread_alive = [True, ]
            self.str_for_statusbar = 'Hello! Choose bots and press "START!"'

            self.make_elements_active(False, *[self.b_pause_play, self.b_stop])

            self.judge = None

            self.supe = superthreading
            self.supe.frame = self

            self.is_computing = False

            self.graphic_tread = threading.Thread(target = self.refresh)
            self.graphic_tread.daemon = True
            self.graphic_tread.start()


        def make_elements_active(self, active = False, *els):
            for el in els:
                wx.CallAfter(el.Enable, active)

        def on_stop(self, event):
            self.play_thread_alive[0] = False
            self.str_for_statusbar = "Stopping..."


        def on_default(self, event):
            self.flush_all_to_default()
            self.str_for_statusbar = "All settings flushed to default"

        def on_pause_play(self, event):
            if self.b_pause_play.GetLabel() == "Play":
                self.lock.release()
                wx.CallAfter(self.b_pause_play.SetLabel, "Pause")
                self.str_for_statusbar = "Computing... "

            else:
                wx.CallAfter(self.b_pause_play.SetLabel, "Play")
                self.lock.acquire()
                self.str_for_statusbar = "Computing paused... "


        def on_close(self, event):
            self.play_thread_alive[0] = False
            self.running = False
            wx.Exit()

        def flush_for_start(self):
            self.make_elements_active(True, *self.enable_disable_set)
            wx.CallAfter(self.b_pause_play.SetLabel, "Pause")


            self.lock.acquire()
            self.winlist[0] = 0
            self.winlist[1] = 0
            self.winlist[2] = 0
            self.maplist[0] = Map()
            self.maplist[1] = Map()
            self.maplist[2] = 0
            self.lock.release()

            wx.CallAfter(self.l_bot1_wins.SetLabel, "0")
            wx.CallAfter(self.l_bot2_wins.SetLabel, "0")


            wx.CallAfter(self.g_progress.SetRange, 100)
            wx.CallAfter(self.g_progress.SetValue, 0)


        def flush_all_to_default(self):
            self.make_elements_active(True, *self.enable_disable_set)
            wx.CallAfter(self.b_pause_play.SetLabel, "Pause")
            self.judge = None
            self.bot1_path = None
            self.bot2_path = None
            self.bot1_name = None
            self.bot2_name = None

            self.lock.acquire()
            self.winlist[0] = 0
            self.winlist[1] = 0
            self.winlist[2] = 0
            self.maplist[0] = Map()
            self.maplist[1] = Map()
            self.maplist[2] = 0
            self.lock.release()

            wx.CallAfter(self.l_bot1_name.SetLabel, "?BOT1?")
            wx.CallAfter(self.l_bot2_name.SetLabel, "?BOT2?")
            wx.CallAfter(self.l_bot1_wins.SetLabel, "0")
            wx.CallAfter(self.l_bot2_wins.SetLabel, "0")

            wx.CallAfter(self.b_add_bot1.SetLabel, "Choose bot 1")
            wx.CallAfter(self.b_add_bot2.SetLabel, "Choose bot 2")

            wx.CallAfter(self.c_round_pause.SetValue, "0")
            wx.CallAfter(self.c_rounds.SetValue, 1)
            wx.CallAfter(self.c_turn_pause.SetValue, "0")

            wx.CallAfter(self.g_progress.SetRange, 100)
            wx.CallAfter(self.g_progress.SetValue, 0)


            #self.lock.release()


        def get_round_pause(self):
            x = self.c_round_pause.GetValue()
            try:
                x = float(x)
                if 0 <= x <= 3:
                    return x
                else:
                    wx.CallAfter(self.c_round_pause.SetValue, str(min(x, 3) if x > 3 else max(0, x)))
                    self.str_for_statusbar = "Warning! Pause must be between 0 and 3 sec! "
                    return float(min(x, 3) if x > 3 else max(0, x))
            except:
                self.str_for_statusbar = "Error! Pause must be a float number between 0 and 3 sec! "
                wx.CallAfter(self.c_round_pause.SetValue, str(0))
                return 0.0


        def get_turn_pause(self):
            x = self.c_turn_pause.GetValue()
            try:
                x = float(x)
                if 0 <= x <= 3:
                    return x
                else:
                    wx.CallAfter(self.c_turn_pause.SetValue, str(min(x, 3) if x > 3 else max(0, x)))
                    self.str_for_statusbar = "Warning! Pause must be between 0 and 3 sec! "
                    return float(min(x, 3) if x > 3 else max(0, x))
            except:
                self.str_for_statusbar = "Error! Pause must be a float number between 0 and 3 sec! "
                wx.CallAfter(self.c_turn_pause.SetValue, str(0))
                return 0.0



        def start_judge(self):
            if self.bot1_path and self.bot2_path:
                try:
                    self.play_thread_alive[0] = True
                    if self.judge:
                        self.judge.__del__()

                    tp = self.get_turn_pause()
                    rp = self.get_round_pause()
                    if not (tp is None) and not(rp is None):
                        self.judge = Judge(self.bot1_path, self.bot2_path,
                                       tp,
                                       rp,
                                       self.lock,
                                       self.play_thread_alive)
                        self.bot1_name = self.judge.bot1.name
                        wx.CallAfter(self.l_bot1_name.SetLabel, self.bot1_name + " (1)")
                        self.bot2_name = self.judge.bot2.name
                        wx.CallAfter(self.l_bot2_name.SetLabel, self.bot2_name + " (2)")
                except:
                    self.flush_all_to_default()
                    self.str_for_statusbar = "Error! You choose wrong file or file isn't a Bot program"


        def on_add_bot1(self, event):
            if self.b_add_bot1.GetLabel() != "OK":
                if self.dialog.ShowModal() == wx.ID_OK:
                    self.bot1_path = self.dialog.GetPath()
                    wx.CallAfter(self.b_add_bot1.SetLabel, "OK")
                    self.start_judge()
                    self.str_for_statusbar = "Bot 1 choosed"



        def on_add_bot2(self, event):
            if self.b_add_bot2.GetLabel() != "OK":
                if self.dialog.ShowModal() == wx.ID_OK:
                    self.bot2_path = self.dialog.GetPath()
                    wx.CallAfter(self.b_add_bot2.SetLabel, "OK")
                    self.start_judge()
                    self.str_for_statusbar = "Bot 2 choosed"



        def start_chemp(self, *args):
            self.flush_for_start()
            self.is_computing = True

            self.make_elements_active(False, *self.enable_disable_set)
            self.make_elements_active(True, *[self.b_pause_play, self.b_stop])
            wx.CallAfter(self.g_progress.SetRange, args[0])
            wx.CallAfter(self.g_progress.SetValue, 0)
            self.start_judge()
            self.str_for_statusbar = "Computing..."
            try:
                self.judge.play_championship(*args)
            except:
                pass
            self.make_elements_active(True, *self.enable_disable_set)
            self.make_elements_active(False, *[self.b_pause_play, self.b_stop])

            self.is_computing = False
            if not self.play_thread_alive[0]:
                self.str_for_statusbar = "Stopped."
            else:
                self.str_for_statusbar = "Complete!"


        def on_start_chemp(self, event):
            if self.judge:
                t = threading.Thread(target = self.start_chemp,
                                      args = (self.c_rounds.GetValue(), self.maplist, self.winlist))
                #self.judge.play_championship(3, self.maplist, self.winlist)
                t.start()


        def refresh(self):
            qmap = 0
            qwin = 0
            while self.running:
                self.lock.acquire()

                if self.maplist[2] != qmap:
                    qmap = self.maplist[2]
                    wx.CallAfter(self.field1.make_empty, self.maplist[0])
                    wx.CallAfter(self.field2.make_empty, self.maplist[1])
                    #self.field1.make_empty(self.maplist[0])
                    #self.field2.make_empty(self.maplist[1])
                if self.winlist[2] != qwin:
                    qwin = self.winlist[2]
                    wx.CallAfter(self.l_bot1_wins.SetLabel, str(self.winlist[0]))
                    wx.CallAfter(self.l_bot2_wins.SetLabel, str(self.winlist[1]))

                wx.CallAfter(self.g_progress.SetValue, self.winlist[2])
                if self.is_computing:
                    wx.CallAfter(self.status_bar.SetStatusText, self.str_for_statusbar +
                                 " Now on %d round" % (self.winlist[2]+1, ) )
                else:
                    wx.CallAfter(self.status_bar.SetStatusText, self.str_for_statusbar)
                wx.CallAfter(self.field1.refresh)
                wx.CallAfter(self.field2.refresh)

                #self.Refresh()

                self.lock.release()
                time.sleep(0.1)
Exemplo n.º 47
0
class Bloody99:
    def __init__(self):
        self.judge = Judge() #need to pause it
        self.initGame()

    def loadImg(self):
        self.background_img_file = 'Image/Nostalgy.gif'
        self.beginning_bg_file = 'Image/AIposter.gif'
        self.cardImgFileName = list()
        self.cardImgFileName.append('Image/01s.gif')
        self.cardImgFileName.append('Image/02s.gif')
        self.cardImgFileName.append('Image/03s.gif')
        self.cardImgFileName.append('Image/04s.gif')
        self.cardImgFileName.append('Image/05s.gif')
        self.cardImgFileName.append('Image/06s.gif')
        self.cardImgFileName.append('Image/07s.gif')
        self.cardImgFileName.append('Image/08s.gif')
        self.cardImgFileName.append('Image/09s.gif')
        self.cardImgFileName.append('Image/10s.gif')
        self.cardImgFileName.append('Image/11s.gif')
        self.cardImgFileName.append('Image/12s.gif')
        self.cardImgFileName.append('Image/13s.gif')
        self.cardImgFileName.append('Image/01h.gif')
        self.cardImgFileName.append('Image/02h.gif')
        self.cardImgFileName.append('Image/03h.gif')
        self.cardImgFileName.append('Image/04h.gif')
        self.cardImgFileName.append('Image/05h.gif')
        self.cardImgFileName.append('Image/06h.gif')
        self.cardImgFileName.append('Image/07h.gif')
        self.cardImgFileName.append('Image/08h.gif')
        self.cardImgFileName.append('Image/09h.gif')
        self.cardImgFileName.append('Image/10h.gif')
        self.cardImgFileName.append('Image/11h.gif')
        self.cardImgFileName.append('Image/12h.gif')
        self.cardImgFileName.append('Image/13h.gif')
        self.cardImgFileName.append('Image/01d.gif')
        self.cardImgFileName.append('Image/02d.gif')
        self.cardImgFileName.append('Image/03d.gif')
        self.cardImgFileName.append('Image/04d.gif')
        self.cardImgFileName.append('Image/05d.gif')
        self.cardImgFileName.append('Image/06d.gif')
        self.cardImgFileName.append('Image/07d.gif')
        self.cardImgFileName.append('Image/08d.gif')
        self.cardImgFileName.append('Image/09d.gif')
        self.cardImgFileName.append('Image/10d.gif')
        self.cardImgFileName.append('Image/11d.gif')
        self.cardImgFileName.append('Image/12d.gif')
        self.cardImgFileName.append('Image/13d.gif')
        self.cardImgFileName.append('Image/01c.gif')
        self.cardImgFileName.append('Image/02c.gif')
        self.cardImgFileName.append('Image/03c.gif')
        self.cardImgFileName.append('Image/04c.gif')
        self.cardImgFileName.append('Image/05c.gif')
        self.cardImgFileName.append('Image/06c.gif')
        self.cardImgFileName.append('Image/07c.gif')
        self.cardImgFileName.append('Image/08c.gif')
        self.cardImgFileName.append('Image/09c.gif')
        self.cardImgFileName.append('Image/10c.gif')
        self.cardImgFileName.append('Image/11c.gif')
        self.cardImgFileName.append('Image/12c.gif')
        self.cardImgFileName.append('Image/13c.gif')
        self.iBack_Card = 'Image/back101.gif'
        # load the image
        self.background = pygame.image.load(self.background_img_file).convert()
        self.beginning_bg = pygame.image.load(self.beginning_bg_file).convert()
        self.cardImg = list()
        for i in range(0, len(self.cardImgFileName)):
            self.cardImg.append(pygame.image.load(self.cardImgFileName[i]).convert())
        self.Back_Card = pygame.image.load(self.iBack_Card).convert()
        self.Back_Card90 = pygame.transform.rotate(self.Back_Card , 90)
        self.Back_Cardn90 = pygame.transform.rotate(self.Back_Card , -90)

    def initPos(self):
        self.player_card_x = SCREEN_SIZE[0]/2 - self.Back_Card90.get_width() 
        self.player_card_y = SCREEN_SIZE[1] - self.cardImg[0].get_height()
        self.p2_card_x = SCREEN_SIZE[0] - self.Back_Card90.get_width() - 10
        self.p2_card_y = SCREEN_SIZE[1]/2 - self.cardImg[0].get_height()
        self.p3_card_x = SCREEN_SIZE[0]/2 - self.Back_Card90.get_width()
        self.p3_card_y = 10 
        self.p4_card_x = 10
        self.p4_card_y = SCREEN_SIZE[1]/2 - self.cardImg[0].get_height()
        self.click_move_x = self.cardImg[0].get_width()/6
        self.click_move_y = self.cardImg[0].get_height()/6

    def num_to_cards(self, num):
        return self.cardImg[num-1]

    def runGame(self):
        i = 1 
        self.prevCard = list()
        log = logger("bloody99.txt")
        self.fill_background()
        for k in range(i):
            pygame.display.update()
            self.judge = Judge()
            self.judge._possibleActions_ = list()
            self.judge.initBoard()
            self.judge.rand4Cards()
            self.fill_background()
            self.resetCardPos()
            if self.judge.isDead[0] == False:
                self.display_player1()
            elif self.judge.isDead[1] == False:
                self.display_player2()
            elif self.judge.isDead[2] == False:
                self.display_player3()
            elif self.judge.isDead[3] == False:
                self.display_player4()
            pygame.display.update()
            
            while not self.judge.isGameFinished():
                self.judge._possibleActions_ = self.judge.getAction()
                if len(self.judge._possibleActions_) == 0:
                    self.judge.setDead(self.judge.current_player)
                    self.judge.changeNextPlayer()
                    continue
                self.fill_background()
                self.resetCardPos()
                self.display_allPlayers()
                self.display_desktop(self.prevCard)
                pygame.display.update()
                state = PlayerState(self.judge.history, self.judge._possibleActions_, self.judge.card[self.judge.current_player-1], len(self.judge.card[0]), len(self.judge.card[1]), len(self.judge.card[2]), len(self.judge.card[3]), len(self.judge.mountain), self.judge.point, self.judge.clock_wise, self.judge.small_h[self.judge.current_player-1]) #get playerstate
                
                if self.judge.player[self.judge.current_player-1].__class__.__name__ == "HumanAgent":
                    click = True
                    while click:
                        for event in pygame.event.get():
                            if event.type == QUIT:
                                pygame.quit()
                                exit()
                            if event.type == MOUSEBUTTONDOWN:
                                if event.button == 1:
                                    self.clickCard(pygame.mouse.get_pos())
                                if event.button == 3:
                                    cards_used = []
                                    for cardIdx in range(len(self.card_clicked_list)):
                                        if self.card_clicked_list[cardIdx] == 1:
                                            cards_used.append(self.judge.card[self.judge.current_player-1][cardIdx])
                                    a = self.judge.player[self.judge.current_player-1].pygameGenmove(self.judge.current_player, cards_used)
                                    a.user = self.judge.current_player
                                    a.victim = self.chooseVictim(a)
                                    if self.judge.checkRule(a) == True and len(cards_used) > 0:
                                        click = False
                                        for v in a.cards_used:
                                            a.cardValue += 13 if (v % 13 == 0) else v % 13
                                        self.fill_background()
                                        self.resetCardPos()
                                        self.display_allPlayers()
                                        self.display_desktop(self.prevCard)
                                        pygame.display.update()       
                                        if a.cardValue == 9:
                                            self.exchangeCards(a.user, a.victim, a.cards_used)
                                            pygame.time.delay(300) 
                                        self.judge.doAction(a)                
                                        if a.cardValue == 7:
                                            self.pickOneCard(a.user, a.victim)
                                            pygame.time.delay(300) 
                                            self.getOneCard(a.user, a.victim)
                                            pygame.time.delay(300) 
                                        self.fill_background()
                                        self.resetCardPos()
                                        self.display_allPlayers()
                                        self.prevCard = a.cards_used
                                        self.display_desktop(self.prevCard)
                                        pygame.display.update()
                                        break
                                    elif self.judge.checkRule(a) == False and len(cards_used) > 0:
                                        font = pygame.font.Font(None, 40)
                                        text = font.render("ILLEGAL MOVE!!", 1, white)
                                        self.window.blit(text, (self.desk_mid_x*2/3+20, self.desk_mid_y-50))   
                                        pygame.display.update()
                                        continue
                                    else:
                                        self.fill_background()
                                        self.resetCardPos()
                                        self.display_allPlayers()
                                        self.display_desktop(self.prevCard)
                                        pygame.display.update()                                        
                                        continue
                else:                          
                    a = self.judge.player[self.judge.current_player-1].genmove(state)
                    for v in a.cards_used:
                        a.cardValue += 13 if (v % 13 == 0) else v % 13
                    self.fill_background()
                    self.resetCardPos()
                    self.display_allPlayers()
                    self.display_desktop(self.prevCard)
                    pygame.display.update()       
                    if a.cardValue == 9:
                        self.exchangeCards(a.user, a.victim, a.cards_used)
                        pygame.time.delay(300) 
                    self.judge.doAction(a)                
                    if a.cardValue == 7:
                        self.pickOneCard(a.user, a.victim)
                        pygame.time.delay(600) 
                        self.getOneCard(a.user, a.victim)
                        pygame.time.delay(600) 
                    else:
                        pygame.time.delay(1500) 
                    self.fill_background()
                    self.resetCardPos()
                    self.display_allPlayers()
                    self.prevCard = a.cards_used
                    self.display_desktop(self.prevCard)
                    pygame.display.update()
                
            winner = 0
            for i in range(4):
                if self.judge.isDead[i] == False:
                    winner = i
            if winner == 0:
                s = "South "
            elif winner == 1:
                s = "East "
            elif winner == 2:
                s = "North "
            else:
                s = "West "
            if self.judge.player[winner].__class__.__name__ == "HumanAgent":
                font = pygame.font.Font(None, 40)
                text = font.render("You Win!", 1, white)
                self.window.blit(text, (self.desk_mid_x - 20, self.desk_mid_y/2+50))   
                pygame.display.update()
            else:
                font = pygame.font.Font(None, 40)
                #text = font.render(s + ": " + self.judge.player[winner].__class__.__name__ + " is the WINNER!!", 1, white)
                text = font.render(s + "is the WINNER!!", 1, white)
                self.window.blit(text, (self.desk_mid_x*2/3-50, self.desk_mid_y/2+50))   
                pygame.display.update()
            g = Game(i, self.judge.player, str(winner+1))
            log.logGame(g)
        pygame.time.delay(2500) 
        self.screen.blit(self.beginning_bg, (0, 0))
        pygame.display.update()
        clock.tick(60)

    def fill_background(self):
        for y in range(0, SCREEN_SIZE[1], self.background.get_height()):
            for x in range(0, SCREEN_SIZE[0], self.background.get_width()):
                self.window.blit(self.background, (x, y))

    def resetCardPos(self):
        self.player_card_pos = [[0 for x in range(2)] for x in range(len(self.judge.card[0]))]
        for i in range(0, len(self.judge.card[0])):
            self.player_card_pos[i][0] = self.player_card_x + i*self.Back_Card.get_width()/2
            self.player_card_pos[i][1] = self.player_card_y 
        self.card_clicked_list = [0 for x in range(len(self.judge.card[0]))]        
        self.p2_card_pos = [[0 for x in range(2)] for x in range(len(self.judge.card[1]))]
        self.p3_card_pos = [[0 for x in range(2)] for x in range(len(self.judge.card[2]))]
        self.p4_card_pos = [[0 for x in range(2)] for x in range(len(self.judge.card[3]))]
        for i in range(0, len(self.judge.card[1])):
            self.p2_card_pos[i][0] = self.p2_card_x
            self.p2_card_pos[i][1] = self.p2_card_y + i*self.Back_Card90.get_height()/2
        for i in range(0, len(self.judge.card[2])):
            self.p3_card_pos[i][0] = self.p3_card_x + i*self.Back_Card.get_width()/2
            self.p3_card_pos[i][1] = self.p3_card_y
        for i in range(0, len(self.judge.card[3])):
            self.p4_card_pos[i][0] = self.p4_card_x
            self.p4_card_pos[i][1] = self.p4_card_y + i*self.Back_Cardn90.get_height()/2

    def display_allPlayers(self):
        self.display_player1()
        self.display_player2()
        self.display_player3()
        self.display_player4()

    def display_player1(self, skipIdx = list()):        
        if len(skipIdx) > 0:
            for x in range(0, len(self.judge.card[0])):
                skip = False
                for i in range(0, len(skipIdx)):
                    if skipIdx[i] != x:
                        continue
                    else:
                        skip = True
                        break
                if skip != True:
                    self.window.blit(self.num_to_cards(self.judge.card[0][x]), (self.player_card_pos[x][0], self.player_card_pos[x][1]))
        else:
            for x in range(0, len(self.judge.card[0])):
                self.window.blit(self.num_to_cards(self.judge.card[0][x]), (self.player_card_pos[x][0], self.player_card_pos[x][1]))
        font = pygame.font.Font(None, 30)
        if self.judge.current_player == 1:
            word = "South: " + self.judge.player[0].__class__.__name__ 
            text = font.render(word, 1, blue)
            self.window.blit(text, (self.player_card_x,self.player_card_y-50))

    def display_player2(self, skipIdx = list()):
        if len(skipIdx) > 0:
            for x in range(0, len(self.judge.card[1])):
                skip = False
                for i in range(0, len(skipIdx)):
                    if skipIdx[i] != x:
                        continue
                    else:
                        skip = True
                        break
                if skip != True:
                    self.window.blit(self.Back_Card90, (self.p2_card_pos[x][0], self.p2_card_pos[x][1]))
        else:
            for x in range(0, len(self.judge.card[1])):
                self.window.blit(self.Back_Card90, (self.p2_card_pos[x][0], self.p2_card_pos[x][1]))
        if self.judge.current_player == 2:
            font = pygame.font.Font(None, 30)
            #word = "East: " + self.judge.player[1].__class__.__name__ 
            word = "East" 
            text = font.render(word, 1, blue)
            self.window.blit(text, (self.p2_card_x-80, self.p2_card_y-50))

    def display_player3(self, skipIdx = list()):
        if len(skipIdx) > 0:
            for x in range(0, len(self.judge.card[2])):
                skip = False
                for i in range(0, len(skipIdx)):
                    if skipIdx[i] != x:
                        continue
                    else:
                        skip = True
                        break
                if skip != True:
                    self.window.blit(self.Back_Card, (self.p3_card_pos[x][0], self.p3_card_pos[x][1]))
        else:
            for x in range(0, len(self.judge.card[2])):
                self.window.blit(self.Back_Card, (self.p3_card_pos[x][0], self.p3_card_pos[x][1]))
        if self.judge.current_player == 3:
            font = pygame.font.Font(None, 30)
            #word = "North: " + self.judge.player[2].__class__.__name__ 
            word = "North" 
            text = font.render(word, 1, blue)
            self.window.blit(text, (self.p3_card_x, self.p3_card_y + self.Back_Card90.get_width()))

    def display_player4(self, skipIdx = list()):
        if len(skipIdx) > 0:
            for x in range(0, len(self.judge.card[3])):
                skip = False
                for i in range(0, len(skipIdx)):
                    if skipIdx[i] != x:
                        continue
                    else:
                        skip = True
                        break
                if skip != True:
                    self.window.blit(self.Back_Cardn90, (self.p4_card_pos[x][0], self.p4_card_pos[x][1]))
        else:
            for x in range(0, len(self.judge.card[3])):
                self.window.blit(self.Back_Cardn90, (self.p4_card_pos[x][0], self.p4_card_pos[x][1]))
        if self.judge.current_player == 4:
            font = pygame.font.Font(None, 30)
            #word = "West: " + self.judge.player[3].__class__.__name__ 
            word = "West" 
            text = font.render(word, 1, blue)
            self.window.blit(text, (self.p4_card_x, self.p4_card_y-50))

    def display_desktop(self, cards):
        self.desk_card_pos = [[0 for x in range(2)] for x in range(len(cards))]
        self.desk_mid_x = SCREEN_SIZE[0]/2 - len(cards)*self.cardImg[0].get_width()/2
        self.desk_mid_y = SCREEN_SIZE[1]/2 - self.cardImg[0].get_height()/2
        for i in range(0, len(cards)):
            self.desk_card_pos[i][0] = self.desk_mid_x + i*self.cardImg[0].get_width()
            self.desk_card_pos[i][1] = self.desk_mid_y
        for i in range(0, len(cards)):
            self.window.blit(self.num_to_cards(cards[i]), (self.desk_card_pos[i][0], self.desk_card_pos[i][1]))
        font = pygame.font.Font(None, 40)
        text = font.render("Point: " + str(self.judge.point), 1, white)
        self.window.blit(text, (SCREEN_SIZE[0]-150,10))
        
    def clickCard(self, mousePos):
        for i in range(0, len(self.judge.card[0])):
            if i == len(self.judge.card[0])-1:
                x = 1
            else:
                x = 0
            if self.player_card_x <= mousePos[0] < self.player_card_x + (i+1+x)*self.cardImg[0].get_width()/2:
                if self.card_clicked_list[i] == 0:
                    # choose the card
                    if self.player_card_y <= mousePos[1] < self.player_card_y + self.cardImg[0].get_height():
                        self.moveCard_player([0,-1], i)
                        self.card_clicked_list[i] = 1
                        break                
                elif self.card_clicked_list[i] == 1:
                    # cancel the choosed card
                    if self.player_card_y - self.click_move_y <= mousePos[1] < self.player_card_y - self.click_move_y + self.cardImg[0].get_height():
                        self.moveCard_player([0,1], i)
                        self.card_clicked_list[i] = 0
                        break

    def moveCard_player(self, dist, idx, skipIdx = list(), skipDuo = (-1,list())):
        oldy = self.player_card_pos[idx][1]
        while abs(self.player_card_pos[idx][1] - oldy) <= self.click_move_y:
            self.player_card_pos[idx][0] += dist[0]
            self.player_card_pos[idx][1] += dist[1]
            self.fill_background()
            self.display_player1(skipIdx)
            if skipDuo[0] == -1:
                self.display_player2()
                self.display_player3()
                self.display_player4()
            elif skipDuo[0] == 2:
                self.display_player2(skipDuo[1])
                self.display_player3()
                self.display_player4()
            elif skipDuo[0] == 3:
                self.display_player3(skipDuo[1])
                self.display_player2()
                self.display_player4()
            elif skipDuo[0] == 4:
                self.display_player4(skipDuo[1])
                self.display_player2()
                self.display_player3()
            self.display_desktop(self.prevCard)
            clock.tick(60)
            pygame.display.update()

    def moveCard_p2(self, dist, idx, skipIdx = list(), skipDuo = (-1,list())):
        oldx = self.p2_card_pos[idx][0]
        while abs(self.p2_card_pos[idx][0] - oldx) <= self.click_move_x:
            self.p2_card_pos[idx][0] += dist[0]
            self.p2_card_pos[idx][1] += dist[1]
            self.fill_background()
            self.display_player2(skipIdx)
            if skipDuo[0] == -1:
                self.display_player1()
                self.display_player3()
                self.display_player4()
            elif skipDuo[0] == 1:
                self.display_player1(skipDuo[1])
                self.display_player3()
                self.display_player4()
            elif skipDuo[0] == 3:
                self.display_player3(skipDuo[1])
                self.display_player1()
                self.display_player4()
            elif skipDuo[0] == 4:
                self.display_player4(skipDuo[1])
                self.display_player1()
                self.display_player3()
            self.display_desktop(self.prevCard)
            clock.tick(60)
            pygame.display.update()

    def moveCard_p3(self, dist, idx, skipIdx = list(), skipDuo = (-1,list())):
        oldy = self.p3_card_pos[idx][1]
        while abs(self.p3_card_pos[idx][1] - oldy) <= self.click_move_y:
            self.p3_card_pos[idx][0] += dist[0]
            self.p3_card_pos[idx][1] += dist[1]
            self.fill_background()
            self.display_player3(skipIdx)
            if skipDuo[0] == -1:
                self.display_player1()
                self.display_player2()
                self.display_player4()
            elif skipDuo[0] == 1:
                self.display_player1(skipDuo[1])
                self.display_player2()
                self.display_player4()
            elif skipDuo[0] == 2:
                self.display_player2(skipDuo[1])
                self.display_player1()
                self.display_player4()
            elif skipDuo[0] == 4:
                self.display_player4(skipDuo[1])
                self.display_player1()
                self.display_player2()
            self.display_desktop(self.prevCard)
            clock.tick(60)
            pygame.display.update()

    def moveCard_p4(self, dist, idx, skipIdx = list(), skipDuo = (-1,list())):
        oldx = self.p4_card_pos[idx][0]
        while abs(self.p4_card_pos[idx][0] - oldx) <= self.click_move_x:
            self.p4_card_pos[idx][0] += dist[0]
            self.p4_card_pos[idx][1] += dist[1]
            self.fill_background()
            self.display_player4(skipIdx)
            if skipDuo[0] == -1:
                self.display_player1()
                self.display_player2()
                self.display_player3()
            elif skipDuo[0] == 1:
                self.display_player1(skipDuo[1])
                self.display_player2()
                self.display_player3()
            elif skipDuo[0] == 2:
                self.display_player2(skipDuo[1])
                self.display_player1()
                self.display_player3()
            elif skipDuo[0] == 3:
                self.display_player3(skipDuo[1])
                self.display_player1()
                self.display_player2()
            self.display_desktop(self.prevCard)
            clock.tick(60)
            pygame.display.update()

    def chooseVictim(self, action):
        # 5 7 9(!= user)  10 12 (-1 -2) click the button then set the action.victim to it.
        cardvalue = 0
        for card in action.cards_used:
            if card % 13 != 0:
                cardvalue += card % 13
            else:
                cardvalue += 13
        if cardvalue > 13 or cardvalue < 1:
            return 0
        elif cardvalue == 5:
            w, h = 100, 50                        
            if self.judge.isDead[0] == False:
                button(self.screen, "South",self.player_card_x, self.player_card_y, w, h, green, bright_green)
            if self.judge.isDead[1] == False:
                button(self.screen, "East",self.p2_card_x, self.p2_card_y, w, h, green, bright_green)
            if self.judge.isDead[2] == False:
                button(self.screen, "North",self.p3_card_x, self.p3_card_y, w, h, green, bright_green)
            if self.judge.isDead[3] == False:
                button(self.screen, "West", self.p4_card_x, self.p4_card_y, w, h, green, bright_green)
            pygame.display.update()
            click = True
            while click:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        pygame.quit()
                        exit()
                    if event.type == MOUSEBUTTONDOWN:
                        if event.button == 1:
                            click = False
                            mousePos = pygame.mouse.get_pos()
                            if self.judge.isDead[0] == False and self.player_card_x < mousePos[0] < self.player_card_x + w and self.player_card_y < mousePos[1] < self.player_card_y + h:
                                victim = 1
                            elif self.judge.isDead[1] == False and self.p2_card_x < mousePos[0] < self.p2_card_x + w and self.p2_card_y < mousePos[1] < self.p2_card_y + h:
                                victim = 2
                            elif self.judge.isDead[2] == False and self.p3_card_x < mousePos[0] < self.p3_card_x + w and self.p3_card_y < mousePos[1] < self.p3_card_y + h:
                                victim = 3
                            elif self.judge.isDead[3] == False and self.p4_card_x < mousePos[0] < self.p4_card_x + w and self.p4_card_y < mousePos[1] < self.p4_card_y + h:
                                victim = 4
                            else:
                                click = True
            pygame.display.update()
            return victim
        elif cardvalue == 7 or cardvalue == 9:
            w, h = 100, 50            
            if self.judge.isDead[1] == False:
                button(self.screen, "East",self.p2_card_x, self.p2_card_y, w, h, green, bright_green)
            if self.judge.isDead[2] == False:
                button(self.screen, "North",self.p3_card_x, self.p3_card_y, w, h, green, bright_green)
            if self.judge.isDead[3] == False:
                button(self.screen, "West", self.p4_card_x, self.p4_card_y, w, h, green, bright_green)
            pygame.display.update()
            click = True
            while click:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        pygame.quit()
                        exit()
                    if event.type == MOUSEBUTTONDOWN:
                        if event.button == 1:
                            click = False
                            mousePos = pygame.mouse.get_pos()
                            if self.judge.isDead[1] == False and self.p2_card_x < mousePos[0] < self.p2_card_x + w and self.p2_card_y < mousePos[1] < self.p2_card_y + h:
                                victim = 2
                            elif self.judge.isDead[2] == False and self.p3_card_x < mousePos[0] < self.p3_card_x + w and self.p3_card_y < mousePos[1] < self.p3_card_y + h:
                                victim = 3
                            elif self.judge.isDead[3] == False and self.p4_card_x < mousePos[0] < self.p4_card_x + w and self.p4_card_y < mousePos[1] < self.p4_card_y + h:
                                victim = 4
                            else:
                                click = True
            pygame.display.update()
            return victim
        elif cardvalue == 10 or cardvalue == 12:
            w, h = 100, 50            
            value = 10 if cardvalue == 10 else 20
            button(self.screen, "+"+str(value), SCREEN_SIZE[0]/3-w/2, SCREEN_SIZE[1]/2 , w, h, green, bright_green)
            button(self.screen, "-"+str(value), 2*SCREEN_SIZE[0]/3-w/2, SCREEN_SIZE[1]/2 , w, h, green, bright_green)
            pygame.display.update()
            click = True
            while click:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        pygame.quit()
                        exit()
                    if event.type == MOUSEBUTTONDOWN:
                        if event.button == 1:
                            click = False
                            mousePos = pygame.mouse.get_pos()
                            if SCREEN_SIZE[0]/3-w/2 < mousePos[0] < SCREEN_SIZE[0]/3-w/2 + w and SCREEN_SIZE[1]/2 < mousePos[1] < SCREEN_SIZE[1]/2 + h:
                                victim = -1
                            elif 2*SCREEN_SIZE[0]/3-w/2 < mousePos[0] < 2*SCREEN_SIZE[0]/3-w/2 + w and SCREEN_SIZE[1]/2 < mousePos[1] < SCREEN_SIZE[1]/2 + h:
                                victim = -2
                            else:
                                click = True
            return victim
        if cardvalue == 10 or cardvalue == 12:
            button(self.screen, "-"+str(cardvalue), SCREEN_SIZE[1]/3, SCREEN_SIZE[0]/2 , 100, 50, green, bright_green)
            button(self.screen, "+"+str(cardvalue), 2*SCREEN_SIZE[1]/3, SCREEN_SIZE[0]/2 , 100, 50, green, bright_green)
            pygame.display.update()
            return -1

    def pickOneCard(self, userIdx, victim):
        i = self.judge.p
        if victim == 1:
            self.moveCard_player([0,-1], i, [], [userIdx, [len(self.judge.card[userIdx-1])-1]])
        elif victim == 2:
            self.moveCard_p2([-1,0], i, [], [userIdx, [len(self.judge.card[userIdx-1])-1]])
        elif victim == 3:
            self.moveCard_p3([0,1], i, [], [userIdx, [len(self.judge.card[userIdx-1])-1]])
        elif victim == 4:
            self.moveCard_p4([1,0], i, [], [userIdx, [len(self.judge.card[userIdx-1])-1]])

    def getOneCard(self, userIdx, victim):
        self.fill_background()
        self.resetCardPos()
        self.display_desktop(self.prevCard)
        if userIdx == 1:
            self.player_card_pos[len(self.judge.card[userIdx-1])-1][1] -= self.click_move_y * 3
            self.display_player1()
            self.display_player2()
            self.display_player3()
            self.display_player4()
            self.moveCard_player([0,1], len(self.judge.card[0])-1)
        elif userIdx == 2:
            self.p2_card_pos[len(self.judge.card[userIdx-1])-1][0] -= self.click_move_x * 3
            self.display_player1()
            self.display_player2()
            self.display_player3()
            self.display_player4()
            self.moveCard_p2([1,0], len(self.judge.card[1])-1)
        elif userIdx == 3:
            self.p3_card_pos[len(self.judge.card[userIdx-1])-1][1] += self.click_move_x * 3
            self.display_player1()
            self.display_player2()
            self.display_player3()
            self.display_player4()
            self.moveCard_p3([0,-1], len(self.judge.card[2])-1)
        elif userIdx == 4:
            self.p4_card_pos[len(self.judge.card[userIdx-1])-1][0] += self.click_move_x * 3
            self.display_player1()
            self.display_player2()
            self.display_player3()
            self.display_player4()
            self.moveCard_p4([-1,0], len(self.judge.card[3])-1)
        pygame.display.update()
    
    def exchangeCards(self, userIdx, victim, cards_used):
        self.fill_background()
        self.prevCard = cards_used
        userSkipCard = list()
        for x in range(0, len(self.judge.card[userIdx-1])):
            for y in range(0, len(cards_used)):
                if self.judge.card[userIdx-1][x] == cards_used[y]:
                    userSkipCard.append(x)
        self.resetCardPos()
        self.display_desktop(self.prevCard)
        if userIdx == 1:
            for i in range(0, len(self.judge.card[userIdx-1])):
                self.moveCard_player([0,-1], i, userSkipCard)
        elif userIdx == 2:
            for i in range(0, len(self.judge.card[userIdx-1])):
                self.moveCard_p2([-1,0], i, userSkipCard)
        elif userIdx == 3:
            for i in range(0, len(self.judge.card[userIdx-1])):
                self.moveCard_p3([0,1], i, userSkipCard)
        elif userIdx == 4:
            for i in range(0, len(self.judge.card[userIdx-1])):
                self.moveCard_p4([1,0], i, userSkipCard)
        if victim == 1:
            for i in range(0, len(self.judge.card[victim-1])):
                self.moveCard_player([0,-1], i, [], [userIdx, userSkipCard])
        elif victim == 2:
            for i in range(0, len(self.judge.card[victim-1])):
                self.moveCard_p2([-1,0], i, [], [userIdx, userSkipCard])
        elif victim == 3:
            for i in range(0, len(self.judge.card[victim-1])):
                self.moveCard_p3([0,1], i, [], [userIdx, userSkipCard])
        elif victim == 4:
            for i in range(0, len(self.judge.card[victim-1])):
                self.moveCard_p4([1,0], i, [], [userIdx, userSkipCard])
        pygame.display.update()       

    def initGame(self):
        pygame.init()
        pygame.display.set_caption('Bloody99')

        self.window = pygame.display.set_mode((SCREEN_SIZE[0], SCREEN_SIZE[1]))
        self.screen = pygame.display.get_surface()
        self.loadImg()
        self.initPos()
        pos = (0, 0)
        self.screen.blit(self.beginning_bg, (0, 0))

        intro = True
        while intro:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
            # things need to update
            button(self.screen, "START!",100,400,200,50,green,bright_green,self.runGame)
            button(self.screen, "QUIT",100,500,200,50,red,bright_red,quitGame)
            pygame.display.update()
            clock.tick(15)
Exemplo n.º 48
0
 def runGame(self):
     i = 1 
     self.prevCard = list()
     log = logger("bloody99.txt")
     self.fill_background()
     for k in range(i):
         pygame.display.update()
         self.judge = Judge()
         self.judge._possibleActions_ = list()
         self.judge.initBoard()
         self.judge.rand4Cards()
         self.fill_background()
         self.resetCardPos()
         if self.judge.isDead[0] == False:
             self.display_player1()
         elif self.judge.isDead[1] == False:
             self.display_player2()
         elif self.judge.isDead[2] == False:
             self.display_player3()
         elif self.judge.isDead[3] == False:
             self.display_player4()
         pygame.display.update()
         
         while not self.judge.isGameFinished():
             self.judge._possibleActions_ = self.judge.getAction()
             if len(self.judge._possibleActions_) == 0:
                 self.judge.setDead(self.judge.current_player)
                 self.judge.changeNextPlayer()
                 continue
             self.fill_background()
             self.resetCardPos()
             self.display_allPlayers()
             self.display_desktop(self.prevCard)
             pygame.display.update()
             state = PlayerState(self.judge.history, self.judge._possibleActions_, self.judge.card[self.judge.current_player-1], len(self.judge.card[0]), len(self.judge.card[1]), len(self.judge.card[2]), len(self.judge.card[3]), len(self.judge.mountain), self.judge.point, self.judge.clock_wise, self.judge.small_h[self.judge.current_player-1]) #get playerstate
             
             if self.judge.player[self.judge.current_player-1].__class__.__name__ == "HumanAgent":
                 click = True
                 while click:
                     for event in pygame.event.get():
                         if event.type == QUIT:
                             pygame.quit()
                             exit()
                         if event.type == MOUSEBUTTONDOWN:
                             if event.button == 1:
                                 self.clickCard(pygame.mouse.get_pos())
                             if event.button == 3:
                                 cards_used = []
                                 for cardIdx in range(len(self.card_clicked_list)):
                                     if self.card_clicked_list[cardIdx] == 1:
                                         cards_used.append(self.judge.card[self.judge.current_player-1][cardIdx])
                                 a = self.judge.player[self.judge.current_player-1].pygameGenmove(self.judge.current_player, cards_used)
                                 a.user = self.judge.current_player
                                 a.victim = self.chooseVictim(a)
                                 if self.judge.checkRule(a) == True and len(cards_used) > 0:
                                     click = False
                                     for v in a.cards_used:
                                         a.cardValue += 13 if (v % 13 == 0) else v % 13
                                     self.fill_background()
                                     self.resetCardPos()
                                     self.display_allPlayers()
                                     self.display_desktop(self.prevCard)
                                     pygame.display.update()       
                                     if a.cardValue == 9:
                                         self.exchangeCards(a.user, a.victim, a.cards_used)
                                         pygame.time.delay(300) 
                                     self.judge.doAction(a)                
                                     if a.cardValue == 7:
                                         self.pickOneCard(a.user, a.victim)
                                         pygame.time.delay(300) 
                                         self.getOneCard(a.user, a.victim)
                                         pygame.time.delay(300) 
                                     self.fill_background()
                                     self.resetCardPos()
                                     self.display_allPlayers()
                                     self.prevCard = a.cards_used
                                     self.display_desktop(self.prevCard)
                                     pygame.display.update()
                                     break
                                 elif self.judge.checkRule(a) == False and len(cards_used) > 0:
                                     font = pygame.font.Font(None, 40)
                                     text = font.render("ILLEGAL MOVE!!", 1, white)
                                     self.window.blit(text, (self.desk_mid_x*2/3+20, self.desk_mid_y-50))   
                                     pygame.display.update()
                                     continue
                                 else:
                                     self.fill_background()
                                     self.resetCardPos()
                                     self.display_allPlayers()
                                     self.display_desktop(self.prevCard)
                                     pygame.display.update()                                        
                                     continue
             else:                          
                 a = self.judge.player[self.judge.current_player-1].genmove(state)
                 for v in a.cards_used:
                     a.cardValue += 13 if (v % 13 == 0) else v % 13
                 self.fill_background()
                 self.resetCardPos()
                 self.display_allPlayers()
                 self.display_desktop(self.prevCard)
                 pygame.display.update()       
                 if a.cardValue == 9:
                     self.exchangeCards(a.user, a.victim, a.cards_used)
                     pygame.time.delay(300) 
                 self.judge.doAction(a)                
                 if a.cardValue == 7:
                     self.pickOneCard(a.user, a.victim)
                     pygame.time.delay(600) 
                     self.getOneCard(a.user, a.victim)
                     pygame.time.delay(600) 
                 else:
                     pygame.time.delay(1500) 
                 self.fill_background()
                 self.resetCardPos()
                 self.display_allPlayers()
                 self.prevCard = a.cards_used
                 self.display_desktop(self.prevCard)
                 pygame.display.update()
             
         winner = 0
         for i in range(4):
             if self.judge.isDead[i] == False:
                 winner = i
         if winner == 0:
             s = "South "
         elif winner == 1:
             s = "East "
         elif winner == 2:
             s = "North "
         else:
             s = "West "
         if self.judge.player[winner].__class__.__name__ == "HumanAgent":
             font = pygame.font.Font(None, 40)
             text = font.render("You Win!", 1, white)
             self.window.blit(text, (self.desk_mid_x - 20, self.desk_mid_y/2+50))   
             pygame.display.update()
         else:
             font = pygame.font.Font(None, 40)
             #text = font.render(s + ": " + self.judge.player[winner].__class__.__name__ + " is the WINNER!!", 1, white)
             text = font.render(s + "is the WINNER!!", 1, white)
             self.window.blit(text, (self.desk_mid_x*2/3-50, self.desk_mid_y/2+50))   
             pygame.display.update()
         g = Game(i, self.judge.player, str(winner+1))
         log.logGame(g)
     pygame.time.delay(2500) 
     self.screen.blit(self.beginning_bg, (0, 0))
     pygame.display.update()
     clock.tick(60)
Exemplo n.º 49
0
#!/usr/bin/env python

import sys, os

try:
    from judge import Judge
    from judge import STDIO, FILE
except:
    path = os.path.realpath(__file__)
    path = os.path.split(path)[0]
    path = os.path.join(path, "..")
    path = os.path.join(path, "..")
    sys.path.append(path)
    from judge import Judge
    from judge import STDIO, FILE

if __name__=="__main__":
    judge = Judge()
    judge.add_test(["sh", "1.sh", "yes"], "yesyes", style=STDIO)
    judge.add_test(["sh", "1.sh",], "error", style=STDIO)
    judge.run()