def start_onmouseclick(self, event): self.start.onmouseclick(event) self.on_exit() game = Game() game.run() self.start.onmouseclickup(event) self.on_enter()
def main(): #theres a better way to do this, but this is faster fn = sys.argv[2] if (len(sys.argv) == 3 and sys.argv[1] == '-c') else 'default.cfg' g.init(fn) # read in the input file to the project's globals game = Game() # create the initial game board log = open(g.logfile, 'w') prepare_log(log) best_soln = [(None, -maxint, -maxint, -maxint)] for n in range(g.runs): print 'Starting run #' + str(n+1) + '\n' log.write('Run ' + str(n+1) + '\n') result = evolution(game, log) best_soln = determine_dominance(best_soln, result) if n < g.runs-1 and not g.datafile: create_soln_file(best_soln) g.seed = randint(0, maxint) game.rand = Random(g.seed) game.new_random_board() log.close() print 'finished calculations' create_soln_file(best_soln)
def main(): parser = argparse.ArgumentParser(description='Start the server') parser.add_argument('--p', help='Port number', type=int, default=8080) parser.add_argument('--min', help='Minimal player to start the game', type=int, default=2) parser.add_argument('--max', help='Maximal player to start a game', type=int, default=10) parser.add_argument('--lobby', help='Time to count down in the lobby in second)', type=int, default=2) parser.add_argument('--t', help='Time to wait until kick someone in second', type=int, default=30) parser.add_argument('--d', help='Debug flag', type=int, default=1) args = parser.parse_args(sys.argv[1:]) com = Com(args.p, args.d) game = Game(com, args.min, args.max, args.lobby, args.t, args.d) com.start_server() game.setup_new_game() while com.check_signal(): game.check_time()
class MainWindow(Frame): def __init__(self, master, rows, columns): Frame.__init__(self, master) self.matrix = Matrix(master, rows, columns) self.matrix.grid(row=0, column=0) self.game = Game(rows, columns) self.game.set_matrix(self.matrix) self.start_button = Button(master, text="Start") self.start_button.grid(row=1, column=0) self.start_button["command"] = self.game.start_clicked self.quit_button = Button(master, text="Quit") self.quit_button.grid(row=1, column=1) self.quit_button["command"] = self.quit self.master = master master.title("Life") # override the "X" close button self.master.protocol("WM_DELETE_WINDOW", self.quit) def quit(self): print "quitting" self.game.quit_clicked() self.master.quit()
def eval_func(chromosome): player = Player(chromosome) game = Game([player] + player_list, verbose=False, quiet=True) # Start the game in quiet mode. ranking = game.play_game() score = ranking.index('GA Player') return score * score
def getGames(self): data = self.loadData(); games = [] for row in data: items = row.split(',') gamedate = items[0] awayTeamStr = self.getTeam(items[1]) if (len(items[2]) > 0): awayTeamScore = items[2] else: awayTeamScore = 0 homeTeamStr = self.getTeam(items[3]) if (len(items[4]) > 0): homeTeamScore = items[4] else: homeTeamScore = 0 g = Game(gamedate, awayTeamStr, awayTeamScore, homeTeamStr, homeTeamScore) if (gamedate < str(date.today()) and not g.wasPlayed()): # if here, means game was postponed or cancelled. it screws up the upcoming games # if one of the teams in the postponed games was involved pass else: games.append(g) return games
def main(): """hack""" parser = SafeConfigParser() parser.read('config.ini') shots = parser.getint('shots', 'number_of_tryes') current_word = Word() category = current_word.random_category() user = Player() player = user.ask_for_name() con = mdb.connect('localhost', 'testuser', '1', 'hangman'); cur = con.cursor() with con: cur.execute("INSERT INTO player(player_name) VALUES('%s');" % (player)) file_name = "%s.log" % player logging.basicConfig(filename=file_name, level=logging.DEBUG, format='%(message)s') logging.info("USER:%s start the game and has %s wrong turns", player, shots ) logging.info("###### [word]:[hidden]:[guess]:[wrong_guess]:[right_guess]") word = current_word.random_word() with con: cur.execute("insert into game(currentWord) values('%s');" %(word)) print word play_fun = Game(word,player) play_fun.play()
def game_looper(level): game = Game(level) result = 0 while not result == -5: result = game.run() again = 'n' if result == -1: print 'You were crushed' again = raw_input('Try again? (Y/N): ') elif result == -2: print 'You fell to your death' again = raw_input('Try again? (Y/N): ') else: print 'You escaped that room!' again = result if again: if again[0] == 'N' or again[0] == 'n': break elif again[0] == 'Y' or again[0] == 'y': game = Game(level) elif result != -1 and result !=-2: game = Game(again) else: break else: break
def __init__( self, pos ): super( TinyWorld, self ).__init__( pos, "sprites/worlds/"+str(Game.level)+"/tiny-1.png", 9 ) Game.addSprite( "tiny-worlds", self ) self.addAnimState( "panic", 0, 3, 12 ) self.setAnimState( "panic" )
def test_make_move_in_occupied_square(self): """ Trying to place a piece in an occupied square should throw a runtime exception. """ game = Game(Player, Player) game.make_move(game.player1, 5) self.assertRaises(RuntimeError, game.make_move, game.player1, 5)
def test_calculates_for_strike(self): game = Game() game.roll(10) game.roll(5) game.roll(4) self.assertEqual(28, game.score)
def test_calculates_for_spare(self): game = Game() game.roll(5) game.roll(5) game.roll(3) self.assertEqual(16, game.score)
def test_calculates_score_no_spare_no_strike(self): game = Game() noOfStruckPins = 5 game.roll(noOfStruckPins) self.assertEqual(game.score, noOfStruckPins)
def interactive(ply): g = Game() mode, end = g.game_type() end = int(end) if mode: # mode is true means new game player_x = Player("x") player_y = Player("y") b = Board(player_x, player_y) ai = Ai(ply) remain = ["PlayerX King", "PlayerX Rook", "PlayerY King"] g.ask_piece(b, player_x, player_y, remain) b.display() File.prompt("Who am I, PlayerX or PlayerY?") localPlayer = input("Player [x/y]: ") if re.match(r"[Xx]", localPlayer): localPlayer = "x" else: localPlayer = "y" # if local player is playerX, PlayerX is our ai moves # PlayerY is opponents moves inputted by us if localPlayer == "x": for i in range(0, end): # b.ai_move(player_x) ai.move(b, player_x) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states) ai.opponent_move(player_y, b) b.display() else: for i in range(0, end): ai.opponent_move(player_x, b) b.display() # b.ai_move(player_y) ai.move(b, player_y) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states) else: player_x = Player("x") player_y = Player("y") b = Board(player_x, player_y) File.test_file(b, g, player_x, player_y) ai = Ai(ply) # AI random moves test: for i in range(0, end): ai.move(b, player_x) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states) ai.move(b, player_y) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states)
def test_make_move_in_empty_square(self): """ Making a move should set that square in the board to the specified player's piece. """ game = Game(Player, Player) self.assertEqual(None, game.board.get_square(5)) game.make_move(game.player1, 5) self.assertEqual(game.player1.piece, game.board.get_square(5))
def new(ctx): g = load_game(ctx.message.server) if g is None: g = Game([], []) g.channel = ctx.message.channel save_game(g, ctx.message.server) yield from bot.say("New game created") else: yield from bot.say("Game already running")
def test_get_by_piece(self): """ Calling this function with a player's piece should return the player object with that piece. The first player's piece should be an 'X' and the second player's piece should be an 'O'. """ game = Game(Player, Player) p1 = game.player1 p2 = game.player2 self.assertEqual(p1, game.get_by_piece('X')) self.assertEqual(p2, game.get_by_piece('O'))
def main(argv): # logging.basicConfig(level=logging.INFO) # logger = logging.getLogger(__name__) myGame = Game() while not myGame.isGameOver(): myGame.onTurn()
def assertScoreForRolls(self, rolls, expectedScore, msg = None): theGame = Game() for roll in rolls: theGame.roll(roll) theActualScore = theGame.score() if theActualScore != expectedScore: print 'expected score: %d, but got score: %d' % ( expectedScore, theActualScore )
def test(): abilities = [AbilitiesAbility(), TruthtellAbility(), SaveAbility(), KillAbility(), CoerceAbility(), StealAbility()] abilityNames = map(lambda a: a.getName(), abilities) samira = Player("Samira", "*****@*****.**", Character("Char",[], abilityNames, "desc")) will = Player("Will", "*****@*****.**", Character("Char",[], abilityNames, "desc")) players = [None, will] game = Game(abilities, players) game.run()
def _get_e_greedy_action(self, state, exploration=None): actions = self.get_action_values(state) if exploration is None or (exploration is not None and random.uniform(0, 1) > exploration): max_val = max(actions) action = np.where(actions == max_val)[0] game = Game(game_board=translate_state_to_game_board(state), spawning=False) if set(action) == set(game.get_illegal_actions()): return [random.choice(game.get_legal_actions())] return [random.choice(action)] else: return [random.choice(self.actions)]
def __init__(self,a,b,match_in_a_row=4): # Agent a ,Agent b Game.__init__(self,a,b,match_in_a_row) self.a.setRole(0) # The first argument/agent is always assigned O (0) self.b.setRole(1) # The second argument/agent is always assigned X (1) """ NOtice that, here first dows not mean that afent a will make the first move of the game. Here, first means the first argument of the constructor Which of a and b will actually give the first move is chosen randomly. See Game class """ self.name = "Four In A Row"
def playGame(size, difficulty, placeObstacles): """Initialize and play the game Snake""" if size == 0: height, width = 20, 20 elif size == 1: height, width = 30, 30 elif size == 2: height, width = 40, 40 if difficulty == 0: speed = 0.075 elif difficulty == 1: speed = 0.05 elif difficulty == 2: speed = 0.025 game = Game(height, width, speed, placeObstacles) game.play()
class Test(unittest.TestCase): def setUp(self): self.game = Game() def testAddingPlayer(self): self.assertEqual(self.game.playerCount(), 0, "no player at start") self.game.addPlayer(Player("Red", Strategy())) self.assertEqual(self.game.playerCount(), 1, "one player added") def testGameFinished(self): self.assertFalse(self.game.finished(), "game should not be finished at start")
def _get_actions(self, state): if self.exploration is not None and random.uniform(0, 1) < self.exploration: model = Game(game_board=translate_state_to_game_board(state), spawning=False) return [random.choice(model.get_legal_actions())] action = self._get_lookahead_actions(state) if action is None: print("LookAhead Failed") model = Game(game_board=translate_state_to_game_board(state), spawning=False) action = [random.choice(model.get_legal_actions())] return action
def main(self): obj = GameOp() obj.readFile() i = 0 while i < obj.data.__sizeof__(): print("Welcome to hangMan Game :D \n1 - Play\n2 - Quit\n") playOption = raw_input("What to do ?") if (playOption == "p"): print("Now we working with Movies names : ") stop = 0 testCase = Game() testCase.set_originalWord( str(obj.data[i]) ) testCase.set_playWord( obj.stringHiding(testCase.originalWord)) testCase.allUp() print(testCase.get_PlayWord()) while True: if (stop == -3 or stop == -10): break else: char_test = raw_input("What is your Guess char : ") stop = obj.game(char_test , testCase) print "\n" if(stop == -3): i += 1 print "Excellent you are in Level : " + str(i) + " Keep Working after lvl 300 you get cup of milk tea :D " print "\n\n\n\n\n\n" else: print "Okay Bye :D " break
def __init__( self, pos, target ): pos[0] -= 0 pos[1] -= 16 super( PaintSplat, self ).__init__( pos, "sprites/player/paint-splat-"+str(random.randint(1,6))+".png", 8 ) Game.addSprite( "player-paint", self ) self.addAnimState( "move", 0, 0, 1 ) self.addAnimState( "splat-idle", 1, 1, 1 ) self.addAnimState( "splat-drip", 2, 10, 4 ) self.setAnimState( "move" ) self.target = [target[0] - 24, target[1] - 24]
def _play_6_game_Types(self,player_1_type,player_2_type): players = [Player(player_1_type,player_number=0),Player(player_2_type,player_number=1)] game = Game(players) game_results = [] game_results.append(game.playGame(game_type=0)) game_results.append(game.playGame(game_type=1)) game_results.append(game.playGame(game_type=2)) # Repeat the beta game for better statistical accuracy for _ in range(0,30): game_results.append(game.playGame(game_type=3)) game_results.append(game.playGame(game_type=4)) game_results.append(game.playGame(game_type=5)) self._add_data_to_csv(game_results,game)
def testPlayGameWithComputer(self): print "testPlayGameWithComputer" #with mock.patch('Game.Computer.generatePosibleNumber', return_value='1234') game = Game() game.computer.generatePosibleNumber = mock.MagicMock(return_value='1234') with mock.patch('__builtin__.raw_input', return_value='1234'): game_end = game.playHuman() self.assertTrue(game_end) game = Game() game.computer.generatePosibleNumber = mock.MagicMock(return_value='1234') with mock.patch('__builtin__.raw_input', return_value='4321'): game_end = game.playHuman() self.assertFalse(game_end)
def main(): # Instiantiate the Game, Player, and AI objects. game = Game(3) player = Player() ai = AI() # Prompt the user for who goes first. first = player.prompt_start() # Run the game loop. game.loop( first=first, player=player, ai=ai, )
parser.add_argument('exe', metavar='run.sh', type=str, help='Your executable') parser.add_argument('-n', dest='n', metavar='N', type=int, default=5, help='Tak board size') parser.add_argument('-mode', dest='mode', type=str, default='GUI', help='How to render') parser.add_argument('-val', dest='val', type=str, default='0', help='value to pass') args = parser.parse_args() game = Game(args.n, args.mode) if args.mode != 'GUI': game_loop(game, args) else: from threading import Thread Th = Thread(target=lambda: game_loop(game, args)) Th.start() game.init_display() game.display.mainloop()
def testGetMap(self): game = Game(1, 13) self.assertEqual(game.getMap(), ['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'])
def testGetAvalMaps(self): game = Game(1, 13) self.assertEqual(game.getAvalMaps(), [1, 2])
class Test_Game(unittest.TestCase): def setUp(self): self.g = Game() def roll_many(self, n, pins): for i in range(n): self.g.roll(pins) def roll_many_spares(self, n, ball_one, ball_two): for i in range(n): self.g.roll(ball_one) self.g.roll(ball_two) def test_gutter_game(self): self.roll_many(20, 0) self.assertEqual(0, self.g.get_score()) def test_all_one(self): self.roll_many(20, 1) self.assertEqual(20, self.g.get_score()) def test_one_spare(self): self.roll_spare() self.g.roll(3) self.roll_many(17,0) self.assertEqual(16, self.g.get_score()) def roll_spare(self): self.g.roll(5) self.g.roll(5) def roll_strike(self): self.g.roll(10) def test_one_strike(self): self.roll_strike() self.g.roll(3) self.g.roll(4) self.roll_many(16, 0) self.assertEqual(24, self.g.get_score()) def test_perfect_game(self): self.roll_many(12, 10) self.assertEqual(300, self.g.get_score()) def test_highest_spare(self): self.roll_many_spares(10, 9, 1) self.g.roll(9) self.assertEqual(190, self.g.get_score()) def get_many_user_rolls(self, num): for i in range(num): self.g.get_user_roll() @patch("builtins.input") def test_current_score(self, pinput): # arrange pinput.side_effect = ["1", "1", "1", "1"] expected = [2, 2] exp_total = 4 # act self.get_many_user_rolls(4) actual = self.g.get_current_score() act_total = self.g.total # [2, 2] Total: 4 # assert self.assertEqual(expected, actual) self.assertEqual(exp_total, act_total) @patch("builtins.input") def test_current_score_spares(self, pinput): # arrange pinput.side_effect = ["9", "1", "9", "1", "9", "1", "9", "1", "9", "1", "9", "1", "9", "1", "9", "1", "9", "1", "9", "1", "9"] expected = [19, 19, 19, 19, 19, 19, 19, 19, 19, "/"] exp_total = 171 # act self.get_many_user_rolls(20) actual = self.g.get_current_score() act_total = self.g.total # [2, 2] Total: 4 # assert self.assertEqual(expected, actual) self.assertEqual(exp_total, act_total)
def testGetMapSize(self): game = Game(1, 13) self.assertEqual(game.getMapSize(), 4)
from Game import Game from Player import Player from Strategies import * from GeneticMinMax import * player1 = Player(MinMaxLvl1(depth=5, show_values=False)) player2 = Player(MinMaxLvl0(depth=5, show_values=False)) game = Game(player1, player2) games = 100 for _ in range(games): game.full_game(log=False) game.reset() game.switch_players() player1.print_score() player2.print_score() print('Player 1:', player1.score, '/ Player 2:', player2.score)
def settings(window): pass def draw_state(): pass if __name__ == '__main__': _map = ''' #### #### ## # $ # # *** # # . . ## ## * * # ##*** # # $ ### # @ # ##### ''' state = [list(i) for i in _map.split('\n')[1:-1]] app = QApplication([]) win = Window(Ui_MainWindow, Game(state)) win.show() sys.exit(app.exec())
def move(self): g = Game(self.x) return g.logic()
def evaluation(self): if self.agent_depth >= self.max_depth or Game.is_end(self.grid): score = 0 for i in range(4): for j in range(4): score += self.grid[i][j] * self.weight[i][j] if Game.is_end(self.grid): if score >= self.t: scn = 0 else: scn = "infinite" else: if score >= self.t: scn = 0 else: scn = 1 return score, scn if self.node_type == "Max": max_score = -1 operator = { "w": Game.up, "a": Game.left, "s": Game.down, "d": Game.right } possible_action = [] a = -1 for op in ["w", "a", "s", "d"]: new_grid = operator[op](self.grid)[0] if new_grid != self.grid: possible_action.append((new_grid, op)) scn = "infinite" for g in possible_action: child_node = Node(g[0], self.agent_depth, self.max_depth, "Min", t=self.t) child_score, scn_c = child_node.evaluation() if child_score > max_score: max_score = child_score a = g[1] if scn_c == "infinite": pass elif scn == "infinite": scn = scn_c elif scn_c < scn: scn = scn_c if self.agent_depth == 0: return a, scn else: return max_score, scn elif self.node_type == "Min": min_score = int(pow(2, 50)) possible_position = [] for x in range(4): for y in range(4): if self.grid[x][y] == 0: possible_position.append((self.weight[x][y], (x, y))) possible_position = sorted(possible_position, reverse=True) tiles = min(self.max_depth - self.agent_depth, len(possible_position)) scn = 0 for i in range(tiles): new_grid = deepcopy(self.grid) new_position = possible_position[i][1] child_node = Node(new_grid, self.agent_depth, self.max_depth, "Chance", new_position, t=self.t) child_score, scn_c = child_node.evaluation() if child_score < min_score: min_score = child_score if scn == "infinite": pass elif scn_c == "infinite": scn = "infinite" else: scn += scn_c return min_score, scn else: average_score = 0 # probability of the new number 2 and 4 p = [0.8, 0.2] scn = 0 for i in range(2): new_grid = deepcopy(self.grid) new_grid[self.position[0]][self.position[1]] = int( pow(2, i + 1)) child_node = Node(new_grid, self.agent_depth + 1, self.max_depth, "Max", t=self.t) child_score, scn_c = child_node.evaluation() average_score += int(p[i] * child_score) if scn == "infinite": pass elif scn_c == "infinite": scn = "infinite" else: scn += scn_c return average_score, scn
cooperation_rate = {} for key1 in nets: cooperation_rate[key1] = {} for key2 in rules: cooperation_rate[key1][key2] = {} for gtype in gtypes: cooperation_rate[key1][key2][gtype] = np.zeros( epoch, dtype=np.float32) return cooperation_rate cooperation_rate = create_result_set(nets, rules, gtypes, epoch) for net in nets: EpochResults = [] for rule in rules: for gtype in gtypes: for r in range(run): DGame = Game(number, rule, fractionC, fractionM, net, gtype) DCRate = DGame.play(rule, rounds, r, 'Epoch') # a set: the number of 'run' cooperation_rate[net][rule][gtype] += DCRate cooperation_rate[net][rule][gtype] = np.around( cooperation_rate[net][rule][gtype] / run, 2) data = cooperation_rate EpochResults.append(data[net][rule][gtype]) np.savetxt('traditional_schemes_' + net + '.csv', np.array(EpochResults), fmt='%.2f')
def main(): game = Game(board_size=5)
from flask import Flask, request, session, jsonify from flask_session import Session import json import tradeGame from Game import Game import hashlib, binascii, os from random import randint app = Flask(__name__) SESSION_TYPE = 'redis' SECRET_KEY = 'secretkey' app.config.from_object(__name__) app.secret_key = 'SecretKey' sess = Session() game = Game() def hash_password(password): """Hash a password for storing.""" salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii') pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000) pwdhash = binascii.hexlify(pwdhash) return (salt + pwdhash).decode('ascii') def verify_password(stored_password, provided_password): """Verify a stored password against one provided by user""" salt = stored_password[:64] stored_password = stored_password[64:] pwdhash = hashlib.pbkdf2_hmac('sha512', provided_password.encode('utf-8'),
def main(): # Hand Model Training # game = Game() # model = BasicModel(3, 128, 52) # model.build() # model.printModel() # print("Playing Rounds") # inp, out = game.playRounds(50000) # print("Training") # model.model.fit(inp, out, validation_split=0.2, steps_per_epoch=64, epochs=16, validation_steps=64) # model.model.save_weights('poker.h5') # #model.model.load_weights('poker.h5') # #pair # hand = np.zeros(52) # hand[10] = 1 # hand[23] = 1 # hand[11] = 1 # hand[24] = 1 # hand[5] = 1 # print(model.predict(hand)) # Discard Model Training # game = Game() # model = DiscardModel(2,256,52) # model.build() # model.printModel() # print("Playing Rounds") # # inp, out = game.playDiscards(10000) # # np.save('out.npy', out) # # np.save('inp.npy', inp) # inp = np.load('inp_10k.npy') # out = np.load('out_10k.npy') # model.model.fit(inp, out, validation_split=0.1, steps_per_epoch=64, epochs=8, validation_steps=64) # #[0., 0., 0., 1., 0.] # print(model.predict(np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, # 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, # 0, 0, 0, 0, 0, 0, 0, 0]))) # #[1., 0., 1., 1., 1.] # print(model.predict(np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, # 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, # 0, 0, 0, 0, 0, 0, 0, 0]))) # model.model.save_weights('discard.h5') # game = Game() # model = DiscardModel(2,256,52) # model.build() # model.model.load_weights('discard_rough.h5') # for x in range(5): # h = Hand() # d = Deck() # h.fill(d) # print(h) # print(model.predict(h.getHandVector())) # game.playDiscardAgainstRandom(model, 1000) game = Game() model = DiscardModel(2, 256, 52) model.build() model.printModel() inp, out = game.playRoughDiscards(100000) model.model.fit(inp, out, validation_split=0.1, steps_per_epoch=64, epochs=64, validation_steps=64) #[0., 0., 0., 1., 0.] print( model.predict( np.array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]))) #[1., 0., 1., 1., 1.] print( model.predict( np.array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]))) model.model.save_weights('discard_rough.h5')
def setUp(self): self.g = Game()
def test_rounds(): g = Game(player_num=2) c, r = g.playRounds(2) print(c) print(r)
import sys import pygame as pg from Game import Game from MenuState import MenuState from GameplayState import GameplayState from GameOverState import GameOverState pg.init() screen = pg.display.set_mode((224 * 3, 256 * 3)) icon = pg.image.load("Assets/Textures/arkanoid_icon.png") states = { "Menu": MenuState(), "Gameplay": GameplayState(), "GameOver": GameOverState() } game = Game(screen, states, "Menu", "Arkanoid", icon) game.run() pg.quit() sys.exit()
play_button_rect.y = math.ceil(screen.get_height()/2) #charge une image play_ctb = pygame.image.load('image/Play_ctb.png') #modifie la taille de l'image (x y) play_ctb=pygame.transform.scale(play_ctb,(400,350)) # play_ctb_rect = play_button.get_rect() #place l'image dans la fenetre play_ctb_rect.x = math.ceil(screen.get_width()/6) play_ctb_rect.y = math.ceil(screen.get_height()/2) game = Game() running = True while running: # appliquer l'arriere plan blit permet d'injecter unne image a endroit specifique de la scene screen.blit(banner, (0,0)) #verifier si le jeux est lancer if game.is_playing: game.update(screen) elif game.is_playing_ctb: #lance la partie game.update_ctb(screen) else:
pygame.display.flip() # Keep at 22FPS LOADINGCLOCK.tick(22) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if not GameLoaded: # Game Class GAME = Game() # Cursor Image Utility.LogMessage("Initializing Cursor...", "LOADINGINFO") Cursor = pygame.image.load("Assets/cursor.png") Cursor_Rect = Cursor.get_rect() # Font for non-image text Utility.LogMessage("Initializing font...", "LOADINGINFO") FONT = pygame.font.Font("Assets/font.ttf", 42) # Creating refresh-rate clock Utility.LogMessage("Initializing clock...", "LOADINGINFO") CLOCK = pygame.time.Clock() # FPS option in "savegame.dat", please prefer using the refresh rate of your monitor,
from Board import Board from Game import Game from Console import Console import pickle if __name__ == '__main__': print("1. Start a new game \n2. Load an existing game") while True: command = input(">> ") if command == "1": board = Board() game = Game(board) break elif command == "2": with open("board.pickle", "rb") as file: board = pickle.load(file) with open("game.pickle", "rb") as file: game = pickle.load(file) break else: print("Invalid command!") console = Console(game) console.start()
# Exploration settings epsilon = 1 # not a constant, going to be decayed EPSILON_DECAY = 0.99975 MIN_EPSILON = 0.001 alice = OneStepBot(1, 1) bob = DQNAgent(-1, DISCOUNT, LEARNING_RATE) MARGIN = 20 RADIUS = 35 interface = Interface(margin=MARGIN, radius=RADIUS) # Iterate over episodes for episode in tqdm(range(1, EPISODES + 1), ascii=True, unit='episodes'): # Restarting episode - reset episode reward and step number episode_reward = 0 game = Game() current_state = np.reshape(np.ndarray.flatten(np.array(game.board)), (1, 42)) step = 1 # Reset flag and start iterating until episode ends done = False while not done: if game.player_turn == bob.turn: # This part stays mostly the same, the change is to query a model for Q values if np.random.random() > epsilon: # Get action from Q table action = bob.make_move(game.board) if action not in game.free_columns: action = rd.choice(game.free_columns) else:
from Game import Game def set_board(game, flipped_cards=[]): for i in range(len(game.cards)): if i % 3 == 0: print('') card = game.cards[i] card_face = card.front_face if card in flipped_cards else card.visible_face print(f"[ {card_face} ]", end=" ") print('') game1 = Game() game1.start() last_event = None def ask_for_card(): if last_event == 'FIRST_CARD_PICKED': return input('Select the second card...').upper() return input('Select a card...').upper() while True: set_board(game1) letter = ask_for_card() if letter == 'Q':
def run(self, cmd_line): # create board current_board = Board() # create game player1, player2 = self.parse_players(cmd_line) current_game = Game(current_board, player1, player2) # create game history if self.history: game_history = GameHistory(current_game) while (True): # print board from board class current_game.current_board.print_board() # print turn and color from game class current_game.print_turn() if self.history: command = input("undo, redo, or next\n>") if command == "undo": current_game = game_history.undo(current_game) current_board = current_game.current_board continue elif command == "redo": current_game = game_history.redo(current_game) current_board = current_game.current_board continue elif command == "next": game_history.redo_stack = [] else: print("That is an invalid command") continue # add game state to undo stack if self.history: game_history.save(current_game) # check if the game has ended in a victory or draw if current_game.is_game_over(current_board): break while (True): try: # increment game counter current_game.game_counter += 1 # current player makes a move current_game.current_player.make_a_move( self, current_game, current_game.current_board, current_game.other_player) # change turns temp = current_game.current_player current_game.current_player = current_game.other_player current_game.other_player = temp # increment number of turns made current_game.number_of_turns += 1 break except OutOfBoundsError: print("That piece cannot move") except JumpAvailableError: print("That piece cannot move") except NotYourPieceError: print("That is not your piece") except EmptySpaceError: print("No piece at that location") except PieceIsStuckError: print("That piece cannot move")
''' Maze Puzzle Game A Fun Engaging Intelectuall challenging Game @Milan Zinzuvadiya ''' from Game import Game #main class to initiate game #pygame.init() g = Game() g.play()
def testPoints(self): game = Game(1, 13) self.assertEqual(game.getPoints(), 0) game.addPoints(10) self.assertEqual(game.getPoints(), 10)
from Game import Game x = Game() x.startGame()
from Game import Game import easygui while True: game_path = easygui.fileopenbox( default= "C:/Users/Stephanos/Documents/Dev/NBAThesis/NBA_Thesis/static/data/game_raw_data/", title="Select a game file") while True: print('\nEnter the event (or exit to return to game select): ') event = input() if (event == "exit"): break try: game = Game(path_to_json=game_path, event_num=event) game.read_json() game.start() except: print("Invlid event number, try again.")
def addGame(self, newWeek, newHomeTeamRank, newAwayTeamRank, newDateTime): newGame = Game(newWeek, newHomeTeamRank, newAwayTeamRank, newDateTime) self.allGames.append(newGame)
from Deck import Deck from Player1 import Player from Game import Game players = int(input("Number of Players:")) decks = int(input("Size of Deck (# of copies):")) bj = float(input("Blackjack Multiplyer:")) print('-----------------------Game start-----------------------') game = Game(players, decks, bj) game.setup() games = 5 while games != 0: games -= 1 game.replay() input()
print("Welcome to the X-Rudder Game!") while True: version = input( "Do you want to play with another person or a computer?. Type \"P\" for player or \"C\" for computer: " ) if (version == "C") or (version == "c") or (version == "P") or (version == "p"): break else: print("Incorrect value entered, try again.") if (version == "C") or (version == "c"): playerOneName = input("Enter your name: ") playerTwoName = "Computer" startGame = Game(playerOneName, playerTwoName, True) #Creating an object of type Game # Plays the game with the computer print("Here's the initial board:") startGame.getBoard().printBoardColors() print(Style.RESET_ALL + "=====") print("Let's get started!") testing = Nodes(startGame, startGame.getBoard(), startGame.getPlayer1(), startGame.getPlayer2()) #NOTE: USED FOR TESTING testing.generateChildren(1) #NOTE: USED FOR TESTING #print(startGame.computerPlaceToken()) For testing startGame.playGameWithComputer() if (version == "P") or (version == "p"): playerOneName = input("Enter player one's name: ") playerTwoName = input("Enter player two's name: ") startGame = Game(playerOneName, playerTwoName,
average_score += int(p[i] * child_score) if scn == "infinite": pass elif scn_c == "infinite": scn = "infinite" else: scn += scn_c return average_score, scn if __name__ == '__main__': count = 1 max_depth = 3 a = 1 for i in range(count): game = Game() game.random_field() game.random_field() T = 4 * int(pow(4, 15)) while not game.is_end(game.grid): game.print_screen() node = Node(game.grid, 0, max_depth, "Max", t=T) action, scn = node.evaluation() if scn == 0: T *= int(pow(2, a)) print("scn:{s}".format(s=scn)) game.update_grid(action) game.random_field() game.print_screen() print("==================================================")