Example #1
0
 def mkDay(self):
         self.announce("Daytime! " + self.nk + " was killed during the night.")
         self.announce(self.nk + " was a " + self.roles[self.nk].role + ".")
         self.removePlayer(self.nk)
         if (self.deadp != None):
                 self.announce("Yesterday's lynch, " + self.deadp_name + ", was a " + self.deadp.role + ".")
         Game.mkDay(self)                
Example #2
0
 def newGame( self, layout, pacmanAgent, ghostAgents, display ):
   agents = [pacmanAgent] + ghostAgents[:layout.getNumGhosts()]
   initState = GameState()
   initState.initialize( layout, len(ghostAgents) )
   game = Game(agents, display, self)
   game.state = initState
   return game
Example #3
0
def main(main_log, error_flag):
    """main_log function"""
    main_log.debug("main() called")
    game = Game(error_flag)
    game.start()
    main_log.debug("main() finish")
    return 0
Example #4
0
 def mkNight(self):
         for votee in self.votees:
                 if (len(self.votees[votee]) >= (len(self.voters) / 2 + 1)):
                         deadp = votee
                         if (deadp == "NL"):
                                 self.deadp = None
                                 self.announce("It is now night. Zzz...")
                                 Game.mkNight(self)
                                 return
                         elif (deadp.role == "Jester"):
                                 self.announce("The Jester, " + self.get_role("Jester") + " has gotten himself lynched! Jester win!")
                                 self.game_over()
                         elif ((deadp.role != "SJ") and (len(self.voters) <= 2)):
                                 self.announce("The Serial Jester, " + self.get_role("SJ") + ", has gained dominance over the town! Town win!")
                         elif (deadp.role == "SJ"):
                                 self.announce("The town has lynched the Serial Jester! Serial Jester win!")
                                 if (self.get_role("Jester") != None):
                                         self.announce("Jester was " + self.get_role("Jester") + ".")
                         else:
                                 self.deadp = deadp
                                 self.deadp_name = self.names[deadp]
                                 self.removePlayer(self.names[deadp])
                                 self.announce("It is now night. Zzz...")
                                 Game.mkNight(self)
                                 return
         self.game_over()
Example #5
0
 def test_intransitive_commands_should_not_throw_exceptions(self):
     for word in self.words:
         game = Game()
         load_advent_dat(game)
         game.start()
         game.do_command(['no'])  # WOULD YOU LIKE INSTRUCTIONS?
         game.do_command([word])
Example #6
0
def main():
    global args
    # configure game object
    game = Game()
    g = args.grid_size
    game.set_size(g, g)
    if args.difficulty == 2:
        game.cat = True
    elif args.difficulty == 0:
        game.easy = True
    # configure player object
    if args.meta:
        if args.test:
            player = agent.CheeseMeta(game, ['left', 'forward', 'right'], epsilon=args.epsilon, fov=args.fov)
        else:
            player = agent.MetaAgent(game, ['left', 'forward', 'right'], epsilon=args.epsilon, fov=args.fov)
        player.side = args.side
    else:
        player = agent.Agent(game, ['left', 'forward', 'right'])
    player.adjust_rewards(abs(args.cheese_reward), abs(args.trap_reward), abs(args.hunger_reward))
    
    # boilerplate for CLI
    t = threading.Thread(target=command, args=(player,))
    t.daemon = True
    t.start()
    # launch point
    if args.meta or args.benchmark:
        benchmark(player, max_runs=args.max_actions)
    else:
        evaluate(player, max_runs=args.max_actions)
Example #7
0
 def test_only_allow_valid_responses_to_yesno_questions(self):
     game = Game()
     # Test valid yes/no responses
     valid_yes_responses = ['y', 'yes']
     valid_no_responses = ['n', 'no']
     
     # Test each yes response
     for response in valid_yes_responses:
         # Yes responses should correspond to true
         game.yesno_callback = self.assertTrue
         game.do_command([response])
     
     # Test each no response
     for response in valid_no_responses:
         # No responses should correspond to false
         game.yesno_callback = self.assertFalse
         game.do_command([response])
     
     # Test invalid yes/no responses
     invalid_responses = ['ye', 'yeah', 'Y', 'Yes', 'No', 'nope', 'nah']
     # Create a callback that always raises an exception
     # That way, if do_command recognizes the response as valid,
     # and thus calls the callback, the test will fail
     def raise_exception_callback(yes):
         raise ValueError
     
     for response in invalid_responses:
         game.yesno_callback = raise_exception_callback
         try:
             game.do_command([response])
         except ValueError:
             raise ValueError("'{}' should not be a valid yes/no response".format(response))
Example #8
0
def replay():
	print('wake up the brain...')
	sess = tf.Session()

	game = Game(SCREEN_WIDTH, SCREEN_HEIGHT, show_game=True)
	brain = DQN(sess, SCREEN_WIDTH, SCREEN_HEIGHT, NUM_ACTION)

	saver = tf.train.Saver()
	ckpt = tf.train.get_checkpoint_state('model')
	saver.restore(sess, ckpt.model_checkpoint_path)

	for episode in range(MAX_EPISODE):
		terminal = False
		total_reward = 0

		state = game.reset()
		brain.init_state(state)

		while not terminal:
			action = brain.get_action()

			state, reward, terminal = game.step(action)
			total_reward += reward

			brain.remember(state, action, reward, terminal)

			time.sleep(0.3)

		print('episode: %d, score: %d' % (episode + 1, total_reward))
Example #9
0
    def __init__(self, bots, round=3000):
        """Initialization of the market game

        @param bots: list of bots
        @param round: number of round

        """
        Game.__init__(self, Market.NAME, bots)

        # Initialization of the constants of the game
        self.farm_price = 20
        self.mill_price = 85
        self.transformation_rate = 1.0
        self.growing_cycle = 100
        self.flour_bought_each_turn = 50
        self.farm_production = 1
        self.mill_production = 1

        # Initialization of the markets
        self.wheat_market=list()
        self.flour_market=list()
        self.transactions_done=list()
        self.stats=list()

        self.round = int(round)
        self.players_state = dict()
        self.botsid = dict()
        i = 0
        for b in self.bots:
            botname = b.name+"_"+str(i)
            self.botsid[botname] = b
            self.players_state[botname]=Player(botname)
            i+=1
Example #10
0
	def _do_code_chalngaccept(self, sock, message):
		plaintext = decrypt_AES(self.clients[sock].symkey, message)
		challenged, challenger = plaintext.split(',')
		players = [self.clients[sock]]

		for user in self.clients.values():
			if user == challenger:
				players.append(user)
		
		# Init new Game and put it in games dict with gameid as key
		new_game = Game(players)
		gameid = new_game.gameid()
		self.games[gameid] = new_game		

		# Set gameid for challenged in clients dict and send gameid
		self.clients[sock].set_game(gameid)
		ciphertext = encrypt_AES(self.clients[sock].symkey, str(gameid).encode())
		self.fire(write(sock, B_GAMEID+ciphertext))

		# Set gameid for challenger in clients dict and send gameid
		for socket, user in self.clients.items():
			if user == challenger:
				print("Sent B_CHALNGACCEPT to {}".format(user))
				ciphertext = encrypt_AES(user.symkey, str(gameid).encode())
				self.fire(write(socket, B_CHALNGACCEPT+ciphertext))
def run():
    n = 5
    width, height = 8, 8
    model_file = 'best_policy_8_8_5.model'
    try:
        board = Board(width=width, height=height, n_in_row=n)
        game = Game(board)

        # ############### human VS AI ###################
        # load the trained policy_value_net in either Theano/Lasagne, PyTorch or TensorFlow

        # best_policy = PolicyValueNet(width, height, model_file = model_file)
        # mcts_player = MCTSPlayer(best_policy.policy_value_fn, c_puct=5, n_playout=400)

        # load the provided model (trained in Theano/Lasagne) into a MCTS player written in pure numpy
        try:
            policy_param = pickle.load(open(model_file, 'rb'))
        except:
            policy_param = pickle.load(open(model_file, 'rb'),
                                       encoding='bytes')  # To support python3
        best_policy = PolicyValueNetNumpy(width, height, policy_param)
        mcts_player = MCTSPlayer(best_policy.policy_value_fn,
                                 c_puct=5,
                                 n_playout=400)  # set larger n_playout for better performance

        # uncomment the following line to play with pure MCTS (it's much weaker even with a larger n_playout)
        # mcts_player = MCTS_Pure(c_puct=5, n_playout=1000)

        # human player, input your move in the format: 2,3
        human = Human()

        # set start_player=0 for human first
        game.start_play(human, mcts_player, start_player=1, is_shown=1)
    except KeyboardInterrupt:
        print('\n\rquit')
Example #12
0
    def run(self):
        if self.client.connected() is False:
            pygame.quit()
            quit()

        self.client.run()
        Game.run(self)
Example #13
0
class TestPlayerGetFunctions(unittest.TestCase):
    """Test the _get_next_player and _get_previous_player funcions."""
    def setUp(self):
        self.game = Game()
        for name in ['Jordan', 'Matt', 'Justin', 'Cris']:
            self.game.add_player(name)

        self.middle_next = 1
        self.middle_prev = 2
        self.beginning = 0
        self.end = 3

    def test_get_next_from_center(self):
        """Get the next player from the middle of the list of players."""
        self.assertEqual(self.game._get_next_player(self.middle_next),
            self.middle_next + 1)

    def test_get_next_from_center_with_step(self):
        """Get the next player from the middle of the list of players
        using a step size greater than one.
        """
        self.assertEqual(self.game._get_next_player(self.middle_next, 2),
            self.middle_next + 2)

    def test_get_next_from_end(self):
        """Get the next player from the end of the list of players."""
        self.assertEqual(self.game._get_next_player(self.end),
            self.beginning)

    def test_get_next_from_end_with_step(self):
        """Get the next player from the end of the list of players using
        a step size greater than one.
        """
        self.assertEqual(self.game._get_next_player(self.end, 2),
            self.beginning + 1)

    def test_get_previous_from_center(self):
        """Get the previous player from the middle of the list of players."""
        self.assertEqual(self.game._get_previous_player(self.middle_prev),
            self.middle_prev - 1)

    def test_get_previous_from_center_with_step(self):
        """Get the previous player from the middle of the list of players
        using a step size greater than one.
        """
        self.assertEqual(self.game._get_previous_player(self.middle_prev, 2),
            self.middle_prev - 2)

    def test_get_previous_from_beginning(self):
        """Get the previous player from the beginning of the list of players.
        """
        self.assertEqual(self.game._get_previous_player(self.beginning),
            self.end)

    def test_get_previous_from_beginning_with_step(self):
        """Get the previous player from the beginning of the list of players
        using a step size greater than one.
        """
        self.assertEqual(self.game._get_previous_player(self.beginning, 2),
            self.end - 1)
Example #14
0
def main():
    # Key(class) -> list of cards
    # Result should be list of people, list of weapons, list of rooms

    # -- Main menu --
    choice = input_int("1) Start new game\n2) Load game\n> ", valid=[1,2])

    # Object that holds game data
    game = None

    if choice == 1:
        # Choose card deck
        card_file = input_filename("Enter card file: ")

        cards = init_cards(card_file)
        game = setup_game(cards)

    elif choice == 2:
        load_file = input_filename("Enter save file: ")
        game = Game()
        game.load_from_file(load_file)
        pass

    # -- At this point a game is loaded --
    game.run()
    def myteam(self):
        now = estNow()
        monday = toMondayOfWeek(now)

        games = []
        games.extend(NeuLion.getGames(subtractWeek(monday)))
        games.extend(NeuLion.getGames(monday))
        games.extend(NeuLion.getGames(addWeek(monday)))

        games = Game.filterGamesForTeam(self.myTeam, games)
        liveGames = Game.extractLiveGames(now, games)
        pastGames = Game.extractPastGames(now, games)

        # Live Game
        for g in liveGames:
            item = generateGameItem(g, 'LIVE: %s @ %s' % (g.visitors.name, g.homeTeam.name))
            xbmcplugin.addDirectoryItem(handle=self.handle, url='%s/game/%s/%s/%s?team=%s' % (self.pluginBase, g.year, g.weekStart, g.id, self.myTeam.id), listitem=item, isFolder=True)

        # Past 7 days of games
        for g in pastGames:
            item = generateGameItem(g, 'REPLAY [%s]: %s @ %s' % (gameDateToString(g.startTime), g.visitors.name, g.homeTeam.name))
            xbmcplugin.addDirectoryItem(handle=self.handle, url='%s/game/%s/%s/%s?team=%s' % (self.pluginBase, g.year, g.weekStart, g.id, self.myTeam.id), listitem=item, isFolder=True)
            print '%s/game/%s/%s/%s?team=%s' % (self.pluginBase, g.year, g.weekStart, g.id, self.myTeam.id)

        # Next 7 days of upcoming games as placeholders
        for g in games:
            item = generateGameItem(g, 'FUTURE [%s]: %s @ %s' % (gameTimeToString(g.scheduledTime), g.visitors.name, g.homeTeam.name))
            xbmcplugin.addDirectoryItem(handle=self.handle, url='%s/game/%s/%s/%s' % (self.pluginBase, g.year, g.weekStart, g.id), listitem=item, isFolder=True)

        xbmcplugin.endOfDirectory(self.handle)
Example #16
0
 def test_skip_to_treasure(self):
     game = Game(['wes', 'bec'])
     game.output = MagicMock()
     game.play()
     self.assertEqual(game.stage, 'treasure')
     game.output.assert_any_call('skip to treasure stage')
     self.assertEqual(game.output.call_count, 1)
 def opponent_winning(self):
     for i in range(9):
         if self._game.valid_move(i):
             test_game = Game(self._game.state_of_board())
             test_game.play(i)
             if test_game.calculate_outcome() == Game.X_WINS:
                 return i
Example #18
0
	def test_over_rolls_with_strikes(self):
		g = Game()
		# assert an exception is raised if player plays more than 12 strikes
		for x in range(1, 13):
			g.roll(score=10)
		with self.assertRaises(GameOverException):
			g.roll(score=10)
Example #19
0
	def test_simple_cases(self):
		g = Game()
		self.assertTrue(g._is_frame_complete(1, [0, 0]))
		self.assertTrue(g._is_frame_complete(2, [1, 0]))
		self.assertTrue(g._is_frame_complete(3, [0, 1]))
		self.assertTrue(g._is_frame_complete(4, [3, 4]))
		self.assertTrue(g._is_frame_complete(9, [4, 5]))
Example #20
0
	def test_frame10_spare(self):
		g = Game()
		self.assertFalse(g._is_frame_complete(10, [5, 5]))
		self.assertFalse(g._is_frame_complete(10, [9, 1]))

		self.assertTrue(g._is_frame_complete(10, [9, 1, 9]))
		self.assertTrue(g._is_frame_complete(10, [9, 1, 10]))
Example #21
0
	def test_over_rolls(self):
		g = Game()
		# assert an exception is raised if player plays more than 20 rolls
		for x in range(1, 21):
			g.roll(score=1)
		with self.assertRaises(GameOverException):
			g.roll(score=10)
Example #22
0
    def test_add_player_to_the_game(self):
        player = Player(name='foo bar')

        game = Game()
        game.add_player(player)

        assert game.players == [player]
Example #23
0
class Room(object):
    """
    game room
    """
    def __init__(self, name=u"", players=[], size=0):
        self.name = name
        self.players = players # []
        self.size = size
        self.game = Game(self) # create a game

    def change_size(self, size):
        """
        @type size: int
        """
        if size <= 20 and size >= len(self.game.players): # otherwise stay unchanged
            self.size = size

    def add_player(self, player):
        """
        @type player: C{Player}
        """
        if self.game.status == "ready":
            self.game.add_player(player)
        else:
            print "cannot add players after the game started."

    def remove_player(self, player):
        # 让错误显现
        self.players.remove(player)

    def is_full(self):
        if len(self.players) == self.size:
            return True
        else:
            return False
Example #24
0
File: sonar.py Project: hausdorf/hw
 def newGame( self, layout, pacmanAgent, numGhosts, display ):
   agents = [pacmanAgent] + [RandomGhost(i+1) for i in range(numGhosts)]
   initState = GameState()
   initState.initialize( layout, numGhosts)
   game = Game(agents, display, self)
   game.state = initState
   return game
    def search(b, d, move=False):
        """
        Performs expectimax search on a given configuration to
        specified depth (d).

        Algorithm details:
           - if the AI needs to move, make each child move,
             recurse, return the maximum fitness value
           - if it is not the AI's turn, form all
             possible child spawns, and return their weighted average 
             as that node's evaluation
        """
        if d == 0 or (move and Game.over(b)):
            return fitness(b)

        alpha = fitness(b)
        if move:
            for _, child in Game.actions(b):
                return max(alpha, search(child, d-1))
        else:
            alpha = 0
            zeros = [(i,j) for i,j in itertools.product(range(4), range(4)) if b[i][j] == 0]
            for i, j in zeros:
                c1 = [[x for x in row] for row in b]
                c2 = [[x for x in row] for row in b]
                c1[i][j] = 2
                c2[i][j] = 4
                alpha += .9*search(c1, d-1, True)/len(zeros) + \
                         .1*search(c2, d-1, True)/len(zeros)
        return alpha
Example #26
0
def main():
  # Initialise stuff: Pygame, the clock..
  pygame.init()
  game = Game()
  game.clock = pygame.time.Clock()

  # Get the PyGame variables in to Game.
  game.screen = pygame.display.set_mode((game.xRes,game.yRes), DOUBLEBUF | HWSURFACE)
  pygame.display.set_caption('Hullet Bell')

  # Set up initial handler
  game.handler = handler.TitleScreenHandler(game)

  while True:
    # Cap the frame rate.
    game.clock.tick(60)

    # Run the game handler.
    if not game.handler.update():
      break

    # Show our hard work!
    pygame.display.flip()

  pygame.quit()
Example #27
0
    def __init__(self, directory):
        Gtk.Window.__init__(self, title="Red Bot 2015")

        dwarfs = ["blue", "green", "red", "violet"]
        grid = Gtk.Grid()

        self.players = []
        self.playfield = RedBotPlayfield(dwarfs)
        self.current_round = 0
        self.round_label = Gtk.Label("round: " + str(self.current_round))
        self.next_round_button = Gtk.Button(label="Next Round")
        self.next_round_button.connect("clicked", self.on_next_button_clicked)
        self.prev_round_button = Gtk.Button(label="Previous Round")
        self.prev_round_button.connect("clicked", self.on_prev_button_clicked)
        self.connect("delete-event", Gtk.main_quit)
        grid.attach(self.prev_round_button, 0, 0, 1, 1)
        grid.attach(self.next_round_button, 1, 0, 1, 1)
        grid.attach(self.playfield, 0, 1, 2, 4)
        grid.attach(self.round_label, 2, 0, 1, 1)
        self.add(grid)
        self.files = filter(lambda l: l.startswith("playfield-") and l.endswith(".txt"), os.listdir(directory))
        self.file_index = 0
        if self.files != []:
            self.files.sort()
            g = Game(self.files[self.file_index], [])
            for i in range(g._get_strat_cnt()):
                self.players.append(RedBotPlayer(dwarfs[i]))
                grid.attach(self.players[i], 2, i + 1, 1, 1)
            self.set_round(g)
            self.show_all()
        else:
            print "no playfield found"
            exit(1)
 def test_all_ones(self):
     """Constructor"""
     game = Game()
     pins = [1 for i in range(11)]
 
     game.roll(11, pins)
     self.assertEqual(game.score, 11)
Example #29
0
class TestGame(unittest.TestCase):
	def game_init_get_post_request_mock(self, host, port, url, params):
		return '{"gameId":20, "board":[[0, 0, 0], [0, 0, 0]]}';

	def game_move_get_post_request_mock(self, host, port, url, params):
		return '{"board":[[0, 0, 2], [0, 0, 1]]}'

	def setUp(self):
		self.game = Game('localhost', 3000)

	def test_game_init(self):
		self.game.get_post_request = self.game_init_get_post_request_mock
		self.game.init('Player 1', 4)
		self.assertEquals(20, self.game.gameId)
		self.assertEquals(3, len(self.game.state.board))
		self.assertEquals(2, len(self.game.state.board[0]))
		for row in self.game.state.board:
			self.assertEquals([0, 0], row)

	def test_game_move(self):
		self.game.get_post_request = self.game_move_get_post_request_mock
		self.game.move(2)
		self.assertEquals(3, len(self.game.state.board))
		self.assertEquals(2, len(self.game.state.board[0]))
		self.assertEquals([0, 0], self.game.state.board[0])
		self.assertEquals([0, 0], self.game.state.board[1])
		self.assertEquals([2, 1], self.game.state.board[2])
Example #30
0
def playRandomLearningGames(amountOfGames,updateEvery):

	learning.initLearning()

	players = []
	players.append(["Learner","LEARNING_PLAYER"])
	for i in xrange(2):
		newPlayerType = random.choice(["CONSERVATIVE","BIG_MOUTH","CAUTIOUS_BLUFFER","HEURISTIC_PLAYER"])
		players.append(["Other Player",newPlayerType])

	scores = dict()
	scores["Other Players"] = 0
	scores["Learner"] = 0

	for i in xrange(1,amountOfGames+1):

		players = []
		players.append(["Learner","LEARNING_PLAYER"])
		for j in xrange(2):
			newPlayerType = random.choice(["CONSERVATIVE","BIG_MOUTH","CAUTIOUS_BLUFFER","HEURISTIC_PLAYER"])
			players.append(["Other Players",newPlayerType])

		theGame = Game(players)
		winner = theGame.startGame()
		scores[winner] += 1
		if i%updateEvery == 0:
			printLine = "TRAINING LEARNER: GamesPlayed:"+str(i)+"\t"
			for key in scores:
				percent = '{percent:.2%}'.format(percent=(float(scores[key]) / float(i)))
				printLine += key+": "+percent+"\t"
			print printLine

			learning.updateLearning(updateEvery)
Example #31
0
import sys
import pygame
from states.menu import Menu
from states.gameplay import Gameplay
from states.game_over import GameOver
from states.splash import Splash
from game import Game

pygame.init()
screen = pygame.display.set_mode((1024, 768))
states = {
    "MENU": Menu(),
    "SPLASH": Splash(),
    "GAMEPLAY": Gameplay(),
    "GAME_OVER": GameOver(),
}

game = Game(screen, states, "SPLASH")
game.run()

pygame.quit()
sys.exit()
Example #32
0
def main():
    game = Game()
    game.play_game()
Example #33
0
B_MUTATION_PROBABILITY = 0.5
MAX_GEN = 10000
N_EPISODE = 10
is_training_finished = False
sessions = [tf.Session(graph=graph) for _ in range(POPULATION_SIZE)]
for sess in sessions:
    sess.run(init)
for generation in range(MAX_GEN)
    fitness_data = []
    for sess in sessions
        fitness = 0
        for _ in range(N_EPISODE):
            fitness_episode = 0

            ready = Event()
            para = Game(ready)

            flag = True
            save_threshold = 0
            while True:
                inputs = para.get_input_to_algo()
                predicted_action,p,w1,b1,w2,b2=sess.run([Y_index,Y_,W1,B1,W2,B2],feed_dict={X:[inputs]})
                para.set_directions(predicted_action)

                thread = Thread(target=game.launch)
                thread.start()
                ready.wait()

                results = game.get_results()

Example #34
0
 def __init__(self):
     self.game = Game()
     self.score = 0
     self.play()
Example #35
0
b_bishop = pygame.image.load("assets/blackbishop.png")
b_bishop = pygame.transform.scale(b_bishop, (int(SQUARESIZE), int(SQUARESIZE)))

b_queen = pygame.image.load("assets/blackqueen.png")
b_queen = pygame.transform.scale(b_queen, (int(SQUARESIZE), int(SQUARESIZE)))

b_knight = pygame.image.load("assets/blackknight.png")
b_knight = pygame.transform.scale(b_knight, (int(SQUARESIZE), int(SQUARESIZE)))

streaming_events = False
streaming_game = False

board_generated = False

Game = Game("")

Move = ["", ""]
FirstTouchDown = ""


def generate_squares(side):
    squares.clear()

    for i in range(0, 8):
        for j in range(0, 8):
            x = int(i * SQUARESIZE) + XBUFFER
            y = int(j * SQUARESIZE)

            width = SQUARESIZE
            height = SQUARESIZE
Example #36
0
    def start_game(self):
        flag = 1
        num_of_game = 1
        print('** The great guessing game **')
        print('')
        while flag and num_of_game <= 100:
            gamePlayed = Game()
            gamePlayed.select_word()

            print()
            currentGuess = '____'
            choiceInput = ''
            ptr = 1

            gamePlayed.word = gamePlayed.word
            while ptr:
                print('Your Current Guess : ', currentGuess)
                print()
                print('g = guess, t = tell me, l for a letter, and q to quit')
                choiceInput = input()
                if choiceInput == 'q' or choiceInput == 'Q':
                    ptr = 0
                    flag = 0
                    gamePlayed.status = 'Gave Up'
                    self.noOfPlays.append(gamePlayed)
                elif choiceInput == 't' or choiceInput == 'T':

                    gamePlayed.evaluate_negative_score(gamePlayed,
                                                       currentGuess)
                    ptr = 0
                    gamePlayed.status = 'Gave Up'
                    self.noOfPlays.append(gamePlayed)
                    print('The correct word is : ', gamePlayed.word)
                    print()
                elif choiceInput == 'g' or choiceInput == 'G':
                    userGuess = input('Enter your Guess: ')
                    if userGuess == gamePlayed.word:
                        ptr = 0
                        gamePlayed.score_evaluation(gamePlayed, currentGuess)
                        gamePlayed.status = 'Success'
                        self.noOfPlays.append(gamePlayed)
                        print('Wow! You got it right : ', gamePlayed.word)
                        print()
                    else:
                        ptr = 1
                        gamePlayed.badGuess += 1
                        print('Sorry! Your guess is incorrect.Try again!.')
                        print()
                elif choiceInput == 'l' or choiceInput == 'L':
                    gamePlayed.numOfRounds += 1
                    userLetter = input('Enter a letter: ')
                    if gamePlayed.word.count(userLetter) > 0:
                        count = gamePlayed.word.count(userLetter)
                        print('Well.. you got', count, ' letters')
                        print()
                        tempString = ''
                        for i in range(len(gamePlayed.word)):
                            if gamePlayed.word[i] == userLetter:
                                tempString += userLetter
                            else:
                                tempString += currentGuess[i]
                        currentGuess = tempString
                        if currentGuess == gamePlayed.word:
                            ptr = 0
                            gamePlayed.score_evaluation(
                                gamePlayed, currentGuess)
                            gamePlayed.status = 'Success'
                            self.noOfPlays.append(gamePlayed)
                            print('Great!You guessed it right. Word is : ',
                                  gamePlayed.word)
                            print()
                    else:
                        gamePlayed.missedLetters += 1
                        print('No such letter found. Please try again!!!')
                        print()
                else:
                    print('Incorrect input!! Re-enter choice from the  menu.')
                    print()
                num_of_game += 1

        print('Game\tWord\tStatus \tBad Guesses\tMissed Letters\tScore')
        print('----\t----\t------ \t-----------\t--------------\t-----')
        itr = 1
        totalScore = 0.00
        for g in self.noOfPlays:
            string_to_print = ''
            spaces_for_game = 4 - len(str(abs(itr)))
            spaces_for_bad_guesses = 11 - len(str(abs(g.badGuess)))
            spaces_for_missed_letter = 14 - len(str(abs(g.missedLetters)))
            string_to_print = str(abs(itr)) + " " * spaces_for_game + "\t"
            string_to_print += g.word + "\t"
            string_to_print += g.status + "\t"
            string_to_print += str(abs(
                g.badGuess)) + " " * spaces_for_bad_guesses + "\t"
            string_to_print += str(abs(
                g.missedLetters)) + " " * spaces_for_missed_letter + "\t"
            string_to_print += str((round(g.score, 2)))
            print(string_to_print)  #output menu table
            #print(itr, " "*spaces_for_game, "\t", g.word, "\t", g.status, "\t", g.badGuess, " "*spaces_for_bad_guesses, "\t", g.missedLetters , " "*spaces_for_missed_letter, "\t", round(g.score,2))
            #print(itr, '\t', g.word, g.status, '\t', g.badGuess, '\t',g.missedLetters, '\t',  g.score)
            print()
            itr += 1
            totalScore += g.score

        print("Final Score : ", round(totalScore, 2))
        print()
Example #37
0
from table_generator import gaussian_table
from game import Game
from ai_player import AIPlayer

def GPlayer(sigma, mu):
  return AIPlayer(gaussian_table(sigma, mu))

players = [GPlayer(i//10,0) for i in range(45,56)]
scores = [0]*10

for (i, player1) in enumerate(players):
  for (j, player2) in enumerate(players):
    if i == j:
      pass
    game = Game(player1, player2, 7, 6, 4, verbose=False)
    result = game.run()
    if result == 1:
      scores[i] += 1
    elif result == -1:
      scores[j] += 1
    else:
      scores[i] += 0.5
      scores[j] += 0.5

best_score = 0
best_player = 0

print(scores)
Example #38
0
from memory import Memory
from model import Residual_CNN
from funcs import playMatches, playMatchesBetweenVersions

import loggers as lg

from settings import run_folder, run_archive_folder
import initialise
import pickle


lg.logger_main.info('=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*')
lg.logger_main.info('=*=*=*=*=*=.      NEW LOG      =*=*=*=*=*')
lg.logger_main.info('=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*')

env = Game()

# If loading an existing neural network, copy the config file to root
if initialise.INITIAL_RUN_NUMBER != None:
    copyfile(run_archive_folder  + env.name + '/run' + str(initialise.INITIAL_RUN_NUMBER).zfill(4) + '/config.py', './config.py')

import config

######## LOAD MEMORIES IF NECESSARY ########

if initialise.INITIAL_MEMORY_VERSION == None:
    memory = Memory(config.MEMORY_SIZE)
else:
    print('LOADING MEMORY VERSION ' + str(initialise.INITIAL_MEMORY_VERSION) + '...')
    memory = pickle.load( open( run_archive_folder + env.name + '/run' + str(initialise.INITIAL_RUN_NUMBER).zfill(4) + "/memory/memory" + str(initialise.INITIAL_MEMORY_VERSION).zfill(4) + ".p",   "rb" ) )
Example #39
0
        self.default_bet = default_bet

    def play(self, dealer, players):
        print("DOUBLE DOWN\n")
        return "d"

    def bet(self, dealer, players):
        return 10


if __name__ == '__main__':

    players = [TestPlayer("test", 100)]

    print("Players: ", players)
    g = Game(players,
             debug=True,
             shoe=TestShoe([
                 Card(0, 1),
                 Card(0, 5),
                 Card(1, 1),
                 Card(1, 5),
                 Card(2, 3),
                 Card(3, 5)
             ]))
    g.run()

    print("OVERALL: ", players)
    if str(players) == "[test (100€)]":
        sys.exit(0)
    sys.exit(1)
Example #40
0
 def new_game(self, game, players, deck):
     g = Game('init', name=game, players=players, deck=deck.cards)
     return g
Example #41
0
import pygame
from game import Game

# instantiate main game object
game = Game()

# show logo splash screen
game.show_splash_screen()

# show the main menu, which in turn calls the game loop
while game.running:
    game.show_main_menu()

# exit game
pygame.quit()
Example #42
0
def main():
    game = Game()
    game.start()
Example #43
0
class GameRunner:
    def __init__(self):
        self.game = Game()
        self.agent = Agent()

        self.autoMC = False
        self.autoTD = False
        self.autoQL = False
        self.autoPlay = False

        card_path = 'resources/cards/'
        self.card_imgs = {}
        for (rank, suit) in cards:
            self.card_imgs[(rank, suit)] = pygame.image.load(os.path.join(card_path, f"{rank}_{suit}.png"))
        self.cBack = pygame.image.load('resources/cardback.png')

        self.init_display()
        self.render_board()
        

    def init_display(self):
        #Initialize Game
        pygame.init()
        self.screen = pygame.display.set_mode((640, 480))
        pygame.display.set_caption('Blackjack')
        self.font = pygame.font.SysFont("arial", 15)
        
        self.hitTxt = self.font.render('[H]it', 1, BLACK)
        self.standTxt = self.font.render('[S]tand', 1, BLACK)

        modes = ["off", "on"]
        self.MCTxt = [self.font.render('[M]C - ' + mode, 1, BLUE) for mode in modes]
        self.TDTxt = [self.font.render('[T]D - ' + mode, 1, BLUE) for mode in modes]
        self.QLTxt = [self.font.render('[Q]L - ' + mode, 1, BLUE) for mode in modes]
        self.playTxt = [self.font.render('[A]uto Play - ' + mode, 1, BLUE) for mode in modes]
        self.gameoverTxt = [self.font.render('End of Round. You WON!', 1, RED), self.font.render('End of Round. You LOST!', 1, RED)]

        self.ops_instr = self.font.render('Click on the button or type the initial character of the operation to play or toggle modes', 1, BLACK)
        self.save_instr = self.font.render('Press 1 to save AI state', 1, BLACK)
        self.load_instr = self.font.render('Press 2 to load from AI\'s saved state', 1, BLACK)

        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()
        self.background.fill((0x00, 0x62, 0xbe))
        self.hitB = pygame.draw.rect(self.background, WHITE, (10, OPS_BTN_Y, 75, OPS_BTN_HEIGHT))
        self.standB = pygame.draw.rect(self.background, WHITE, (95, OPS_BTN_Y, 75, OPS_BTN_HEIGHT))

        
    def loop(self):
        while True:
            # Our state information does not take into account of number of cards
            
            if self.autoMC:
                #MC Learning
                #Compute the values of all states under the default policy (see ai.py)
                self.agent.MC_run(50)
            if self.autoTD:
                #TD Learning
                #Compute the values of all states under the default policy (see ai.py)
                self.agent.TD_run(50)
            if self.autoQL:
                #Q-Learning
                #For each state, compute the Q value of the action "Hit" and "Stand"
                self.agent.Q_run(50)
            
            if self.autoPlay:
                if self.game.game_over() or self.game.stand:
                    self.game.update_stats()
                    self.game.reset()

                decision = self.agent.autoplay_decision(copy.deepcopy(self.game.state))
                if decision == 0:
                    self.game.act_hit()
                else:
                    self.game.act_stand()
                
            self.handle_user_action()
            self.render_board()
            
    def check_act_MC(self, event):
        clicked = event.type == MOUSEBUTTONDOWN and self.MCB.collidepoint(pygame.mouse.get_pos())
        pressed = event.type == KEYDOWN and event.key == K_m
        return clicked or pressed

    def check_act_TD(self, event):
        clicked = event.type == MOUSEBUTTONDOWN and self.TDB.collidepoint(pygame.mouse.get_pos())
        pressed = event.type == KEYDOWN and event.key == K_t
        return clicked or pressed

    def check_act_QL(self, event):
        clicked = event.type == MOUSEBUTTONDOWN and self.QLB.collidepoint(pygame.mouse.get_pos())
        pressed = event.type == KEYDOWN and event.key == K_q
        return clicked or pressed
    
    def check_act_autoplay(self, event):
        clicked = event.type == MOUSEBUTTONDOWN and self.playB.collidepoint(pygame.mouse.get_pos())
        pressed = event.type == KEYDOWN and event.key == K_a
        return clicked or pressed

    def check_act_hit(self, event):
        clicked = event.type == MOUSEBUTTONDOWN and self.hitB.collidepoint(pygame.mouse.get_pos())
        pressed = event.type == KEYDOWN and event.key == K_h

        return not self.game.game_over() and not self.autoPlay and (clicked or pressed)

    def check_act_stand(self, event):
        clicked = event.type == MOUSEBUTTONDOWN and self.standB.collidepoint(pygame.mouse.get_pos())
        pressed = event.type == KEYDOWN and event.key == K_s

        return not self.game.game_over() and not self.autoPlay and (clicked or pressed)

    def check_reset(self, event):
        clicked = event.type == MOUSEBUTTONDOWN
        pressed = event.type == KEYDOWN

        return self.game.game_over() and not self.autoPlay and (clicked or pressed)
    
    def handle_user_action(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            # Clicking the white buttons can start or pause the learning processes
            elif self.check_act_MC(event):
                self.autoMC = not self.autoMC
            elif self.check_act_TD(event):
                self.autoTD = not self.autoTD
            elif self.check_act_QL(event):
                self.autoQL = not self.autoQL
            elif self.check_act_autoplay(event):
                self.autoPlay = not self.autoPlay
            
            elif self.check_act_hit(event):
                self.game.act_hit()
                
            elif self.check_act_stand(event):
                self.game.act_stand()

            elif self.check_reset(event):
                self.game.update_stats()
                self.game.reset()
            
            if event.type == KEYDOWN:
                if event.key == K_x:
                    pygame.quit()
                    sys.exit()
                if event.key == K_1:
                    self.agent.save("saved")
                elif event.key == K_2:
                    self.agent.load("saved")
    
    @staticmethod
    def draw_label_hl(surface, pos, label, padding=PADDING, bg=WHITE, wd=2, border=True):
        specs = [(bg, 0)]
        if border:
            specs += [(BLACK, wd)]
        for color, width in specs:
            x = pos[0] - padding
            y = pos[1] - padding
            w = label.get_width() + padding * 2
            h = label.get_height() + padding * 2
            pygame.draw.rect(surface, color, (x, y, w, h), width)

    def render_board(self):
        winTxt = self.font.render('Wins: {}'.format(self.game.winNum), 1, WHITE)
        loseTxt = self.font.render('Losses: {}'.format(self.game.loseNum), 1, WHITE)
        if self.game.loseNum == 0 and self.game.winNum == 0:
            win_rate = 0.
        else:
            win_rate = self.game.winNum / (self.game.winNum + self.game.loseNum)
        win_rate_txt = self.font.render('Win rate: {:.2f}%'.format(win_rate * 100), 1, WHITE)
            
        button_colors = [RED, GREEN]
        self.MCB = pygame.draw.rect(self.background, button_colors[self.autoMC], (180, OPS_BTN_Y, 75, OPS_BTN_HEIGHT))
        self.TDB = pygame.draw.rect(self.background, button_colors[self.autoTD], (265, OPS_BTN_Y, 75, OPS_BTN_HEIGHT))
        self.QLB = pygame.draw.rect(self.background, button_colors[self.autoQL], (350, OPS_BTN_Y, 75, OPS_BTN_HEIGHT))
        self.playB = pygame.draw.rect(self.background, button_colors[self.autoPlay], (435, OPS_BTN_Y, 115, OPS_BTN_HEIGHT))


        state_info = self.font.render('State (user_sum, user_has_Ace, dealer_first) ={}'.format(self.game.state), 1, BLACK)
        MCU = self.font.render('Current state\'s (MC value, #samples): ({:f}, {})'.format(
            self.agent.MC_values[self.game.state], 
            self.agent.N_MC[self.game.state]
        ), 1, BLACK)

        TDU = self.font.render('Current state\'s (TD value, #samples): ({:f}, {})'.format(
            self.agent.TD_values[self.game.state], 
            self.agent.N_TD[self.game.state]
        ), 1, BLACK)

        QV = self.font.render('Current stats\'s Q values ([Hit, Stand], #samples): ([{:f},{:f}], {})'.format(
            self.agent.Q_values[self.game.state][0],
            self.agent.Q_values[self.game.state][1],
            self.agent.N_Q[self.game.state],
        ) , 1, BLACK)
        
        self.screen.blit(self.background, (0, 0))
        self.screen.blit(self.hitTxt, (37, OPS_TXT_Y))
        self.screen.blit(self.standTxt, (113, OPS_TXT_Y))
        self.screen.blit(self.MCTxt[self.autoMC], (190, OPS_TXT_Y))
        self.screen.blit(self.TDTxt[self.autoTD], (277, OPS_TXT_Y))
        self.screen.blit(self.QLTxt[self.autoQL], (359, OPS_TXT_Y))
        self.screen.blit(self.playTxt[self.autoPlay], (444, OPS_TXT_Y))
        self.screen.blit(self.ops_instr, (OPS_INSTR_X, OPS_INSTR_Y))

        for width, color in [(0, WHITE), (2, BLACK)]:
            pygame.draw.rect(self.screen, color,
                (10, 170, 600, 95), width)
        self.screen.blit(state_info, (20, 180))
        self.screen.blit(MCU, (20, 200))
        self.screen.blit(TDU, (20, 220))
        self.screen.blit(QV, (20, 240))

        self.screen.blit(winTxt, (520, 23))
        self.screen.blit(loseTxt, (520, 48))
        self.screen.blit(win_rate_txt, (520, 73))

        self.screen.blit(self.save_instr, (350, 380))
        self.screen.blit(self.load_instr, (350, 400))

        for i, card in enumerate(self.game.userCard):
            x = 10 + i * 20
            self.screen.blit(self.card_imgs[card], (x, USR_CARD_HEIGHT))
        
        if self.game.game_over() or self.game.stand:
            if self.game.state == WIN_STATE:
                result_txt = self.gameoverTxt[0]
            else:
                result_txt = self.gameoverTxt[1]
            self.draw_label_hl(self.screen, GAME_OVER_TEXT_POS, result_txt)
            self.screen.blit(result_txt, GAME_OVER_TEXT_POS)
            for i, card in enumerate(self.game.dealCard):
                x = 10 + i * 20
                self.screen.blit(self.card_imgs[card], (x, 10))
        else:
            self.screen.blit(self.card_imgs[self.game.dealCard[0]], (10, 10))
            self.screen.blit(self.cBack, (30, 10))

        pygame.display.update()
Example #44
0
'''
Andrew Dong
setup.py:
    Create a working poker bot that initially only knows the rules of texas
    hold'em. It knows nothing of a strong hand or anything, but will learn
    through use of reinforcement learning on different hand strengths made
    at random.
    Note: Hitting esc during execution will allow the bot to leave the loop
    and save the results there. Useful for allowing bot to run indefinitely
'''

from game import Game

main = Game()

# because I don't think python allows me to search for a list within a list
# so seperate various parts of a state
statesPocket = []
probPocket = []
encounteredPocket = []
statesFlop = []
probFlop = []
encounteredFlop = []
statesTurn = []
probTurn = []
encounteredTurn = []
statesRiver = []
probRiver = []
encounteredRiver = []

# file inputs
Example #45
0
__author__ = 'JuanDavid'

from player import Player
from game import Game
from board import Board
from piece import Piece
from aima_method import SeachMethod
from random import randint
from load import Load
import json

p_one = Player(Player.RANDOM, Piece.WHITE)
p_two = Player(Player.SMARTEST, Piece.BLACK)

game = Game(p_one, p_two)
board = Board(6, 4)
board.initialize_default_board()
print "Que empieze el juego"

while game.is_terminal(board) is False:

    posible_movements = game.successors(board, game.get_player_turn())
    search = SeachMethod(SeachMethod.AIMA_ALPHABETA_SEARCH, 1)
    move = search.search(board, game)
    print board.get_piece_in_pos(move[0][0], move[0][1]).to_string()
    board.move_piece(move[0][0], move[0][1], move[1][0], move[1][1])
    game.change_turn()
    print board.to_string()

game.to_db(board, game.get_enemy_player())
import pygame
from game import Game, Settings

if __name__ == '__main__':
    settings = Settings(20, 30, 30)
    game = Game(settings)
    game.init()
    game.loop()
Example #47
0
import pygame
from game import Game

pygame.init()

# Générer la fenêtre du jeu
pygame.display.set_caption("Comet fall game")
screen = pygame.display.set_mode((1080, 720))

# importer de charger l'arrire plan de notre jeu
background = pygame.image.load('assets/bg.jpg')

# charger le jeu
game = Game()

running = True

# Boucle de jeu
while running:

    # Appliquer l'arrière plan du jeu
    screen.blit(background,
                (0, -200))  # applique une surface à un endroit de la fenetre

    # appliquer l'image du joueur
    screen.blit(game.player.image, game.player.rect)

    # Vérifier si le joueur souhaite aller à droite ou à gauche
    if game.pressed.get(
            pygame.K_RIGHT
    ) and game.player.rect.x + game.player.rect.width < screen.get_width():
class DeductoActivity(activity.Activity):
    """ Logic puzzle game """
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        try:
            super(DeductoActivity, self).__init__(handle)
        except dbus.exceptions.DBusException as e:
            _logger.error(str(e))

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self.level = 0
        self._correct = 0
        self._playing = True
        self._game_over = False

        self._python_code = None

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)

        self._sharing = False
        self._initiating = False
        self._setup_presence_service()

        if 'level' in self.metadata:
            self.level = int(self.metadata['level'])
            self.status.set_label(_('Resuming level %d') % (self.level + 1))
            self._game.show_random()
        else:
            self._game.new_game()

    def _setup_toolbars(self):
        """ Setup the toolbars. """

        self.max_participants = 4

        toolbox = ToolbarBox()

        # Activity toolbar
        activity_button = ActivityToolbarButton(self)

        toolbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self.set_toolbar_box(toolbox)
        toolbox.show()
        self.toolbar = toolbox.toolbar

        self._new_game_button = button_factory('new-game',
                                               self.toolbar,
                                               self._new_game_cb,
                                               tooltip=_('Start a new game.'))

        separator_factory(toolbox.toolbar, False, True)

        self._true_button = button_factory(
            'true',
            self.toolbar,
            self._true_cb,
            tooltip=_('The pattern matches the rule.'))

        self._false_button = button_factory(
            'false',
            self.toolbar,
            self._false_cb,
            tooltip=_('The pattern does not match the rule.'))

        separator_factory(toolbox.toolbar, False, True)

        self._example_button = button_factory(
            'example',
            self.toolbar,
            self._example_cb,
            tooltip=_('Explore some examples.'))

        self.status = label_factory(self.toolbar, '', width=300)

        separator_factory(toolbox.toolbar, True, False)

        self._gear_button = button_factory('view-source',
                                           self.toolbar,
                                           self._gear_cb,
                                           tooltip=_('Load a custom level.'))

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

    def _new_game_cb(self, button=None):
        ''' Start a new game. '''
        if (not self._sharing) or self._initiating:
            self._game_over = False
            self._correct = 0
            self.level = 0
            if not self._playing:
                self._example_cb()
            self._game.new_game()
            if self._initiating:
                _logger.debug('sending new game and new grid')
                self._send_new_game()
                self._send_new_grid()
            self.status.set_label(_('Playing level %d') % (self.level + 1))
        else:
            self.status.set_label(_('Only sharer can start a new game.'))

    def _test_for_game_over(self):
        ''' If we are at maximum levels, the game is over '''
        if self.level == self._game.max_levels:
            self.level = 0
            self._game_over = True
            self.status.set_label(_('Game over.'))
        else:
            self.status.set_label(_('Playing level %d') % (self.level + 1))
            self._correct = 0
            if (not self._sharing) or self._initiating:
                self._game.show_random()
                if self._initiating:
                    self._send_new_grid()

    def _true_cb(self, button=None):
        ''' Declare pattern true or show an example of a true pattern. '''
        if self._game_over:
            if (not self._sharing) or self._initiating:
                self.status.set_label(_('Click on new game button to begin.'))
            else:
                self.status.set_label(
                    _('Wait for sharer to start ' + 'a new game.'))
            return
        if self._playing:
            if self._game.this_pattern:
                self._correct += 1
                if self._correct == 5:
                    self.level += 1
                    self._test_for_game_over()
                    self.metadata['level'] = str(self.level)
                else:
                    self.status.set_label(
                        _('%d correct answers.') % (self._correct))
                    if (not self._sharing) or self._initiating:
                        self._game.show_random()
                        if self._initiating:
                            self._send_new_grid()
            else:
                self.status.set_label(_('Pattern was false.'))
                self._correct = 0
            if (button is not None) and self._sharing:
                self._send_true_button_click()
        else:
            self._game.show_true()

    def _false_cb(self, button=None):
        ''' Declare pattern false or show an example of a false pattern. '''
        if self._game_over:
            if (not self._sharing) or self._initiating:
                self.status.set_label(_('Click on new game button to begin.'))
            else:
                self.status.set_label(
                    _('Wait for sharer to start ' + 'a new game.'))
            return
        if self._playing:
            if not self._game.this_pattern:
                self._correct += 1
                if self._correct == 5:
                    self.level += 1
                    self._test_for_game_over()
                else:
                    self.status.set_label(
                        _('%d correct answers.') % (self._correct))
                    if (not self._sharing) or self._initiating:
                        self._game.show_random()
                        if self._initiating:
                            self._send_new_grid()
            else:
                self.status.set_label(_('Pattern was true.'))
                self._correct = 0
            if (button is not None) and self._sharing:
                self._send_false_button_click()
        else:
            self._game.show_false()

    def _example_cb(self, button=None):
        ''' Show examples or resume play of current level. '''
        if self._playing:
            self._example_button.set_icon_name('resume-play')
            self._example_button.set_tooltip(_('Resume play'))
            self._true_button.set_tooltip(
                _('Show a pattern that matches the rule.'))
            self._false_button.set_tooltip(
                _('Show a pattern that does not match the rule.'))
            Button1 = '☑'
            Button2 = '☒'
            self.status.set_label(
                _("Explore patterns with the {} and {} buttons.".format(
                    Button1, Button2)))
            self._playing = False
        else:
            self._example_button.set_icon_name('example')
            self._example_button.set_tooltip(_('Explore some examples.'))
            self._true_button.set_tooltip(_('The pattern matches the rule.'))
            self._false_button.set_tooltip(
                _('The pattern does not match the rule.'))
            self.status.set_label(_('Playing level %d') % (self.level + 1))
            self._playing = True
            self._correct = 0

    def _gear_cb(self, button=None):
        ''' Load a custom level. '''
        self.status.set_text(
            _('Load a "True" pattern generator from the journal'))
        self._chooser('org.laptop.Pippy', self._load_python_code_from_journal)
        if self._python_code is None:
            return
        LEVELS_TRUE.append(self._python_code)
        self.status.set_text(
            _('Load a "False" pattern generator from the journal'))
        self._chooser('org.laptop.Pippy', self._load_python_code_from_journal)
        LEVELS_FALSE.append(self._python_code)
        if self._python_code is None:
            return
        self.status.set_text(_('New level added'))
        self._game.max_levels += 1

    def _load_python_code_from_journal(self, dsobject):
        ''' Read the Python code from the Journal object '''
        self._python_code = None
        try:
            _logger.debug("opening %s " % dsobject.file_path)
            file_handle = open(dsobject.file_path, "r")
            self._python_code = file_handle.read()
            file_handle.close()
        except IOError:
            _logger.debug("couldn't open %s" % dsobject.file_path)

    def _chooser(self, filter, action):
        ''' Choose an object from the datastore and take some action '''
        chooser = None
        try:
            chooser = ObjectChooser(parent=self, what_filter=filter)
        except TypeError:
            chooser = ObjectChooser(
                None, self,
                Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT)
        if chooser is not None:
            try:
                result = chooser.run()
                if result == Gtk.ResponseType.ACCEPT:
                    dsobject = chooser.get_selected_object()
                    action(dsobject)
                    dsobject.destroy()
            finally:
                chooser.destroy()
                del chooser

    # Collaboration-related methods

    # The sharer sends patterns and everyone shares whatever vote is
    # cast first among all the sharer and joiners.

    def _setup_presence_service(self):
        ''' Setup the Presence Service. '''
        self.pservice = presenceservice.get_instance()
        self._initiating = None  # sharing (True) or joining (False)

        owner = self.pservice.get_owner()
        self.owner = owner
        self._share = ""
        self.connect('shared', self._shared_cb)
        self.connect('joined', self._joined_cb)

    def _shared_cb(self, activity):
        ''' Either set up initial share...'''
        self._new_tube_common(True)

    def _joined_cb(self, activity):
        ''' ...or join an exisiting share. '''
        self._new_tube_common(False)

    def _new_tube_common(self, sharer):
        ''' Joining and sharing are mostly the same... '''
        if self._shared_activity is None:
            _logger.debug("Error: Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()")
            return

        self._initiating = sharer
        self._sharing = True

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan

        self.tubes_chan[
            TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES].connect_to_signal(
                'NewTube', self._new_tube_cb)

        if sharer:
            _logger.debug('This is my activity: making a tube...')
        else:
            _logger.debug('I am joining an activity: waiting for a tube...')
            self.tubes_chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES].ListTubes(
                reply_handler=self._list_tubes_reply_cb,
                error_handler=self._list_tubes_error_cb)

    def _list_tubes_reply_cb(self, tubes):
        ''' Reply to a list request. '''
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        ''' Log errors. '''
        _logger.debug('Error: ListTubes() failed: %s' % (e))

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        ''' Create a new tube. '''
        _logger.debug('New tube: ID=%d initator=%d type=%d service=%s \
params=%r state=%d' % (id, initiator, type, service, params, state))

        if (type == TelepathyGLib.TubeType.DBUS and service == SERVICE):
            if state == TelepathyGLib.TubeState.LOCAL_PENDING:
                self.tubes_chan[
                    TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES].AcceptDBusTube(id)

            tube_conn = TubeConnection(
                self.conn,
                self.tubes_chan[TelepathyGLib.IFACE_CHANNEL_TYPE_TUBES],
                id,
                group_iface=self.text_chan[
                    TelepathyGLib.IFACE_CHANNEL_INTERFACE_GROUP])

            self.chattube = ChatTube(tube_conn, self._initiating,
                                     self._event_received_cb)

    def _setup_dispatch_table(self):
        ''' Associate tokens with commands. '''
        self._processing_methods = {
            'n': [self._receive_new_game, 'new game'],
            'g': [self._receive_new_grid, 'get a new grid'],
            't': [self._receive_true_button_click, 'get a true button press'],
            'f': [
                self._receive_false_button_click,
                'get a false ' + 'button press'
            ],
        }

    def _event_received_cb(self, event_message):
        ''' Data from a tube has arrived. '''
        if len(event_message) == 0:
            return
        try:
            command, payload = event_message.split('|', 2)
        except ValueError:
            _logger.debug('Could not split event message %s' % (event_message))
            return
        self._processing_methods[command][0](payload)

    def _send_new_game(self):
        '''
        Send a new game message to all players
        (only sharer sends grids)
        '''
        self._send_event('n| ')

    def _receive_new_game(self, payload):
        ''' Receive a new game notification from the sharer. '''
        self._game_over = False
        self._correct = 0
        self.level = 0
        if not self._playing:
            self._example_cb()
        self.status.set_label(_('Playing level %d') % (self.level + 1))

    def _send_new_grid(self):
        ''' Send a new grid to all players (only sharer sends grids) '''
        self._send_event('g|%s' % (json_dump(self._game.save_grid())))

    def _receive_new_grid(self, payload):
        ''' Receive a grid from the sharer. '''
        (dot_list, boolean) = json_load(payload)
        self._game.restore_grid(dot_list, boolean)

    def _send_true_button_click(self):
        ''' Send a true click to all the players '''
        self._send_event('t|t')

    def _receive_true_button_click(self, payload):
        ''' When a button is clicked, everyone should react. '''
        self._playing = True
        self._true_cb()

    def _send_false_button_click(self):
        ''' Send a false click to all the players '''
        self._send_event('f|f')

    def _receive_false_button_click(self, payload):
        ''' When a button is clicked, everyone should react. '''
        self._playing = True
        self._false_cb()

    def _send_event(self, entry):
        ''' Send event through the tube. '''
        if hasattr(self, 'chattube') and self.chattube is not None:
            self.chattube.SendText(entry)
class TrainPipeline():
    def __init__(self):
        # params of the board and the game
        self.board_width = 8
        self.board_height = 8
        self.n_in_row = 5
        self.board = Board(width=self.board_width,
                           height=self.board_height,
                           n_in_row=self.n_in_row)
        self.game = Game(self.board)
        # training params

        self.temp = 1.0  # the temperature param
        self.n_playout = 400  # num of simulations for each move
        self.c_puct = 5
        self.buffer_size = 10000
        self.batch_size = 512  # mini-batch size for training
        self.data_buffer = deque(maxlen=self.buffer_size)
        self.play_batch_size = 1
        self.epochs = 3  # num of train_steps for each update
        self.check_freq = 50
        self.game_batch_num = 1500
        self.best_win_ratio = 0.0
        # num of simulations used for the pure mcts, which is used as the opponent to evaluate the trained policy
        self.pure_mcts_playout_num = 1000

        # start training from a new policy-value net
        self.policy_value_net = PolicyValueNet(self.board_width,
                                               self.board_height)
        self.mcts_player = MCTSPlayer(self.policy_value_net.policy_value_fn,
                                      c_puct=self.c_puct,
                                      n_playout=self.n_playout,
                                      is_selfplay=1)

    def get_equi_data(self, play_data):
        """
        augment the data set by rotation and flipping
        play_data: [(state, mcts_prob, winner_z), ..., ...]"""
        extend_data = []
        for state, mcts_porb, winner in play_data:
            for i in [1, 2, 3, 4]:
                # rotate counterclockwise
                equi_state = np.array([np.rot90(s, i) for s in state])
                equi_mcts_prob = np.rot90(
                    np.flipud(
                        mcts_porb.reshape(self.board_height,
                                          self.board_width)), i)
                extend_data.append(
                    (equi_state, np.flipud(equi_mcts_prob).flatten(), winner))
                # flip horizontally
                equi_state = np.array([np.fliplr(s) for s in equi_state])
                equi_mcts_prob = np.fliplr(equi_mcts_prob)
                extend_data.append(
                    (equi_state, np.flipud(equi_mcts_prob).flatten(), winner))
        return extend_data

    def collect_selfplay_data(self, n_games=1):
        """collect self-play data for training"""
        for i in range(n_games):
            winner, play_data = self.game.start_self_play(self.mcts_player,
                                                          temp=self.temp)
            # augment the data
            play_data = self.get_equi_data(play_data)
            self.episode_len = len(play_data) / 8
            self.data_buffer.extend(play_data)

    def policy_update(self):
        """update the policy-value net"""
        mini_batch = random.sample(self.data_buffer, self.batch_size)
        state_batch = [data[0] for data in mini_batch]
        mcts_probs_batch = [data[1] for data in mini_batch]
        winner_batch = [data[2] for data in mini_batch]

        for i in range(self.epochs):
            self.policy_value_net.train_step(state_batch, mcts_probs_batch,
                                             winner_batch)

        loss, entropy = self.policy_value_net.train_step(state_batch,
                                                         mcts_probs_batch,
                                                         winner_batch,
                                                         show_loss=1)
        print(" loss:{:.3f}\n entropy:{:.3f}\n ".format(loss, entropy))

    def policy_evaluate(self, n_games=10):
        """
        Evaluate the trained policy by playing games against the pure MCTS player
        Note: this is only for monitoring the progress of training
        """
        current_mcts_player = MCTSPlayer(self.policy_value_net.policy_value_fn,
                                         c_puct=self.c_puct,
                                         n_playout=self.n_playout)
        pure_mcts_player = MCTS_Pure(c_puct=5,
                                     n_playout=self.pure_mcts_playout_num)
        win_cnt = defaultdict(int)
        for i in range(n_games):
            winner = self.game.start_play(current_mcts_player,
                                          pure_mcts_player,
                                          start_player=i % 2,
                                          is_shown=0)
            win_cnt[winner] += 1
        win_ratio = 1.0 * (win_cnt[1] + 0.5 * win_cnt[-1]) / n_games
        print("num_playouts:{}, win: {}, lose: {}, tie:{}".format(
            self.pure_mcts_playout_num, win_cnt[1], win_cnt[2], win_cnt[-1]))
        return win_ratio

    def run(self):
        """run the training pipeline"""
        try:
            for i in range(self.game_batch_num):
                self.collect_selfplay_data(self.play_batch_size)

                if len(self.data_buffer) > self.batch_size:
                    print("batch i:{}, episode_len:{}".format(
                        i + 1, self.episode_len))
                    self.policy_update()
                # check the performance of the current model,and save the model params
                if (i + 1) % self.check_freq == 0:
                    print("current self-play batch: {}".format(i + 1))
                    self.policy_value_net.saver.save(
                        self.policy_value_net.sess,
                        self.policy_value_net.model_file)
                    win_ratio = self.policy_evaluate()

                    if win_ratio > self.best_win_ratio:
                        print("New best policy!!!!!!!!")
                        self.best_win_ratio = win_ratio
                        #                        self.policy_value_net.saver.save(self.policy_value_net.sess, self.policy_value_net.model_file) # update the best_policy
                        if self.best_win_ratio == 1.0 and self.pure_mcts_playout_num < 5000:
                            self.pure_mcts_playout_num += 100
                            self.best_win_ratio = 0.0
        except KeyboardInterrupt:
            self.policy_value_net.saver.save(self.policy_value_net.sess,
                                             self.policy_value_net.model_file)
            print('\n\rquit')
Example #50
0
class GameMenuServer(PodSixNet.Server.Server):
    def __init__(self, *args, **kwargs):
        PodSixNet.Server.Server.__init__(self, *args, **kwargs)
        self.game = Game()
        self.numPlayers = 0
        self.playerChannels = []  #list of channels
        self.players = []  #list of player object pointers
        self.optionSet = ""  #string identifier used to indicate set of options.

        self.curSugP = None
        self.curSugR = None
        self.curSugW = None

    channelClass = ClientChannel

    def Connected(self, channel, addr):
        print('new connection:', channel)

        if self.numPlayers >= TOTAL_PLAYERS:
            channel.Send({
                "action": "rejected",
                "message": "Too many players!"
            })
        else:
            self.playerChannels.append(channel)
            self.players.append(self.game.addPlayer())
            self.numPlayers += 1

            if self.numPlayers == TOTAL_PLAYERS:
                #Start the game
                self.game.initializeGame()
                for p in range(len(self.playerChannels)):
                    self.sendCards(p)
                    self.playerChannels[p].Send({
                        "action": "startgame",
                        "player": p,
                        "numPlayers": TOTAL_PLAYERS
                    })
                    self.sendMessage("All player's have arrived. Let's begin!",
                                     p)
                self.sendPositions()
                self.sendTurns()

    #tell all clients all board positions
    def sendPositions(self):
        transmission = {"action": "updatePositions"}
        #add players' positions to the transmission
        for p in range(len(self.players)):
            transmission[str(p)] = self.game.getPlayerLocID(p)

        transmission['turn'] = self.game.whoseTurn

        #send entire transmission to each player
        for pc in self.playerChannels:
            pc.Send(transmission)

    #Send generic message to a player's HUD
    def sendMessage(self, message, playerID):
        transmission = {"action": "message", "message": message}
        self.playerChannels[playerID].Send(transmission)

    def sendMessageAll(self, message):
        for p in range(len(self.playerChannels)):
            self.sendMessage(message, p)

    def sendTurns(self):
        turn = self.game.whoseTurn
        for p in range(len(self.players)):
            if turn == p:
                self.sendMessage("Your Turn!", p)
            else:
                message = "Waiting for " + self.game.getPlayerName(
                    turn) + "..."
                self.sendMessage(message, p)

    def sendCards(self, playerID):
        cardsP = self.game.getPlayerCards(playerID, "P")
        print(cardsP)
        transmission = {
            "action": "setCards",
            "cardType": "P",
            "numCards": len(cardsP)
        }
        for c in range(len(cardsP)):
            transmission[str(c)] = cardsP[c]
        self.playerChannels[playerID].Send(transmission)

        cardsR = self.game.getPlayerCards(playerID, "R")
        transmission = {
            "action": "setCards",
            "cardType": "R",
            "numCards": len(cardsR)
        }
        for c in range(len(cardsR)):
            transmission[str(c)] = cardsR[c]
        self.playerChannels[playerID].Send(transmission)

        cardsW = self.game.getPlayerCards(playerID, "W")
        transmission = {
            "action": "setCards",
            "cardType": "W",
            "numCards": len(cardsW)
        }
        for c in range(len(cardsW)):
            transmission[str(c)] = cardsW[c]
        self.playerChannels[playerID].Send(transmission)

    #Send generic options to a player's HUD
    def sendOptions(self, options, playerID, clearOthers=True):
        transmission = {"action": "options", "numOptions": len(options)}
        for o in range(len(options)):
            transmission[str(o)] = options[o]
        self.playerChannels[playerID].Send(transmission)

        #clear all other user's options
        if clearOthers:
            for p in range(self.numPlayers):
                if p != playerID:
                    transmission = {"action": "options", "numOptions": 0}
                    self.playerChannels[p].Send(transmission)

    def clearAllOptions(self):
        for p in range(self.numPlayers):
            transmission = {"action": "options", "numOptions": 0}
            self.playerChannels[p].Send(transmission)

    def selectOption(self, option, playerID):
        if self.optionSet == "ok":
            self.game.incrementTurn()
            self.clearAllOptions()
            self.sendTurns()
        elif self.optionSet == "room":
            if option == 2:
                self.game.incrementTurn()
                self.clearAllOptions()
                self.sendTurns()
                return
            else:
                #cardsL = ROOM_NAMES
                #cardsW = WEAPONS
                if option == 0:
                    self.optionSet = "suggestionP"
                else:
                    self.optionSet = "accusationP"
                self.sendMessage("Who's the muderer?!", playerID)
                self.sendOptions(PLAYER_NAMES[0:TOTAL_PLAYERS], playerID)
        elif self.optionSet == "suggestionP":
            self.curSugP = option
            self.optionSet = "suggestionW"
            self.sendMessage("What was the weapon?", playerID)
            #room must be current room
            self.curSugR = self.game.getPlayerLocID(playerID)
            self.sendOptions(WEAPONS, playerID)
        elif self.optionSet == "suggestionW":
            self.curSugW = option
            self.sendMessageAll(PLAYER_NAMES[playerID] + " suggests: '" +
                                PLAYER_NAMES[self.curSugP] + " in the " +
                                ROOM_NAMES[self.curSugR] + " with the " +
                                WEAPONS[self.curSugW] +
                                "!' Interviewing Witnesses...")
            self.game.makeSuggestion(playerID, self.curSugP, self.curSugR,
                                     self.curSugW)
            self.sendPositions()
            self.clearAllOptions()
            self.disprove(playerID)

        elif self.optionSet == "accusationP":
            self.curSugP = option
            self.optionSet = "accusationL"
            self.sendMessage("Where did they do it?", playerID)
            self.sendOptions(ROOM_NAMES, playerID)
        elif self.optionSet == "accusationL":
            self.curSugR = option
            self.optionSet = "accusationW"
            self.sendMessage("What was the weapon?", playerID)
            self.sendOptions(WEAPONS, playerID)
        elif self.optionSet == "accusationW":
            self.curSugW = option
            self.optionSet = "ok"
            win = self.game.makeAccusation(self.curSugP, self.curSugR,
                                           self.curSugW)
            if win:
                self.clearAllOptions()
                self.sendMessageAll(PLAYER_NAMES[playerID] + " WINS!!")
            else:
                self.clearAllOptions()
                self.sendMessageAll(PLAYER_NAMES[playerID] +
                                    " falsely accused... They lose!")

        elif self.optionSet == "disprove":
            accuser = self.game.whoseTurn
            disprover = playerID
            if self.disproveCardTypes[option] == "P":
                cardText = PLAYER_NAMES[self.curSugP]
            elif self.disproveCardTypes[option] == "R":
                cardText = ROOM_NAMES[self.curSugR]
            elif self.disproveCardTypes[option] == "W":
                cardText = WEAPONS[self.curSugW]

            self.sendMessage(
                PLAYER_NAMES[disprover] + " shows you a card: " + cardText,
                accuser)
            self.sendMessage(
                "You show " + PLAYER_NAMES[accuser] + " a card: " + cardText,
                disprover)
            self.clearAllOptions()
            self.optionSet = "ok"
            self.sendOptions(["OK"], accuser)

    def disprove(self, accuser):
        disprover = self.game.disproverTurn
        #if disprove turn makes it back to the accuser
        if disprover == accuser:
            self.sendMessageAll("Suggesting was not disproven!!")
            self.clearAllOptions()
            self.game.incrementTurn()
            self.sendTurns()
        else:
            self.optionSet = "disprove"
            #get from game somehow??
            self.disproveCardTypes = self.game.getSugCards()
            options = []
            for i in range(len(self.disproveCardTypes)):
                if self.disproveCardTypes[i] == "P":
                    options.append("Show card: " + PLAYER_NAMES[self.curSugP])
                elif self.disproveCardTypes[i] == "R":
                    options.append("Show card: " + ROOM_NAMES[self.curSugR])
                elif self.disproveCardTypes[i] == "W":
                    options.append("Show card: " + WEAPONS[self.curSugW])

            if len(options) == 0:
                self.game.rotateDisprover()
                self.disprove(accuser)
            else:
                self.sendOptions(options, disprover)
Example #51
0
# example code for students of B4B33RPH course
# Author: Tomas Svoboda, and the RPH team

from game import Game

# assuming your player is in player.py as required
# https://cw.fel.cvut.cz/wiki/courses/b4b33rph/cviceni/veznovo_dilema/specifikace
import player

# define the payoff matrix; see game.py for detailed explanation of this matrix
payoff_matrix = (((4, 4), (1, 6)), ((6, 1), (2, 2)))

# define the number of iterations
number_of_iterations = 20

# create the players
playerA = player.MyPlayer(payoff_matrix)
# at the moment, me and the opponent are of the same type
playerB = player.MyPlayer(payoff_matrix)

# create the game instance
my_game = Game(playerA, playerB, payoff_matrix, number_of_iterations)
# run game
my_game.run()

# get scores
scores = my_game.get_players_payoffs()

# display scores
print('playerA got:', scores[0], '\nplayerB got:', scores[1])
Example #52
0
def main():

    option = utilities.chooseGameMode()

    game = Game()

    # Useful variables for the game drawing
    circlePositions = []
    BLACK = (0, 0, 0)
    GREY = (200, 200, 200)
    RED = (255, 0, 0)
    WHITE = (255, 255, 255)

    # initialize the pygame module
    pygame.init()

    SQUARESIZE = 100
    width = 850
    height = 600
    size = (width, height)
    # load and set the logo
    pygame.display.set_caption("Nine Men's Morris")
    # create a surface on screen that has the size of 240 x 180
    screen = pygame.display.set_mode(size)

    def draw_game(option):
        screen.fill(GREY)
        draw_lines()
        draw_circles()
        writeGameInfo(option)

    def draw_lines():
        for i in range(3):
            for k in range(4):
                a = 50 + (75 * i)
                b = 550 - (75 * i)
                pygame.draw.line(screen, BLACK, (a, a), (a, b))
                pygame.draw.line(screen, BLACK, (a, a), (b, a))
                pygame.draw.line(screen, BLACK, (b, a), (b, b))
                pygame.draw.line(screen, BLACK, (a, b), (b, b))

        pygame.draw.line(screen, BLACK, (300, 50), (300, 200))
        pygame.draw.line(screen, BLACK, (50, 300), (200, 300))
        pygame.draw.line(screen, BLACK, (300, 550), (300, 400))
        pygame.draw.line(screen, BLACK, (550, 300), (400, 300))

    def draw_circle(a, b):
        index, ring = get_circle_index(a, b)
        if game.selecti(index, ring).getValue() == 0:
            pygame.draw.circle(screen, BLACK, (a, b), 5)
        elif game.selecti(index, ring).getValue() == 1:
            pygame.draw.circle(screen, BLACK, (a, b), 20)
        else:
            pygame.draw.circle(screen, WHITE, (a, b), 20)

    def draw_circles():
        for i in range(3):
            a = 50 + (75 * i)
            b = 550 - (75 * i)
            draw_circle(a, a)
            draw_circle(300, a)
            draw_circle(b, a)
            draw_circle(a, b)
            draw_circle(300, b)
            draw_circle(b, b)
            draw_circle(a, 300)
            draw_circle(a, b)
            draw_circle(b, 300)

    def writeGameInfo(option):
        writeText("Black Pieces: ", BLACK, 600, 100)
        writeText(str(game.getPiecesOffBoard(1)), BLACK, 750, 100)
        writeText("White Pieces:", BLACK, 600, 150)
        writeText(str(game.getPiecesOffBoard(2)), BLACK, 750, 150)
        if option == 1:
            if game.player == 1:
                writeText("PLACE A BLACK PIECE", RED, 600, 300)
            else:
                writeText("PLACE A WHITE PIECE", RED, 600, 300)
        elif option == 2:
            if game.player == 1:
                writeText("MOVE A BLACK PIECE", RED, 600, 300)
            else:
                writeText("MOVE A WHITE PIECE", RED, 600, 300)
        elif option == 3:
            if game.player == 1:
                writeText("REMOVE A WHITE PIECE", RED, 600, 300)
            else:
                writeText("REMOVE A BLACK PIECE", RED, 600, 300)

    def draw_game_result(winner):
        if winner == 1:  # black wins
            screen.fill(WHITE)
            writeText("BLACK WINS", BLACK, 200, 250, 100)
        else:
            screen.fill(BLACK)
            writeText("WHITE WINS", WHITE, 200, 250, 100)

    def writeText(message, color, px, py, size=30):
        myfont = pygame.font.SysFont("Comic Sans MS", size)
        label = myfont.render(message, 1, color)
        screen.blit(label, (px, py))

    def create_circle_coords():
        for i in range(3):
            a = 50 + (i * 75)
            b = 550 - (i * 75)
            newRing = [(a, a), (300, a), (b, a), (b, 300), (b, b), (300, b),
                       (a, b), (a, 300)]
            circlePositions.append(newRing)

    def get_circle_index(mx, my):
        r = 0
        for ring in circlePositions:
            c = 0
            for order in ring:
                if mx >= (order[0] - 25) and mx <= (order[0] + 25) and my >= (
                        order[1] - 25) and my <= (order[1] + 25):
                    return (c, r)
                c += 1
            r += 1
        return (-1, -1)

    def AiVsAi():

        running = 0

        placing_phase = 0
        moving_phase = 0
        can_remove = 0
        is_moving = 0
        movingIndex = -1
        movingRing = -1
        movingIndexTo = -1
        movingRingTo = -1

        moving_phase2 = 0
        can_remove2 = 0
        is_moving2 = 0
        movingIndex2 = -1
        movingRing2 = -1
        movingIndexTo2 = -1
        movingRingTo2 = -1

        depth = 2

        while running == 0:
            if game.player == 1:
                running, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo = AiPlay(
                    depth, placing_phase, moving_phase, can_remove, is_moving,
                    movingIndex, movingRing, movingIndexTo, movingRingTo)
            else:
                running, placing_phase, moving_phase2, can_remove2, is_moving2, movingIndex2, movingRing2, movingIndexTo2, movingRingTo2 = AiPlay(
                    depth, placing_phase, moving_phase2, can_remove2,
                    is_moving2, movingIndex2, movingRing2, movingIndexTo2,
                    movingRingTo2)
            pygame.display.update()
        return running

    def humanVsHuman():

        running = 0

        placing_phase = 0
        moving_phase = 0
        can_remove = 0
        is_moving = 0
        movingIndex = -1
        movingRing = -1

        while running == 0:

            running, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing = humanPlay(
                placing_phase, moving_phase, can_remove, is_moving,
                movingIndex, movingRing)

        return running

    def humanVsAi():

        running = 0

        placing_phase = 0
        moving_phase = 0
        can_remove = 0
        is_moving = 0
        movingIndex = -1
        movingRing = -1
        movingIndexTo = -1
        movingRingTo = -1

        depth = 1

        while running == 0:
            if game.player == 1:
                running, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing = humanPlay(
                    placing_phase, moving_phase, can_remove, is_moving,
                    movingIndex, movingRing)
            else:
                running, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo = AiPlay(
                    depth, placing_phase, moving_phase, can_remove, is_moving,
                    movingIndex, movingRing, movingIndexTo, movingRingTo)
            time.sleep(2)
        return running

    def AiPlay(depth, placing_phase, moving_phase, can_remove, is_moving,
               movingIndex, movingRing, movingIndexTo, movingRingTo):
        # Placing pieces phase
        while placing_phase != 18:

            for event in pygame.event.get():

                if (event.type == pygame.QUIT
                        or event.type == pygame.K_ESCAPE):
                    self.running = False
                    sys.exit()

                if can_remove == 1:  # remove a piece
                    minimax_values = game.minimax(depth, -math.inf, math.inf,
                                                  True, 4)
                    index = minimax_values[1]
                    ring = minimax_values[2]
                    game.remove(ring, index)
                    can_remove = 0
                    if placing_phase != 18:
                        game.changePlayer()
                        draw_game(1)
                        return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo
                    else:
                        checkWin = game.checkWin()
                        game.changePlayer()
                        draw_game(2)
                        return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo
                else:  # place a piece
                    minimax_values = game.minimax(depth, -math.inf, math.inf,
                                                  True, 1)
                    index = minimax_values[1]
                    ring = minimax_values[2]
                    can_remove = game.place(index, ring)
                    placing_phase += 1
                    if can_remove == 1:
                        draw_game(3)
                        return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo
                    elif placing_phase == 18:
                        checkWin = game.checkWin()
                        game.changePlayer()
                        draw_game(2)
                        return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo
                    else:
                        game.changePlayer()
                        draw_game(1)
                        return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo

        # Moving pieces phase
        while moving_phase != 1:

            for event in pygame.event.get():

                if (event.type == pygame.QUIT
                        or event.type == pygame.K_ESCAPE):
                    running = False
                    sys.exit()

                if can_remove == 1:  # remove a piece
                    minimax_values = game.minimax(depth, -math.inf, math.inf,
                                                  True, 4)
                    index = minimax_values[1]
                    ring = minimax_values[2]
                    game.remove(ring, index)
                    can_remove = 0
                    checkWin = game.checkWin()
                    game.changePlayer()
                    draw_game(2)
                    return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo

                elif is_moving == 0:  # choose a piece to move
                    if game.countPieces(game.player) == 3:
                        minimax_values = game.minimax(depth, -math.inf,
                                                      math.inf, True, 3)
                    else:
                        minimax_values = game.minimax(depth, -math.inf,
                                                      math.inf, True, 2)

                    print(minimax_values)

                    index = minimax_values[1]
                    ring = minimax_values[2]
                    index_to = minimax_values[3]
                    ring_to = minimax_values[4]

                    is_moving = 1
                    movingIndex = index
                    movingRing = ring
                    movingIndexTo = index_to
                    movingRingTo = ring_to
                    return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo

                else:  # choose where to move the piece
                    movingResult = game.move(movingIndex, movingRing,
                                             movingIndexTo, movingRingTo)
                    if movingResult != 0:
                        is_moving = 0
                        movingIndex = -1
                        movingRing = -1
                        movingIndexTo = -1
                        movingRingTo = -1
                        if movingResult == 2:
                            can_remove = 1
                            draw_game(3)
                            return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo
                        else:
                            checkWin = game.checkWin()
                            game.changePlayer()
                            draw_game(2)
                            return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing, movingIndexTo, movingRingTo
                pygame.display.update()

    def humanPlay(placing_phase, moving_phase, can_remove, is_moving,
                  movingIndex, movingRing):
        # Placing pieces phase
        while placing_phase != 18 or can_remove == 1:

            for event in pygame.event.get():

                if (event.type == pygame.QUIT
                        or event.type == pygame.K_ESCAPE):
                    self.running = False
                    sys.exit()

                if can_remove == 1:  # remove a piece
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        mx, my = pygame.mouse.get_pos()
                        index, ring = get_circle_index(mx, my)
                        if index != -1:
                            value = game.selecti(index, ring).getValue()
                            if value == game.getNextPlayer(game.player):
                                game.remove(ring, index)
                                can_remove = 0
                                if placing_phase != 18:
                                    game.changePlayer()
                                    draw_game(1)
                                    return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing
                                else:
                                    checkWin = game.checkWin()
                                    game.changePlayer()
                                    draw_game(2)
                                    return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing
                else:  # place a piece
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        mx, my = pygame.mouse.get_pos()
                        index, ring = get_circle_index(mx, my)
                        if index != -1:
                            value = game.selecti(index, ring).getValue()
                            if value == 0:
                                can_remove = game.place(index, ring)
                                placing_phase += 1
                                if can_remove == 1:
                                    draw_game(3)
                                    return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing
                                elif placing_phase == 18:
                                    checkWin = game.checkWin()
                                    game.changePlayer()
                                    draw_game(2)
                                    return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing
                                else:
                                    game.changePlayer()
                                    draw_game(1)
                                    return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing

                pygame.display.update()

        # Moving pieces phase
        while moving_phase != 1:

            for event in pygame.event.get():

                if (event.type == pygame.QUIT
                        or event.type == pygame.K_ESCAPE):
                    running = False
                    sys.exit()

                if can_remove == 1:  # remove a piece
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        mx, my = pygame.mouse.get_pos()
                        index, ring = get_circle_index(mx, my)
                        if index != -1:
                            value = game.selecti(index, ring).getValue()
                            if value != game.player and value != 0:
                                game.remove(ring, index)
                                can_remove = 0
                                checkWin = game.checkWin()
                                game.changePlayer()
                                draw_game(2)
                                return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing

                elif is_moving == 0:  # choose a piece to move
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        mx, my = pygame.mouse.get_pos()
                        index, ring = get_circle_index(mx, my)
                        if index != -1:
                            value = game.selecti(index, ring).getValue()
                            if value == game.player:
                                if game.countPieces(game.player) == 3 or len(
                                        game.pieceMoves(index, ring)) != 0:
                                    is_moving = 1
                                    movingIndex = index
                                    movingRing = ring
                                    return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing

                else:  # choose where to move the piece
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        mx, my = pygame.mouse.get_pos()
                        index, ring = get_circle_index(mx, my)
                        if index != -1:
                            value = game.selecti(index, ring).getValue()
                            if value == 0:
                                movingResult = game.move(
                                    movingIndex, movingRing, index, ring)
                                if movingResult != 0:
                                    is_moving = 0
                                    movingIndex = -1
                                    movingRing = -1
                                    if movingResult == 2:
                                        can_remove = 1
                                        draw_game(3)
                                        return 0, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing
                                    else:
                                        checkWin = game.checkWin()
                                        game.changePlayer()
                                        draw_game(2)
                                        return checkWin, placing_phase, moving_phase, can_remove, is_moving, movingIndex, movingRing
                pygame.display.update()

    def startGame():
        create_circle_coords()
        draw_game(1)
        pygame.display.update()

    def endGame(winner):
        draw_game_result(winner)
        pygame.display.update()
        time.sleep(5)
        sys.exit()

    startGame()

    if option == 0:
        running = humanVsHuman()
    elif option == 1:
        running = humanVsAi()
    else:
        running = AiVsAi()

    endGame(running)
Example #53
0
def main():
    pygame.font.init()
    game = Game()
    game.main()
Example #54
0
dark_green = (0, 75, 0)
red = (255, 0, 0)
dark_red = (128, 0, 0)
white = (255, 255, 255)
oswald_light_blue = (146, 193, 233)

# Starting player index
first_player = 0

# Set up the drawing window
game_display = pygame.display.set_mode(
    [sizes.display_width, sizes.display_height])
pygame.display.set_caption('The Oswald Squares')

# Setup game object
game = Game(game_display, sizes, first_player)

# Setup end screen
end_screen = EndScreen(game_display, sizes)

# Text initializations
start_screen_message = Text('PRESS ANY KEY TO START!',
                            2 * sizes.text_size,
                            game_display,
                            sizes.display_width / 2,
                            sizes.display_height - (2 * sizes.text_size),
                            blink=True)

# Image manipulation
start_title = pygame.image.load('./media/hollywood_title.png')
start_title = pygame.transform.scale(start_title,
Example #55
0
class Main(object):
    """main loop of the game"""
    def __init__(self):
        pygame.init()
        # 包括读取设置文件,设置游戏基本属性
        self.initAttr()
        # 传递所需的参数,实例化所包含的各个类
        self.initObj()
        self.initContext()

    def initAttr(self):
        self.width, self.height = WINDOW_WIDTH, WINDOW_HEIGHT
        self.state = STATE.menu
        self.running = True
        self.level = SETLEVEL["DEFAULT_LEVEL"]
        self.channelID = None

    def initObj(self):
        # 设置大小,用于背景图片的缩放
        self.gameNet = GameNet(self)
        self.gameNet.connectToServer()
        self.menu = Menu((self.width, self.height), self)
        self.rules = Rules(self.width, self.height)
        self.setLevel = SetLevel(self.width, self.height)
        self.matching = Matching((self.width, self.height), self)
        self.game = Game(self)
        # finish 界面的大小和游戏界面一样
        self.finish = Finish((self.game.width, self.game.height))

    # 绘制游戏主窗体
    def initContext(self):
        self.screen = pygame.display.set_mode((self.width, self.height), DOUBLEBUF)
        pygame.display.set_caption("Boxes")

        self.clock = pygame.time.Clock();

    def linkSuccess(self):
        print "link success"
        print self.channelID

    def enterMatching(self):
        self.matching.getRooms()

    def enemyComming(self, turn, gameID):
        self.gameID = gameID
        self.game.enemyComming(turn)
        self.game.setHome()

    def joinGame(self, level, gameID, turn):
        self.game = Game(self)
        self.game.gameID = gameID
        self.state = STATE.game
        self.game.setLevel(level)
        self.game.enemyComming(turn)
        self.game.setAway()

    def enterMenu(self):
        self.state = STATE.menu

    # 进入游戏界面事件
    def enterGame(self, level):
        self.game.setLevel(level)
        self.game.initContext()
        self.state = STATE.game

    def startedNewGame(self, level):
        print "open room", level
        self.gameNet.openRoom(level)

    def leaveServer(self, gameID):
        self.gameNet.leaveServer(self.gameID)
        self.state = STATE.menu

    def backToMenu(self):
        self.initContext()
        self.state = STATE.menu

    def addScore(self):
        self.game.addScore()

    def enemyAddScore(self):
        self.game.enemyAddScore()

    def getRooms(self, matching, page, num):
        self.gameNet.getRooms(matching, page, num)

    def update(self):
        self.clock.tick(60)
        self.screen.fill(0)
        self.gameNet.pump()

        if STATE.exit == self.state:
            exit()

        elif STATE.setLevel == self.state:
            var = self.setLevel.draw(self.screen)
            if (var in STATE):
                self.state = var
            else:
                self.startedNewGame(var)
                self.enterGame(var)

        elif STATE.game == self.state:
            self.state = self.game.draw()
            if (self.state != STATE.game):
                self.initContext()

        elif STATE.matching == self.state:
            self.state = self.matching.draw(self.screen)

        elif STATE.menu == self.state:
            self.menu.draw(self.screen)
            self.state = self.menu.clickListener()

        elif STATE.rules == self.state:
            self.rules.draw(self.screen)
            self.state = self.rules.clickListener()

        elif STATE.finish == self.state:
            var = self.finish.draw(self.screen)
            if (var != STATE.finish):
                self.backToMenu()

        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                if STATE.game == self.state:
                    self.gameNet.exitFlag = True
                    self.gameNet.leaveServer(self.game.gameID)
                    sleep(0.5)
                    pygame.quit()
                    exit()
                else:
                    pygame.quit()
                    exit()
                # exit()
            # if (event.type == pygame.KEYDOWN):
            #     if (event.key == pygame.K_ESCAPE):
            #         exit() 
            #         pygame.quit()
        pygame.display.flip()

    def winning(self):
        self.finish.setWin(self.game.gameID)
        self.enterFinish()

    def lost(self):
        self.finish.setLost(self.game.gameID)
        self.enterFinish()

    def drawGame(self):
        self.finish.setDraw(self.game.gameID)
        self.enterFinish()

    def enterFinish(self):
        self.state = STATE.finish

    def run(self):
        while self.running:
            self.update()

    def exit(self):
        pygame.quit()
        exit()
Example #56
0
from console import Console
from controllerIO import Controller
import pyglet as pl
from game import Game
from levelSDK import PackedLevel
from PC import PC

if __name__ == '__main__':
    c = Controller(0, keyboard=True)

    l1 = PackedLevel()
    l1.loadTileSheet("NBIG.png", 80, 80)
    l1.loadBackground("ICE_TOWN_BG.png")
    l1.loadWalls("ICE_TOWN_Tile Layer 2.csv")
    l1.loadOverhead("ICE_TOWN_Tile Layer 3.csv")
    l1.setTextBox("textBackground.png", 0, 0, "super long text " * 100)
    #l1.loadLevelTriggers("ICE_TOWN_Tile Layer 4.csv")
    l1.loadNPCs("ICE_TOWN_Tile Layer 5.csv")
    l1.loadNPCText("..\\json\\test.json")  # ID/text in json
    char = PC("redPC.png", 10, 600, 450, 300, 0, 3, 3, 2, 2, 0, 0)
    g = Game()
    g.setPC(char)
    g.setTitle("Cat Mystery Dungeon")
    s = Console()
    s.set_controller(c)
    g.addLevel(l1.unpackLevel())
    s.loadGame(g)
    s.run()
Example #57
0
    def take_turn(self, game):

        self._drew_card_from_deck = False
        action = None
        all_actions = game.get_available_actions(self)
        self.player_info = game.get_player_info(self)

        print "Scores: %s" % game.get_visible_scores()
        print "Status: %s" % self.player_info

        if game.gui:
            #print 'attempting to display edges'
            game.gui.update(game)
            game.gui.show_destinations(self.player_info.destinations)

        # Loop until there is an action to take.
        while action is None:
            # Ask the user to select a type of action if they have any options.
            if game.get_remaining_actions(self) != 1:
                print ""
                print "Choose a type of action to take:"
                print "0: Draw Card"
                print "1: Draw Tickets"
                print "2: Connect Cities"

                action_type = ConsolePlayer.get_selection()
            else:
                # If there is only one action left, just force the player to draw.
                action_type = 0

            if action_type == 0:
                # Pick from available cards
                face_up_cards = game.get_face_up_cards()

                print ""
                print "Choose draw:"
                print "0: Draw from Deck"

                for i in range(len(face_up_cards)):
                    # Make sure that the user does not have the option to draw wilds.
                    if face_up_cards[
                            i] != Colors.none or game.get_remaining_actions(
                                self) != 1:
                        print "%d: %s" % (i + 1,
                                          Colors.str_card(face_up_cards[i]))

                if game.get_remaining_actions(self) != 1:
                    print "%d: Cancel" % (len(face_up_cards) + 1)

                selection = ConsolePlayer.get_selection()

                if selection == 0:
                    action = DrawDeckAction()
                    self._drew_card_from_deck = True
                elif 0 < selection <= len(face_up_cards):
                    if face_up_cards[
                            selection -
                            1] != Colors.none or game.get_remaining_actions(
                                self) != 1:
                        action = DrawFaceUpAction(selection - 1,
                                                  face_up_cards[selection - 1])
            elif action_type == 1:
                # Draw a destination card
                action = DrawDestinationAction()
            elif action_type == 2:
                # Connect Edges
                edges_seen = set()

                # Find all edges that can be connected with the set of currently available actions.
                for action_iter in all_actions:
                    if action_iter.is_connect():
                        edges_seen.add(action_iter.edge)

                edges_seen = list(edges_seen)
                edges_seen.sort(key=lambda edge: (edge.color, edge.cost))
                if game.gui:
                    #print 'attempting to display edges'
                    game.gui.show_destinations(self.player_info.destinations)
                    game.gui.show_edges(edges_seen)

                # Show options for selection to user.
                print ""
                print "Choose a route to claim:"
                for i in range(len(edges_seen)):
                    print "%d: %s" % (i, str(edges_seen[i]))

                print "%d: Cancel" % (len(edges_seen))

                selection = ConsolePlayer.get_selection()

                if 0 <= selection < len(edges_seen):
                    # Ask how the user would like to claim the edge.
                    possible_actions = Game.all_connection_actions(
                        edges_seen[selection], self.player_info.hand.cards,
                        self.player_info.num_cars)

                    print ""
                    print "Choose which cards to use:"
                    for i in range(len(possible_actions)):
                        print "%d: %s" % (
                            i, Hand.cards_str(possible_actions[i].cards))

                    print "%d: Cancel" % (len(possible_actions))

                    selection = ConsolePlayer.get_selection()

                    if 0 <= selection < len(possible_actions):
                        action = possible_actions[selection]

        print ""
        return action
Example #58
0
import pygame
from game import Game

pygame.init()
play = Game()
play.do_game()
Example #59
0
class GameRunner:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("2048")
        self.surface = pygame.display.set_mode(
            (BOARD_SIZE_PX, BOARD_SIZE_PX + BOARD_Y_OFFSET_PX), 0, 32)
        self.myfont = pygame.font.SysFont("arial", 20)
        self.scorefont = pygame.font.SysFont("arial", 20)

        self.grayscale = False
        self.game = Game()
        self.auto = False
        self.ec = False

    def loop(self):
        while True:
            game_over = self.game.game_over()
            if game_over:
                self.auto = False

            direction = None
            for event in pygame.event.get():
                if not game_over:
                    if event.type == KEYDOWN:
                        if self.is_arrow(event.key):
                            direction = ROTATIONS[event.key]
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == K_RETURN:
                        self.auto = not self.auto
                    if event.key == K_e:
                        self.ec = not self.ec
                    if event.key == pygame.K_r:
                        self.game.reset()
                        self.auto = False
                    if 50 < event.key and 56 > event.key:
                        self.game.board_size = event.key - 48
                        self.game.reset()
                        self.auto = False
                    if event.key == pygame.K_s:
                        self.game.save_state()
                    elif event.key == pygame.K_l:
                        self.game.load_state()
                    elif event.key == pygame.K_u:
                        self.game.undo()
                    elif event.key == pygame.K_g:
                        self.grayscale = not self.grayscale

            if self.auto and not game_over:
                ai = AI(self.game.get_state())
                if not self.ec:
                    direction = ai.compute_decision()
                else:
                    direction = ai.compute_decision_ec()

            if direction != None:
                self.game.move_and_place(direction)

            self.print_matrix()
            if game_over:
                self.print_game_over()
            pygame.display.update()

    def print_matrix(self):
        tile_size = BOARD_SIZE_PX / self.game.board_size
        self.surface.fill(WHITE)
        for i in range(0, self.game.board_size):
            for j in range(0, self.game.board_size):
                tile_count = self.game.tile_matrix[i][j]
                ul_x_px = i * tile_size
                ul_y_px = j * tile_size + BOARD_Y_OFFSET_PX
                color = None
                if self.grayscale:
                    color_order = min(math.log(tile_count, 2),
                                      MAX_CORD) if tile_count > 0 else 0
                    color = MAXC - ((color_order / float(MAX_CORD)) * MAXC)
                    color = [color] * 3
                else:
                    color = COLORS[tile_count]
                pygame.draw.rect(self.surface, color,
                                 (ul_x_px, ul_y_px, tile_size, tile_size))
                pygame.draw.rect(self.surface, BLACK,
                                 (ul_x_px, ul_y_px, tile_size, tile_size), 2)
                tile_lbl = self.myfont.render(str(tile_count), 1, BLACK)
                score_lbl = self.getScoreLabel()

                tile_lbl_x = ul_x_px + TEXT_X_OFFSET_PX
                tile_lbl_y = ul_y_px + TEXT_Y_OFFSET_PX
                tile_lbl_pos = (tile_lbl_x, tile_lbl_y)
                self.draw_label_hl(tile_lbl_pos, tile_lbl, 2, [230] * 3, 1,
                                   False)
                self.surface.blit(tile_lbl, tile_lbl_pos)

                self.surface.blit(score_lbl, SCORE_LABEL_POS)

                if self.ec:
                    ec_lbl = self.scorefont.render("[EC]", 1, BLACK, WHITE)
                    self.surface.blit(ec_lbl, EC_LABEL_POS)

    def getScoreLabel(self):
        return self.scorefont.render("Score: {}".format(self.game.score), 1,
                                     BLACK, WHITE)

    def draw_label_hl(self,
                      pos,
                      label,
                      padding=PADDING,
                      bg=WHITE,
                      wd=2,
                      border=True):
        specs = [(bg, 0)]
        if border:
            specs += [(BLACK, wd)]
        for color, width in specs:
            pygame.draw.rect(self.surface, color,
                             (pos[0] - padding, pos[1] - padding,
                              label.get_width() + padding * 2,
                              label.get_height() + padding * 2), width)

    def print_game_over(self):
        game_over_lbl = self.scorefont.render("Game Over!", 1, BLACK, WHITE)
        score_lbl = self.getScoreLabel()
        restart_lbl = self.myfont.render("Press r to restart!", 1, BLACK,
                                         WHITE)

        for lbl, pos in [(game_over_lbl, (50, 100)), (score_lbl, (50, 200)),
                         (restart_lbl, (50, 300))]:
            self.draw_label_hl(pos, lbl)
            self.surface.blit(lbl, pos)

    def is_arrow(self, k):
        return (k == pygame.K_UP or k == pygame.K_DOWN or k == pygame.K_LEFT
                or k == pygame.K_RIGHT)
Example #60
0
import sys
sys.path.insert(0, '../../bomberman')
sys.path.insert(1, '..')

# Import necessary stuff
import random
from game import Game
from monsters.selfpreserving_monster import SelfPreservingMonster

# TODO This is your code!
sys.path.insert(1, '../groupNN')
from testcharacter import TestCharacter

# Create the game
random.seed(123)  # TODO Change this if you want different random choices
g = Game.fromfile('map.txt')
g.add_monster(
    SelfPreservingMonster(
        "monster",  # name
        "M",  # avatar
        3,
        9,  # position
        1  # detection range
    ))

# TODO Add your character
g.add_character(TestCharacter(
    "me",  # name
    "C",  # avatar
    0,
    0  # position