def handleDisconnect():
    try:
        close_room(session["user"])
        del gameBoards[session["user"]]
    except Exception as e:
        print(e)
    for x, y in userPairs.items():
        if x == session["user"]:
            emit("disconnect", y, room=y)
            if (y):
                gameBoards[y] = game()
            if (userPairs[x]):
                userPairs[y] = False
                del userPairs[x]
                break
                y = False
            else:
                del userPairs[x]
                break
        if y == session["user"]:
            emit("disconnect", x, room=x)
            gameBoards[x] = game()
            userPairs[x] = False
            break
    print(userPairs)
    print(gameBoards)
Exemple #2
0
def index():

    players = []
    gameJson = []
    data = None

    if 'user' not in session:
        user = str(uuid4())
        session['user'] = user
        mc[user] = []

    else:
        user = session['user']
        players = mc[user]
        gameObj = game(players)
        mc[user] = gameObj[0]
        gameJson = gameObj[1]

    if request.method == 'POST':
        data = request.get_json(force=False, silent=True)
        gameObj = game(players, **data)
        mc[user] = gameObj[0]
        gameJson = gameObj[1]
        return jsonify(gameJson)

    return render_template('index.html', data=gameJson, time=ctime())
Exemple #3
0
def startgame(App):
    """
    Function creates game object based on user input
    ...

    Parameters
    ----------
    :param App: TKinter window object that deals gui
    :type App: Tk.window

    Return
    ------
    :return t_game: game for user to start playing
    :type t_game: game object
    """
    x = App.username # Pull name data from entry field
    if App.gametype.get() == 0: # Data from radio buttons - load vs new game
        t_game = game(x,new=True)
    elif App.gametype.get() == 1:
        try:
            t_game = game(x,new=False)
        except:
            w("Unable to find user data, will load a new game...")
            t_game = game(x,new=True)
    else:
        t_game = game(x,new=True)
    return t_game
Exemple #4
0
def play(mouse_pos):
    x = mouse_pos[0]
    y = mouse_pos[1]
    if x in range(495, 720) and y in range(250, 450):
        game()
    elif x in range(745, 895) and y in range(315, 450):
        statistics_window()
Exemple #5
0
def eval_once(opp, times=1):
    model.eval()
    win = 0
    lose = 0
    draw = 0
    for t in range(times):
        if is_miwa:
            miwa = abplayer('2 1 3', miwa_dp)
            opp = miwa.play
        res1 = game.game(opp, mlplayer_once)
        if res1 == 0:
            win += 1
        elif res1 == 1:
            lose += 1
        else:
            draw += 1

        if is_miwa:
            miwa = abplayer('2 2 4', miwa_dp)
            opp = miwa.play
        res2 = game.game(mlplayer_once, opp)
        if res2 == 1:
            win += 1
        elif res2 == 0:
            lose += 1
        else:
            draw += 1
    return win, lose, draw
def convertReplay(path,limit=15000):
	replay=sc2reader.load_replay(path)
	players=[]
	races=[]
	for i in replay.players:
		players.append(i.name)
		races.append(i.pick_race)
	if(len(players)>2):
		print("error: replay not 1v1 "+path)
		return ("error","error")
	hot={}
	frame={}
	hot[players[0]]=[]
	hot[players[1]]=[]
	frame[players[0]]=[]
	frame[players[1]]=[]
	for event in replay.events:
		if event.frame>=limit:
			break
		if event.name=="GetControlGroupEvent" or event.name=="SetControlGroupEvent" or event.name=="AddToControlGroupEvent" :
			hot[event.player.name].append(event.hotkey)
			frame[event.player.name].append(event.frame)
	
#mapsc2="",length="",date=""
	if (len(hot[players[0]])>10):				
		g1=game.game(players[0],players[1],races[0],races[1],hot[players[0]],frame[players[0]],path,replay.map_name,replay.length,replay.date)
	else:
		g1="error"
		print("error, not enough frame")
	if (len(hot[players[1]])>10):
		g2=game.game(players[1],players[0],races[1],races[0],hot[players[1]],frame[players[1]],path)
	else:
		g2="error"
		print("error, not enough frame")		
	return (g1,g2)
Exemple #7
0
def robot(s):
    while s.upper() != 'BYE':
        if s == "计算":
            calcstr = str(input('请输入计算表达式:\n\t\t\t\t\t\t'))
            print('计算结果为:{}'.format(eval(calcstr)))
        elif s == '玩游戏':
            n = int(input("我会玩:\n\n1.猜数\n2.掷骰子\n\n你想要玩哪个呢?\n\t\t\t\t\t\t"))
            game(n)
        elif s == "听歌":
            playmusic()
        elif s == "翻译":
            translate()
        elif s == "讲笑话":
            sayjokes()
        elif s == "查询天气":
            inquire()
        elif s == "搜索关键词":
            search()
        elif s == "厉害" or s == "真棒":
            print("谢谢夸奖~")
        else:
            print(random.choice(notunderstand))
        s = str(input("\n{},{}\n\t\t\t\t\t\t".format(user,
                                                     random.choice(ask))))
    print("{},下次再会~\n".format(user))
    def menu(self):
        RunOn = True
        frames = pygame.time.Clock()
        esta_tocando = True
        sound = imagens.soundOn
        self.window.music_on(esta_tocando, musica.menu)
        while RunOn:
            frames.tick(30)
            for event in pygame.event.get():
                if (event.type == pygame.QUIT):
                    RunOn = False
                elif (event.type == pygame.MOUSEBUTTONDOWN):
                    (mouseX, mouseY) = event.pos
                    if (mouseX >= 251) and (mouseX <= 548):
                        if (mouseY >= 179) and (mouseY <= 244):
                            RunOn = False
                            game.game()
                        elif (mouseY >= 299) and (mouseY <= 369):
                            print("sobre")
                        elif (mouseY >= 421) and (mouseY <= 489):
                            RunOn = False
                    elif ((mouseX >= 750) and
                          (mouseX <= 800)) and ((mouseY >= 0) and
                                                (mouseY <= 50)):
                        if esta_tocando:
                            esta_tocando = False
                            sound = imagens.soundOff
                        else:
                            esta_tocando = True
                            sound = imagens.soundOn
                        self.window.music_on(esta_tocando, musica.menu)
            if RunOn:
                self.window.redraw(imagens.menu, sound, self.window)

            pygame.display.update()
Exemple #9
0
def main():
    '''
    main app
    '''
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--rules',
        help='shows game rules',
        action='store_true'
    )
    parser.add_argument(
        '--start',
        '-s',
        help='start a game with player name',
        dest='name'
    )
    parser.add_argument(
        '--leaderboard',
        help='read leaderboard',
        action='store_true'
    )
    args = parser.parse_args()
    if args.name:
        name = args.name
        game(name)
    elif args.rules:
        print(read_from_game_rules())
    elif args.leaderboard:
        leaderboard = read_from_leaderboard()
        if not leaderboard:
            msg = 'nothing found'
        else:
            msg = stringify_leaderboard(leaderboard)
        print(msg)
Exemple #10
0
def main(board, server_moves):
    # board = [
    # 	[0, 0, 0, 0, 0],
    # 	[0, 0, 0, 0, 0, 0],
    # 	[0, 1, 0, 0, 0, 0, 0],
    # 	[0, 0, 0, 0, 0, 0, 0, 0],
    # 	[0, 0, 0, 1, 2, 0, 0, 0, 0],
    # 	[0, 0, 0, 0, 1, 2, 0, 0, 0, 0],
    # 	[1, 0, 0, 0, 0, 0, 0, 0, 0],
    # 	[1, 0, 0, 0, 0, 0, 0, 0],
    # 	[1, 0, 0, 0, 0, 0, 0],
    # 	[0, 0, 0, 0, 0, 0],
    # 	[0, 0, 0, 0, 0]
    # ]

    heuristics = vh.verify_heuristics(board, sys.argv[1])
    #heuristics = None

    if heuristics == None:
        return game.game(sys.argv[1], board, server_moves)
    elif (heuristics[0] + 1, heuristics[1] + 1) not in server_moves:
        return game.game(sys.argv[1], board, server_moves)
    else:
        print('best move: ' + str(heuristics))
        return heuristics
Exemple #11
0
def main():
	""" Request input from player """

	while True:
		input = raw_input(constants.ENTER)
		if input == 's':
			game()
			break
Exemple #12
0
def single_mode():
	clear()
	update_parameters()
	game_bar()
	cos = Frame(root)
	game(cos, int(parameters['size']), [], 'single')
	cos.grid(pady=20, padx=40)
	back_button = Button(root, text=u"\u2302", command=starting_menu).grid(column=1, row=0, sticky='N', padx=40, pady=40)
Exemple #13
0
def main():
    """ Request input from player """

    while True:
        input = raw_input(constants.ENTER)
        if input == 's':
            game()
            break
def test_game_01():
   assert game('piedra', 'tijera') == 'p1', 'Unexpected result'
   assert game('tijera', 'piedra') == 'p2', 'Unexpected result'
   assert game('tijera', 'papel') == 'p1', 'Unexpected result'
   # p1= raw_input ('jugador 1: ')
    #p2= raw_input ('jugador 2: ')
    #print game(p1,p2)
   
    
Exemple #15
0
def sim_season(team1, team2, games=82):
    for i in range(games):
        game.game(team1, team2)

    for team in [team1, team2]:
        print ''
        print team.name
        name_width = max([len(p.name) for p in team.players])
        print '|        Name        | PPG  | ASS/G | FG%  | 3PT%  | FGA/G| TO/G | STL/G | BLK/G | REB/G |OREB/G | MIN/G |'
        print '----------------------------------------------------------------------------------------------------------'
        for p in team.players:
            p.fga = p.fg2a + p.fg3a
            p.fgm = p.fg2m + p.fg3m
            ppg = '%.1f' % (float(p.points) / games)
            fg_string = '%.1f' % (100 * float(p.fgm) / p.fga)
            try:
                fg3_string = '%.1f' % (100 * float(p.fg3m) / p.fg3a)
            except:
                fg3_string = '0.0'
            fgag = '%.1f' % (float(p.fga) / games)
            apg = '%2.1f' % (float(p.assists) / games)
            topg = '%.1f' % (float(p.turnovers) / games)
            spg = '%.1f' % (float(p.steals) / games)
            bpg = '%.1f' % (float(p.blocks) / games)
            rpg = '%.1f' % (float(p.rebounds) / games)
            orpg = '%.1f' % (float(p.off_rebounds) / games)
            avg_secs = p.time_played.total_seconds() / games
            hours, remainder = divmod(avg_secs, 3600)
            minutes, seconds = divmod(remainder, 60)
            minutes = '%02d' % minutes
            seconds = '%02d' % seconds
            mpg = '%s:%s' % (minutes, seconds)
            print '|{0:<{n}}|{1:<{p}}|{2:<{f}}|{3:<{p}}|{4:<{f}}|{5:<{p}}|{6:<{p}}|{7:<{f}}|{8:<{f}}|{9:<{f}}|{10:<{f}}|{11:<{f}}|'.format(
                p.name,
                ppg,
                apg,
                fg_string,
                fg3_string,
                fgag,
                topg,
                spg,
                bpg,
                rpg,
                orpg,
                mpg,
                n=20,
                p=6,
                f=7)

    print ''
    t1ppg = '%.1f' % (float(team1.season_points) / games)
    t2ppg = '%.1f' % (float(team2.season_points) / games)
    print '%s: %s-%s  -  %s PPG' % (team1.name, team1.wins, team1.losses,
                                    t1ppg)
    print '%s: %s-%s  -  %s PPG' % (team2.name, team2.wins, team2.losses,
                                    t2ppg)
Exemple #16
0
def general(text: str):
    check = False
    if is_arithmetic(text):
        text = "คำตอบ คือ " + str(eval(text)) + " ค่ะ"
        check = True
    elif "เล่นเกม" in text:
        game()
        check = True
        text = ""
    return (text, check)
Exemple #17
0
def main():
   
   '''Probably for selecting level, getting user's name...etc
   someParameter should be a dictionary
   '''
   stats = runWelcomeScreen() 

   '''Run the actual game after welcome screen done'''
   game.game(stats)

   endGame() 
Exemple #18
0
def game_loop(lv, start):
    global colidiu
    global bullets
    LV = lv
    g.game(u.colidiu, u.bullets, relogio, t.tela, u.ColorW, c.cat.MoveU,
           c.cat.MoveD, c.cat.MoveL, c.cat.MoveR, cat.wreck_start, cat.wrecked,
           cat, grupo_obstaculos, u.ColorY, todas_as_sprites, mouse1, mouse2,
           mouse3, mouse4, u.x, u.y, u.game_over, grupo_oM1, grupo_oM2,
           grupo_oM3, grupo_oM4, u.colidiuM, u.LV, u.run, cloud, back, start,
           u.Tm, u.Mega, u.w, u.h, u.Mega_On, u.p, u.r, u.l, u.N, u.cont, u.Q,
           u.V, u.up, u.Vup)
Exemple #19
0
def main():
    print('Welcome to Rock, Paper, Scissors, Lizard, Spock')
    player1 = player('Player 1')
    player2 = player('Player 2')
    game1 = game('Game 1', player1, player2)
    game2 = game('Game 2', player1, player2)
    game3 = game('Game 3', player1, player2)
    games = (game1, game2, game3)
    getPlayer2(player2)
    for gameInstance in games:
        game.getrResult(gameInstance)
    playAgain()
Exemple #20
0
 def on_key_press(symbol, modifiers):
     if symbol == key.BACKSPACE:
         window.set_exclusive_mouse(False)
         window.exclusive = False
     # Hand control of the window over to the next driver
     elif symbol == key.F1:
         #color_cube_batch needs to be deleted
         color_cube_vl.delete()
         pyglet.clock.unschedule(camera.camera_update)
         game.game(window)
     elif symbol == key.F2:
         color_cube_vl.delete()
         pyglet.clock.unschedule(camera.camera_update)
         game.viewer(window)
Exemple #21
0
    def init_game(self, create: bool, ip: Optional[List[IPv4Address]],
                  port: Optional[List[int]]) -> None:
        ai_plays = not create and ip is None
        if create or ai_plays:
            server_player, client_player, height, width = \
                self._config_game(ai_plays)
            if not ai_plays:
                assert port is not None
                self._echo_server(server_player, client_player, port[0])

            game(height, width, self.player1, self.player2)
        else:
            assert ip is not None and port is not None
            self._echo_client(ip[0], port[0])
Exemple #22
0
def startup():
    os.system('clear')
    player = characters.character(20, 10, [], "")
    while player.name == "":
        s = raw_input("What would you like to do? New/Load: ")
        choice = s.lower()
        if choice == "new":
            player.name = intro(player)
            print player.name
            game.game(player)
        elif choice == "load":
            instance.load(player)
            game.game(player)
        else:
            print "That is not a valid command."
Exemple #23
0
def play_game():
  import game as p
  print('\n\n*****************************************************************************\nDescription of the game you\'ll play in each of the 5 turns:\n\nTake a coin and denote heads by H and tails by T. Select a sequence of length three as you wish, consisting of heads (denoted H) and tails (denoted T), e.g. your choice could be HHT or TTH or HHH or TTT etc.The computer will ask you to enter your choice. The computer will then make its own choice of a sequence of length three with heads and tails.\n\nStart the game:\n\nYou toss the coin. If its heads, you enter H, if its tails, you enter T. Then again you toss the coin and enter what comes up and go on doing this, thereby getting a series of heads and tails e.g. HHTTHHTTTH......\n\n\nWinning rule:\nYou win (and the game stops) the moment you see the sequence of length three which you have selected, occuring side by side, in this series of H\'s and T\'s. The computer wins if the same happens with its choice.\n\nFor your convenience, the computer will keep a track of the occurences of heads and tails as you go on tossing, and it will point out the moment there is a match. In case you think this is a trick, well its not! Keep track of heads and tails yourself if you like, should you choose not to trust the computer on this!\n\nPLEASE TOSS THE COIN PROPERLY, ELSE IT WONT\'T BE RANDOM REALLY! \n********************************************************************************')

  while True:
    a = raw_input('\n\nPress Y to continue and N to quit:')

    if (a == 'Y') or (a == 'y'):
      p.game()
      break
    elif (a == 'N') or (a == 'n'):
      print('Thank you for your time!')
      break 
    else:
      print('Please enter a valid choice.')
Exemple #24
0
def test_game(start, choice1, choice2, expected):
    if start == "YES":
        if choice1 and choice1 not in ("ROCK", "PAPER", "SCISSORS"):
            print("Invalid choice")
            return False

        else:
            print(choice1, choice2)
            dec = game(choice1, choice2, start)
            assert dec == expected
            return True
        
    elif start == "NO":
        dec = game(choice1, choice2, start)
        assert dec == expected
Exemple #25
0
def message(xml):
    dom = minidom.parseString(xml)
    root = dom.firstChild 
    children = [node for node in root.childNodes if node.nodeType == 1]

    mes_type = children[3].childNodes[0].data
    uid = children[1].childNodes[0].data
    me = children[0].childNodes[0].data
    status = user_status(uid,1,g)

    mes = "想跟我聊天?直接输入文字就好了"
    
    if mes_type == 'text':
        text = children[4].childNodes[0].data
        if text == 'Hello2BizUser':
            mes = "欢迎您关注中大信科学生会的微信!\n\n您可以通过#加吐嘈内容向我们提任何意见,我们将会及时回复。十分欢迎您对信科学生会的工作提出质疑与建议。此外,您可以输入任何文字跟我聊天,打发闲暇时间。\n\n信科女生节「逸仙传说」微信游戏正式上线!一个信科女神的奇幻故事,一段尘封许久的逸仙传说,一次精彩绝伦的冒险之旅!回复“女神冒险”开始一次伟大的冒险旅程!\n\n你的希望,我的可能!\nYour will, we will!"
        elif text[0] == '#':
            mes = advise(text[1:])
        elif text == '女神冒险' or not status == 'new' :
            mes = game(uid,text,g)
        else :
            mes = get_response(text)

    word_list = mes.split('#e#')
    if len(word_list) == 2 :
        return replypic % (uid,me,'%d' % (int(time.time())),word_list[1],word_list[0],word_list[0])
    return replytext % (uid,me,'%d' % (int(time.time())),word_list[0])
Exemple #26
0
    def round_end_message(self, status):
        """
        Handles the creation of a new game object,
        adds the 'games' global list for bookkeeping.
        :param status:  values of 1 or other values for different
                        prompts when user guesses right or gives
                        up respectively.
        """
        uncovered_indices = [
            i for i, x in enumerate(self.user_word) if x == "-"
        ]

        _game = game.game(
            len(self.games) + 1, "".join(self.correct_word), self.status,
            self.total_bad_guesses, len(uncovered_indices), self.total_score)
        self.games.append(_game)

        if status == 1:
            print("You guessed the right answer. it was truely " +
                  "".join(self.correct_word))

        elif status == 0:
            print("Dont give up next time.the right answer was " +
                  "".join(self.correct_word))
        else:
            self.menu()
            self.choose_option()
Exemple #27
0
	def addReplayFromData(self,filename):
		#we add the p1 and p2 files
		#print("add "+ filename +"to "+self.name)
		f=open(filename)
		name1=f.readline().rstrip()
		name2=f.readline().rstrip()
		race1=f.readline().rstrip()
		race2=f.readline().rstrip()
		hotkeys=[]
		frames=[]
		for line in f:
			t=line.rstrip().split("\t")
			hotkeys.append(int(t[0]))
			frames.append(int(t[1]))
		#create the game ,verify that list are not empty
		#compute matrix and APM of games 
		if (len(frames)!=0):
			
			g=game.game(name1,name2,race1,race2,hotkeys,frames,path=filename)
			g.calculateAllFeatures(self.limit_matrix,0,self.limit_apm)
			#g.calculate_matrix(self.limit_matrix)
			#g.calculate_frequency(self.limit_matrix)
			#g.calculateFrequencyGap()
			#g.normalize_matrix()
			#g.calculateAPMj1(self.limit_apm)
			
			if g.player1 not in self.players:
				self.players[g.player1]=[]
			self.players[g.player1].append(g)
		else:
			print("empty replay",filename)
		return 	g
Exemple #28
0
def main():
    graphics = graph.init_video()
    graphics.screen.fill((32, 0, 64))
    pygame.mouse.set_visible(0)
    pygame.display.flip()
    level = game.load_level()
    mygame = game.init_game(level)
    graphics.tilemap = level.tilemap
    graphics.tilemap_height = level.height
    graphics.tilemap_width = level.width
    next = "title"
    mygame.ingame = 0
    while next != "quit":
        if next == "menu":
            next = menu.main_menu(mygame, level, graphics)
        if next == "edit":
            next = "menu"
            edit.edit(level, graphics)
        if next == "play":
            next = game.game(mygame, level, graphics)
        if next == "title":
            mygame.sound_12.play()
            next = menu.title_screen(graphics)
        if next == "intro":
            mygame.sound_12.play()
            next = menu.intro(graphics)
        if next == "win":
            mygame.sound_0.play()
            next = menu.win(graphics)
            
    graph.free_video()
Exemple #29
0
def main():
    pygame.init()
    size = (800,600)
        
    pygame.display.set_caption("Antarctic Algebra Proof of Concept")
    pygame.mouse.set_visible(False)
    
    screen = pygame.display.set_mode(size)
    clock = pygame.time.Clock()
    
    state = 0
    states = [Menu(screen).draw, game(screen).draw]

    running = True
    while running:
        milliseconds = clock.tick(60) # maximum number of frames per second
        
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
        pygame.display.flip()
        
        state = states[state](event) # sets the state of the game.
    pygame.quit()
Exemple #30
0
    def __init__(self):
        pygame.init()
        self.width = 1024
        self.height = 768
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.screen.blit(sprites("Sprites").load("Loading"), (0, 0))
        pygame.display.update()
        self.running = True

        self.AllSprites = sprites("Sprites")
        self.AllSprites.loadAll()

        self.clock = pygame.time.Clock()
        self.state = "Menu"
        self.sounds = soundManager("Sound")
        self.mainMenu = Main_Menu(self.screen, self.width, self.height, self.AllSprites, self.sounds)
        self.game = game(self.screen, self.width, self.height, self.AllSprites, self.sounds)
        
        self.lobby = None
        self.multiGame = None

        self.fontsize = 10
        self.font = pygame.font.Font(os.path.join('Fonts', 'nasalization-rg.ttf'), self.fontsize)

        pygame.event.set_blocked(pygame.NOEVENT)
Exemple #31
0
def main():
    """
    Main function, includes intro and user functionality, such as movement
    """
    this_game = game("test",new=False) # start game 
    textui = Textui()
    in_play = True
    maps = []
    moves = 0
    while in_play == True:
        moves += 1
        flt = random()
        if flt < 0.25:
            movement("w",textui,this_game)
        elif flt < 0.5:
            movement("a",textui,this_game)
        elif flt < 0.75:
            movement("s",textui,this_game)
        else:
            movement("d",textui,this_game)
        if this_game.user.current_location.map.key not in maps: # Adds all visited maps to maps list
            maps.append(this_game.user.current_location.map.key)
            diff = remaining_maps(maps)
            with open("maptest.txt", 'w') as f:
                f.write(f'# Maps Seen: {len(maps)} \n Maps seen: {maps} \n Maps Unseen: {diff} \n Moves: {moves}')
        if len(maps) == 29:
            print("All accessible - all maps reached") # once all have been visited quits program
            quit()
        

    win.mainloop()
def parseText(submittedText):
	lines = submittedText.split('\n')
	with lines as fp:
		line = fp.readline()
		cnt = 1
		while line:
			line = line.split('\t')
		homeTeam = line[4] == 'Highrock'
		otherTeam = (line[4], line[6])[homeTeam]
		subj = line[2]+(' vs ', ' at ')[homeTeam]+otherTeam
		subj = subj.strip()

		gameYear = datetime.now().year
		gameMonthNum = list(calendar.month_abbr).index(line[1].split('-')[1])
		gameDayNum = line[1].split('-')[0]
		formattedGameDate = str(gameMonthNum) + '/' + str(gameDayNum) + '/' + str(gameYear)
		gameTime = line[3]

		allGames.append(game.game(subj, formattedGameDate, gameTime, homeTeam))
		line = fp.readline()
		cnt += 1

	return lines

# f.write('SUBJECT, START DATE, START TIME, END DATE, END TIME, ALL DAY EVENT, DESCRIPTION, LOCATION, PRIVATE\n')

# for aGame in allGames:
# 	newRow = aGame.subject+','+ aGame.date + ',' + aGame.time + ','+ aGame.date +',' + aGame.time + ',FALSE'
# 	f.write(newRow)
# 	print(aGame.time)
Exemple #33
0
 def selfplay(self):
     gm = game()
     gm.newgame()
     player = NolosZeroPlayer()
     while True:
         gm.draw()
         p = player.play(gm=gm, silence=True)
         self.extenddata(player.root_node.parent, gm)
         gm.domove(p)
         if gm.isDraw():
             # self.savedata()
             gm.draw()
             self.extenddata2(False, None)
             if len(self.traindata) >= c.minbatch:
                 return self.traindata
             gm.newgame()
             continue
         winned, winner = gm.isWin(p)
         if winned:
             # self.savedata()
             gm.draw()
             self.extenddata2(winned, winner)
             if len(self.traindata) >= c.minbatch:
                 return self.traindata
             gm.newgame()
             continue
 def test_lost(self):
     g = game.game()
     # Change grid to make it lost
     g._game__grid = np.array([[1, 2, 3, 4], [4, 3, 2, 1], [1, 2, 3, 4],
                               [4, 3, 2, 1]])
     print(g._game__grid)
     self.assertTrue(g.lost())
Exemple #35
0
 def word_guess(self,i_word,i_indices,w_index):
     """
     method that executes when the user selects guess option and guesses the word
     :param i_word: the word to guess
     :param i_indices: the uncovered letters
     :param w_index: the index of the uncovered letters
     :return:
     """
     g_word = input("Enter the guess: ")
     if g_word.lower() == i_word:
         print("Correct Guess \n")
         l_score = guess.calc_score(self,i_word,i_indices)
         t_score = l_score[1]
         missed_letters = 4 - len(w_index)
         t_game = game(i_word, "success", guess.no_wrong_guess, missed_letters, t_score)
         guess.summary.append(t_game)
         guess.cl_att(self)
         guess.import_word(self)
         guess.no_game += 1
         if guess.no_game <= 100:
             guess.start_game(self)
         else:
             print("Game ended...")
             guess.print_summary(self,guess.summary)
     else:
         print("Wrong Guess... Try Again...\n")
         guess.no_wrong_guess +=1
         guess.start_game(self)
    def test_moove(self):
        random.seed(42)  # Fix seed
        g = game.game()

        # Control that mooves have correct actions
        # Up moove
        g.moove("up")  # Moove do nothing
        self.assertTrue(
            np.all(g.get_grid() == np.array([[0, 0, 0, 4], [0, 0, 0, 0],
                                             [0, 0, 0, 0], [0, 0, 0, 0]])))
        # Down moove
        g.moove("down")
        self.assertTrue(
            np.all(g.get_grid() == np.array([[0, 0, 0, 0], [4., 0, 0, 0],
                                             [0, 0, 0, 0], [0, 0, 0, 4.]])))
        # Left moove
        g.moove("left")
        self.assertTrue(
            np.all(g.get_grid() == np.array([[0, 0, 2, 0], [0, 0, 0, 4],
                                             [0, 0, 0, 0], [0, 0, 0, 4]])))
        # Right moove
        g.moove("right")
        self.assertTrue(
            np.all(g.get_grid() == np.array([[2, 0, 0, 0], [4, 0, 0, 0],
                                             [0, 0, 0, 0], [4, 2, 0, 0]])))

        # Up moove
        g.moove("up")
        self.assertTrue(
            np.all(g.get_grid() == np.array([[2, 2, 0, 0], [8, 0, 0, 0],
                                             [0, 0, 0, 4], [0, 0, 0, 0]])))
        # Should only accept up, down, right, left
        self.assertRaises(ValueError, g.moove, "cdy")
Exemple #37
0
 def quit(self,i_word,i_indices,w_index):
     """
     the user quits the game
     :param i_word: the word to guess
     :param i_indices: the index of the uncovered letters
     :param w_index: the uncovered letters
     :return:
     """
     quit_choice = input("Are you sure?\nEnter 'y' for 'yes' and 'n' for 'no': \n")
     if quit_choice.lower() != "y" and quit_choice.lower() != "n":
         print("\nWrong option... Enter 'y' or 'n'")
         guess.quit(self,i_word,i_indices,w_index)
     elif quit_choice.lower() == "y":
         if guess.no_wrong_guess > 0 or guess.no_letter_req > 0:
             print("Word is ", i_word, "\n")
             l_score = guess.calc_score(self, i_word, i_indices)
             g_score = l_score[0]
             t_score = 0
             t_score = t_score - g_score
             missed_letters = 4 - len(w_index)
             t_game = game(i_word, "gave up", guess.no_wrong_guess, missed_letters, t_score)
             guess.summary.append(t_game)
         print("Thanks for playing!!!")
         guess.print_summary(self,guess.summary)
     elif quit_choice.lower() == "n":
         print("Continue to play the game...")
         guess.start_game(self)
Exemple #38
0
 def tell(self,i_word,i_indices,w_index):
     """
     method that when the user gives up and the method displays the word
     :param i_word: the wor to guess
     :param i_indices: the index of the uncovered letters
     :param w_index: the uncovered letters
     :return:
     """
     print("Word is ", i_word,"\n")
     l_score = guess.calc_score(self, i_word, i_indices)
     g_score = l_score[0]
     t_score = 0
     t_score = t_score-g_score
     #print(t_score)
     missed_letters = 4 - len(w_index)
     t_game = game(i_word,"gave up",guess.no_wrong_guess,missed_letters,t_score)
     guess.summary.append(t_game)
     guess.cl_att(self)
     guess.import_word(self)
     guess.no_game += 1
     if guess.no_game <= 100:
         guess.start_game(self)
     else:
         print("Game ended")
         guess.print_summary(self,guess.summary)
Exemple #39
0
    def start(self, numRounds=1):
        try:
            self.setRobotMode(1, runState.home)
            self.setRobotMode(2, runState.home)
            sleep(5)
            self.setRobotMode(1, runState.hold)
            self.setRobotMode(2, runState.hold)
            while self.plc.getMem('IX8.0') == True or self.plc.getMem('IX8.1') == True:
                sleep(0.5)

            keepGoing = True
            for i in range(numRounds):
                print("Game {0} of {1}".format(i+1, numRounds))
                self.currentGame = game(self.Player1, self.Player2)
                while keepGoing:
                    currentId = self.currentGame.currentPlayer.id
                    if self.currentGame.currentPlayer.type == playerType.robot:
                        if self.currentGame.remaining == game.boardHeight * game.boardWidth:
                            movePos = random.randint(0,3)
                        else:
                            movePos = self.currentGame.findBestMove().col
                        print("Player",currentId, "moves to", self.gamePositions[movePos])
                        movePos += 4
                    elif self.currentGame.currentPlayer.type == playerType.human:
                        print("Player",currentId," - Enter a move: ")
                        movePos = self.readInput()

                    if movePos >= 4:
                        self.setRobotMode(currentId, movePos)
                        sleep(1)
                        matchFound = self.currentGame.move(self.currentGame
                        .currentPlayer, movePos)
                    
                        self.currentGame.showGrid()
                        self.setRobotMode(currentId, runState.hold)
                        if currentId == 1:
                            while self.plc.getMem('IX8.0') == True:
                                sleep(0.5)
                        elif currentId == 2:
                            while self.plc.getMem('IX8.1') == True:
                                sleep(0.5)
                        print(matchFound)
                        if (matchFound == True):
                            print("Player", currentId, "Wins!")
                            keepGoing = False
                        elif self.currentGame.remaining == 0:
                            keepGoing = False
                print("Game Over!")
                sleep(10)
                self.cleanUp()

        except Exception as ex:
            print("An error occured during runtine: ", ex)

        finally:
            if self.plc.plc.get_connected:
                self.stopBelt()
                self.setRobotMode(1, runState.hold)
                self.setRobotMode(2, runState.hold)
                self.plc.plc.disconnect()
Exemple #40
0
    def __init__(self, init_model=None):
        self.board = board()
        self.game = game(self.board)
        # Training parameter
        self.learn_rate = 2e-3
        self.lr_multiplier = 1.0
        self.temp = 1.0
        self.n_playout = 400
        self.c_puct = 5
        self.buffer_size = 10000
        self.batch_size = 512
        self.data_buffer = deque(maxlen=self.buffer_size)
        self.play_batch_size = 1
        self.epochs = 5
        self.kl_targ = 0.02
        self.check_freq = 50
        self.game_batch_num = 1500
        self.best_win_ratio = 0.0

        # num of simulations used for pure mcts
        self.pure_mcts_playout_num = 1000
        if init_model:
            # start from an existing policy value net
            self.policy_value_net = PolicyValueNet(model_file=init_model)
        else:
            self.policy_value_net = PolicyValueNet()
Exemple #41
0
def making_games():
    # creating games between players
    global find_players
    
    while True:
        if len(find_players) < 2:
            continue
        
        player1 = find_players.popleft()
        player2 = find_players.popleft()    
        
        make_log(player1, player2)
        threading.Thread(target=game(player1, player2).start).start()
 def keep_score(self,playerOneName,playerTwoName,playerOne,playerTwo):
     playerOneWins = []
     playerTwoWins = []
         
     while len(playerOneWins) < 3 and len(playerTwoWins) < 3:
         thegame = game.game()
         gameWinner = thegame.get_result(playerOneName,playerTwoName,playerOne,playerTwo)
         if gameWinner == playerOneName:
             playerOneWins.append(playerOneName)
         elif gameWinner == playerTwoName:
             playerTwoWins.append(playerTwoName)
     if len(playerOneWins) == 3:
         print(playerOneName + " wins the match! \n")
         input("Press enter to exit.")
         
     elif len(playerTwoWins) == 3:
         print(playerTwoName + " wins the match! \n")
         input("Press enter to exit.")
    def __init__(self):
        sdl2hl.init()
        sdl2hl.mixer.init(sdl2hl.mixer.AudioInitFlag.ogg)
        sdl2hl.mixer.open_audio()
        sdl2hl.ttf.init()

        self.window_size = (1920, 1080)

        self.window = sdl2hl.Window(title="Winter Wizard Jam", w=self.window_size[0], h=self.window_size[1])
        # self.renderer = sdl2hl.Renderer(self.window,-1, sdl2hl.RendererFlags.presentvsync)
        self.renderer = sdl2hl.Renderer(self.window)

        self.game = game.game(self.renderer, self.window_size)
        self.title = title.Title(self.renderer, self.window_size)
        self.end = end.End(self.renderer, self.window_size)

        self.best_run_time = 0
        self.best_run_ghost_data = []
        self.best_run_set = False
Exemple #44
0
# -*- coding: utf-8 -*-
import sys
from game import game

if __name__ == "__main__":
    G=game()
    G.importfile('mat1.txt')

    print("Strongly connected components :")
    
    strongcomp = G.levels()
        
    print(strongcomp)
    
    print("Reduced matrix :")
    
    reduced = G.reducedgraph()

    for line in reduced.generatematrix():
        print(line)
    
    print("Longest path :")
    
    '''startnode = int(input("Enter the starting node : "))
    endnode = int(input("Enter the ending node : "))'''

    startnode = 1
    endnode = 8
    
    i=1
    
Exemple #45
0
    def set_normal_term(self):
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)


    def getch(self):
            return sys.stdin.read(1)
                        
    def kbhit(self):
   
            dr,dw,de = select([sys.stdin], [], [], 0)
            return dr != []


 
if __name__=="__main__" :
    game1=game.game()
    kb=take_input()
    player1=person.player(1,77)
    donkey=person.donkey(25,75)
    fireballs=game.fireball()
    princess=person.princess(28,60)
    game1.setboard(player1,donkey,princess)
    game1.printboard(player1)
    while True:
        if kb.kbhit(): 
                x = kb.getch()
                game1.resetperson(player1)
                if ord(x)==100:
                    player1.moveright_player(game1)
                    player1.previous=1
Exemple #46
0
#===============================================================================
# Playing the Outer-State Strategy
#===============================================================================
if __name__ == '__main__':
	
	temp_weights = np.empty([ACTION_NUM, NUM_COLORS * NUM_VALUES * NUM_HAND * NUM_PLAYERS + 7])
	temp_weights.fill(0.01)
	# temp_weights[(NUM_HAND*2):, :] = 0.2 # higher weights for hinting

	game_score = []
	hints = []

	for k in range(1000): 
		if (k % 100) = 0: 
			print("GAME: ", k)
		g = game()
		g.weights = temp_weights

		count = 0
		
		while True: 

			# each player makes moves
			for i in range(NUM_PLAYERS): 

				score_old = g.score()
				state_old = g.players[i].new_state

				# (1) IF THERE IS PLAYABLE CARD, PLAY IT 
				# list of playable cards 
				playable = check_playable(g.hands[i], g.played)
Exemple #47
0
import game

g = game.game()
g.loop()
Exemple #48
0
def intro():
	text.text(10,10, ["Greetings stalactites.  Frogs have inhabited the",
		"bottom of our dreary cave, and it is our goal to keep them",
		"alive until they can produce offspring capable of living",
		"here under their own powers.",
		"",
		"Until then, release the water from yourselves onto the frogs so",
		"that their skin does not dry out.",
		"Best of luck to us all.",
		"",
		"",
		"(Press 'Space' to proceed)"])
	
	startgame(0)  #number for possible future additions of difficulty level

rungame = game.game()
numfrogs = 0
	
def startgame(difficulty):
	global rungame
	
	numstalac = 5	#numstalac not presently used
	
	if difficulty == 0:		#current all-encompasing difficulty: ie. random.
		MINFROGS = 3
		MAXFROGS = 7
		numfrogs = ika.Random(MINFROGS, MAXFROGS)
			
		game.generatefrogs(numfrogs)
		game.generatestalactites(numstalac)
def runClient():
    foo = game.game(sys.argv[1], 5555, 60,False,False)
Exemple #50
0
def randompuzzle(solved, screen, end): # Remove allpuz, menubg, text, end ## MAY CHANGE ##
    puzzlenum = randint(1, end)
    solved = game.game(puzzlenum, screen, solved)
    return True
Exemple #51
0
#!/usr/bin/python2
#

import os, sys
import pygame
from game import game
import player

already_run = False

while True:
    the_game = game()
    the_game.run(already_run)
    already_run = True
Exemple #52
0
__author__ = 'mohammed'
import pygame

import game
import button

pygame.init()
size = width, height = 888, 660 #screen size
screen = pygame.display.set_mode(size) #sets the screen size
menu = pygame.image.load("menuart.png").convert() #gets menu code and converts into optimised format
logo = pygame.image.load("logo.png").convert() #same for logo
logo.set_colorkey(button.BLACK)
while 1:
    mouse = pygame.mouse.get_pos() #gets mouse position for mouseover
    btn = button.Button("Testing sizes", 393.5, 450,100,50) #creates button with text
    for event in pygame.event.get(): #checks for special events such as quit and click
        if event.type == pygame.QUIT: pygame.quit() #if quit event, quit pygame
        elif event.type == pygame.MOUSEBUTTONDOWN: #checks if mouse is clicked
            if btn.rect.collidepoint(mouse): #checks if mouse is over the button
                print("button one clicked")
                game.game()
    screen.blit(menu, [0,0]) #draws menu on screen
    screen.blit(logo, [133.5,56.5]) #draws logo on screen
    btn.draw(mouse, screen) #draws button on screen
    pygame.display.flip() #updates screen
Exemple #53
0
from math import exp, log
from game import game
import copy
import random

game = game('input.txt')

iter = 100000  # number of iterations allowed
T = 1.0  # initial temperature
dec_cnt = 1 # decrease temperature every dec.cnt iterations
alpha = exp(log(1 / T) / (iter * 1.0 / dec_cnt))
d = 4
best = None
bestFit = 10000

for i in range(1, iter):
    if i % dec_cnt == 0:
        T = d / log(i + 1)   #1.0 / pow(i, log(2.5) / log(i + 1))
    newGame = copy.deepcopy(game)
    newGame.mutate()
    newfit = newGame.fitness()

    delta = newfit - game.fitness()

    if random.random() < exp(-delta / T):
        game = newGame

    if newfit < bestFit:
        bestFit = newfit
        best = newGame
Exemple #54
0
def game():
    game = gm.game([gm.player('player1'), gm.player('player2')], 6)
    return game
Exemple #55
0
def main():
    gra = game(640,480)
    gra.play()
from game import game
from player import player

#win_count is organized alphabetically
win_count = [0, 0, 0]

Bruce = player("Bruce", 47, 25, 25, 3, 80, 45, 75)
Jean = player("Jean", 70, 10, 15, 5, 90, 25, 85)
Serena = player("Serena", 10, 20, 66, 4, 65, 50, 85)

game_one = game(Serena, Jean)
game_two = game(Serena, Bruce)
game_three = game(Bruce, Jean)

#each player will play the other two players GAMES number of times
GAMES = 50

for x in range(0, GAMES):
	winner1 = game_one.play()
	winner2 = game_two.play()
	winner3 = game_three.play()

	if winner1 == "Bruce" : 
		win_count[0] += 1
	elif winner1 == "Jean" :
		win_count[1] += 1
	else:
		win_count[2] += 1

	if winner2 == "Bruce" : 
		win_count[0] += 1
    '''
    options = [str(x) + ". " + commands[x][0] for x in range(0, len(commands))]
    print '\n'.join(options)  
    
def exit_loop():
    '''    
    Exits the while loop by calling system's exit function
    '''
    print "Thank you for playing!"
    os._exit(1)    

if __name__ == '__main__':
    
    print "Welcome to Michael Li's game of Rock-Paper-Scissors - where everything's made up and the points don't matter!"
    name = raw_input("What is your name? ")
    game = game(name)
    
    commands = [["Start a new game.", game.start_new_game],
            ["Start a new round.", game.start_round],
            ["Print the current score.", game.print_scores],
            ["Print your win ratio.", game.print_ratio],
            ["Print the number of rounds that have been played.", game.print_rounds],
            ["Exit.", exit_loop]
            ]
    while (1):
        print_options()
        user_query = raw_input("What would you like to do? ")
        try:
            user_query = int(user_query)
            commands[user_query][1]()
        except:
Exemple #58
0
from game import game
  
# === Run === #

game()  #starts the game
Exemple #59
0
# implements q-learning
if __name__ == '__main__':

	temp_weights = np.empty([ACTION_NUM, NUM_COLORS * NUM_VALUES * NUM_HAND * NUM_PLAYERS + 7])
	temp_weights.fill(0.1)
	temp_weights[(NUM_HAND*2):, :] = 0.2 # higher weights for hinting


	scores = []
	
	f = open('output_notnorm.txt', 'w')
	for k in range(1000000): 
		# f = open('output' + str(i) + '.txt', 'w')
		
		g = game()
		g.weights = temp_weights
		# print(g.weights)

		count = 0
		hints = []

		# print("GAME: ", k)
		if (k % 1000) == 0: 
			print("GAME: ", k)

		while True: 
			count += 1
			# print("ITERATION " + str(count))
			# f.write("ITERATION " + str(count) + "\n")
Exemple #60
0
        number = int(userInput[3])
        
        if userInput[2] == commands[0]:
            if isinstance(number,int):
                self.game.players[player].playCard(number)
                printCards(myGame.players[player].getHand())
                self.setup()
                
        elif userInput[2] == commands[1]:
            printCards(self.game.players[player].getHand())
            self.setup()
            
        elif userInput[2] == commands[2]:
            if isinstance(number,int):
                self.game.players[player].drawCard(number)
        else:
            print ("Not valid command!")
            self.setup()
        

myGame = game(4)
print ("Current Player: "+str(myGame.getCurrentPlayer()))
print ("------------------------------")
print ("Current Play Card: ")
printCards(myGame.getCurrentCard())
print ("------------------------------")
print ("Player 0's hand: ")
printCards(myGame.players[0].getHand())

commandHandler(myGame)