Esempio n. 1
0
    def test_read_message_decreases_messages_count(self):
        self.game = Game(self.questions_storage)
        self.game.next_question()
        start_messages_count = self.game.get_messages_count()

        self.game.read_message()

        self.assertLess(self.game.get_messages_count(), start_messages_count)
Esempio n. 2
0
	def evaluate(self, member):
		scr = pygame.display.set_mode((800,600))
		ac = choice(self.action)
		g = Game(scr, member, None, ac)
		a = g.start()
		if g.thing.life < 0:
			g.thing.life = 0
		member.fitness = (g.thing.full - g.thing.life)/g.wave
		return member.fitness			
Esempio n. 3
0
    def test_request_help_adds_messages(self):
        self.game = Game(self.questions_storage)
        self.game.next_question()
        start_messages_count = self.game.get_messages_count()

        self.game.request_help()

        self.assertGreater(self.game.get_messages_count(),
                           start_messages_count)
Esempio n. 4
0
 def evaluate(self, member):
     scr = pygame.display.set_mode((800, 600))
     ac = choice(self.action)
     g = Game(scr, member, None, ac)
     a = g.start()
     if g.thing.life < 0:
         g.thing.life = 0
     member.fitness = (g.thing.full - g.thing.life) / g.wave
     return member.fitness
Esempio n. 5
0
 def test_get_label_h_pairs(self):
     game = Game(3)
     game.shuffle(333)
     clean_tiles = [[(1, 0)], [(2, 0)], [(3, 0)], [(4, 0)], [(5, 0)], [(6, 0)], [(7, 0)], [(8, 0)], [(9, 0)]]
     self.assertNotEqual(game.get_label_h_pairs(), clean_tiles)
     game.tiles = game.generate_tiles(3)
     self.assertEqual(game.get_label_h_pairs(), clean_tiles)
Esempio n. 6
0
    def do_start(self, _):
        try:
            self.game = Game(
                player_1=self.player_1,
                player_2=self.player_2,
            )
        except AttributeError as exc:
            if 'player_1' in str(exc):
                self.logger.error("Game cannot start: You need to create the Player 1: p1 <name> .")

            elif 'player_2' in str(exc):
                self.logger.error("Game cannot start: You need to create the Player 2: p2 <name> .")

        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))
Esempio n. 7
0
	def load_monster(self, doc):
		color = doc.get('color', None)
		if color is None:
			color = libtcod.red
		elif hasattr(color, 'upper'):
			color = getattr(libtcod, color)
		else:
			color = libtcod.Color(*color)

		ai_class = doc.get('ai_class', BasicMonster)
		cls_data = {}
		if ai_class is not BasicMonster:
			cls_data = {}
			if hasattr(ai_class, 'items'):
				nm = ai_class.pop('class_name', 'monsters.BasicMonster')
				cls_data.update(ai_class)
				ai_class = nm

			module, clas = ai_class.rsplit('.',1)
			module = __import__(module)
			ai_class = getattr(module, clas)

		death_func = getattr(ai_class, 'death', monster_death)

		print 'loading', doc
		Game.register_monster_type(
			(lambda doc:
				lambda map,level,con,x,y: objects.Object( map, con, x,y,
					doc['char'],
					doc.get('name_fmt', '%s the %s') % (
						libtcod.namegen_generate(doc['namegen_class']).capitalize(),
						doc['race_name'].capitalize()
					),
					color,
					True,
					fighter=objects.Fighter(
						hp=doc['hp'],
						defense=doc['defense'],
						power=doc['power'],
						death_function=death_func
					),
					ai=ai_class().load_data(cls_data),
					level=level
				)
			)(doc), doc['spawn_chance'])
Esempio n. 8
0
def test_possible_to_emerge():
    game = Game()
    game.add_lives(Life(0, 0))
    game.add_lives(Life(1, 0))
    game.add_lives(Life(2, 1))

    assert len(game.get_possible_to_emerge()) == 17
Esempio n. 9
0
def main(stdscr):
    with open("result.out") as f:
        game = Game(*json.loads(f.read()))
    if len(sys.argv) > 1 and sys.argv[1] == "-t":
        turn = int(sys.argv[2])-1
    else:
        turn = 0
        
    play_game(stdscr, game, turn=turn)
Esempio n. 10
0
 def test_slide_tile(self):
     game = Game(3)
     game.tiles = game.generate_tiles(3)
     print(game)
     self.assertFalse(game.slide_tile(1))
     self.assertFalse(game.slide_tile(2))
     self.assertFalse(game.slide_tile(4))
     self.assertTrue(game.slide_tile(8))
     self.assertTrue(game.slide_tile(7))
     self.assertTrue(game.slide_tile(7))
     self.assertTrue(game.slide_tile(8))
Esempio n. 11
0
def run():
	args = docopt(__doc__)
	debug.log(args)
	if args['-']:
		story = sys.stdin.read()
	else:
		story = open(args['STORY-FILE'], 'r').read()
	characters = open(args['CHARACTERS-FILE'], 'r').read()
	stats = open(args['STATS-FILE'], 'r').read()
	game = Game(story, characters, stats).start()
    def client_on_message(self, message):
        """
        When the client receive a message
        :param message: The message receive
        :return: None
        """
        messages = Server.Server.decode_message(message)

        for message in messages:
            message = message.split('_')

            if message[0] == MESSAGE_NEED_STATE:
                self.client_send_player_name()
                self.client_send_token()

            elif message[0] == MESSAGE_SEND_NAME_SELECTED:
                self.players_entry_string_variable[0].set(message[1])
                self.name_string_var_trace_write(False)

            elif message[0] == MESSAGE_SEND_TOKEN_SELECTED:
                try:
                    # noinspection PyTypeChecker
                    self.players_tokens[
                        self.opponent_id] = TokenStyle.TokenStyle(
                            int(message[1]))

                    self.players_tokens_images[self.opponent_id] = \
                        self.ui.image_getter.save_token_photos[self.opponent][self.players_tokens[self.opponent_id]]

                    self.players_tokens_labels[self.opponent_id].config(
                        image=self.players_tokens_images[self.opponent_id])
                except ValueError:
                    pass

            elif message[0] == MESSAGE_PLAYER_1_WANT_START:
                self.player_1_want_to_start()

            elif message[0] == MESSAGE_PLAY:
                game = Game.Game(
                    first_player=(TokenState.Player_2,
                                  TokenState.Player_1)[message[1] == "1"])

                self.export_last_game_settings()

                self.ui.change_panel(
                    ServerGamePanel.ServerGamePanel,
                    player_1=Player.Player(
                        TokenState.Player_1, self.players_tokens[0],
                        self.players_entry_string_variable[0].get()),
                    player_2=Player.Player(
                        TokenState.Player_2, self.players_tokens[1],
                        self.players_entry_string_variable[1].get()),
                    is_server=self.create_game,
                    game=game)
Esempio n. 13
0
def test_available_moves():
    g = Game(Strategy(), Strategy())
    s = g.state

    moves = available_moves(s)
    for m in moves:
        new_state = deepcopy(g.state)

        new_state.apply(m)
        new_state.show()

    return moves
Esempio n. 14
0
    def __init__(self, game: Game) -> None:
        super().__init__()
        self.camera = game.camera
        self.mouse_watcher = game.mouseWatcherNode
        self.previous_mouse = Point2()
        self.mouse_sensitivity = 50
        self.actions = {}

        # game.setBackgroundColor(94/255, 39/255, 80/255)
        game.render.set_antialias(AntialiasAttrib.MAuto)
        self.camera.set_pos(0, 0, 0)
        self.camera.look_at(1, 0, 0)
        game.disable_mouse()

        props = WindowProperties()
        props.set_cursor_hidden(True)
        props.set_mouse_mode(WindowProperties.M_relative)
        game.win.request_properties(props)

        for action in "walk-forward", "walk-backward", "walk-left", "walk-right":
            self.accept(action, self.actions.update, [{action: True}])
            self.accept(action + "-up", self.actions.update, [{action: False}])
Esempio n. 15
0
 def test_check_win_with_uncorrect_positions_0(self):
     test_mas = (
         ("O", "O", 3, 4, 5, 6, 7, 8, "O"),
         (1, "O", 3, "O", 5, "O", 7, 8, 9),
         ("O", "O", 3, "O", 5, 6, 7, 8, 9),
         (1, 2, 3, 4, 5, "O", 7, 8, "O"),
         (1, 2, 3, "O", 5, 6, 7, 8, 9),
         (1, 2, "O", 4, 5, 6, "O", 8, "O"),
         (1, "O", 3, "O", 5, 6, "O", 8, 9),
         ("O", 2, "O", 4, "O", 6, 7, "O", 9),
     )
     for it in test_mas:
         chw = Game(it).check_win()
         self.assertFalse(chw)
Esempio n. 16
0
 def test_check_win_with_uncorrect_positions_X(self):
     test_mas = (
         (1, "X", 3, 4, 5, "X", 7, "X", 9),
         ("X", 2, 3, "X", "X", 6, 7, 8, 9),
         (1, "X", 3, "X", 5, "X", 7, 8, 9),
         ("X", "X", 3, 4, 5, 6, 7, 8, "X"),
         (1, 2, "X", 4, "X", 6, 7, "X", "X"),
         (1, 2, "X", "X", "X", 8, 7, 8, 9),
         (1, 2, "X", "X", 5, "X", "X", 8, 9),
         (1, "X", 3, 4, 5, 6, 7, "X", 9),
     )
     for gb in test_mas:
         chw = Game(gb).check_win()
         self.assertFalse(chw)
Esempio n. 17
0
 def game_loop(self):
     while self.running:
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 self.running = False
                 sys.exit(0)
             elif event.type == pygame.KEYDOWN:
                 if event.unicode.isalpha():
                     self.entered_name += event.unicode
                 elif event.key == pygame.K_BACKSPACE:
                     self.entered_name = self.entered_name[:-1]
                 elif event.key == pygame.K_RETURN:
                     self.running = False
                     Game(self.entered_name)
         self.display()
         pygame.display.update()
         CLOCK.tick(FPS)
Esempio n. 18
0
def play_game(screen, game, turn=0):
    maxturn = len(game.record)-1
    turn = min(max(turn, 0), maxturn) 
    while True:
        table, score = game.record[turn]
        g = Game(table=table, score=score, size=game.size, turn=turn+1)
        render_info(g, screen)
        render_help(screen)
        action, arg = prompt_key(g, screen)
        if action == "next":
            turn += 1
        elif action == "prev":
            turn -= 1
        elif action == "skip":
            turn = int(arg)-1
            
        elif action == "add":
            turn += int(arg)
        turn = min(max(turn, 0), maxturn)
Esempio n. 19
0
    def __init__(self,
                 master,
                 ui,
                 is_server=False,
                 player_1=Player.Player(TokenState.TokenState.Player_1,
                                        TokenStyle.TokenStyle.Blue),
                 player_2=Player.Player(TokenState.TokenState.Player_2,
                                        TokenStyle.TokenStyle.Green),
                 game=Game.Game()):
        """
        Constructor
        """
        super().__init__(master,
                         ui,
                         player_1,
                         player_2,
                         game,
                         disable_end_button=not is_server)

        self.is_server = is_server

        if self.is_server:
            self.button_main_menu.configure(
                text=self.ui.translation.get_translation("quit"))

            # Set server functions
            self.ui.server.on_message_function = self.server_on_message
            self.ui.server.on_client_connect_function = self.server_on_client_connect_function
            self.ui.server.on_client_disconnect_function = self.server_on_client_disconnect_function

        else:
            tkinter.tix.Label(self.win_text_frame,
                              text=self.ui.translation.get_translation(
                                  "server_game_wait_host")).grid(row=1,
                                                                 column=0)

            # Set client functions
            self.ui.client.on_message_function = self.client_on_message
            self.ui.client.on_connection_function = self.client_on_connection_function
            self.ui.client.on_disconnection_function = self.client_on_disconnection_function
Esempio n. 20
0
 def test_check_win_with_wit_garbage(self):
     test_mas = (
         ("a", 2, "ty", "X", 5, 6, 7, "O", 9),
         (1, 2, "X", "X", "X", 6, 7, 8, 9),
         (1, "O", 3, "r", "67", "O", 7, 8, 9),
         ("O", "@", "X", "l", 5, "D", 7, "X", 9),
         ("*", 2, "4", "]", "|", 6, 7, 8, "X"),
         (1, "X", 3, 4, "O", 6, 7, "O", 9),
         (1, 2, 3, "X", "X", "O", 7, 0x45, 9),
         (
             1,
             "O",
             3,
             "F",
             5,
             "f",
             7,
             8,
         ),
     )
     for it in test_mas:
         chw = Game(it).check_win()
         self.assertFalse(chw)
    def button_play_command(self):
        """
        When the button play (or ready is press)
        :return: None
        """

        if self.create_game:
            if self.player_2_is_connected:
                if self.player_2_is_ready:
                    self.export_last_game_settings()

                    self.ui.change_panel(
                        ServerGamePanel.ServerGamePanel,
                        player_1=Player.Player(
                            TokenState.Player_1, self.players_tokens[0],
                            self.players_entry_string_variable[0].get()),
                        player_2=Player.Player(
                            TokenState.Player_2, self.players_tokens[1],
                            self.players_entry_string_variable[1].get()),
                        is_server=self.create_game,
                        game=Game.Game(
                            first_player=random.choice((TokenState.Player_1,
                                                        TokenState.Player_2))))

                    self.ui.server.send_message_to_all(
                        Server.Server.encode_message('_'.join(
                            (MESSAGE_PLAY,
                             str(self.ui.current_panel.game.current_turn.value)
                             ))))
                else:
                    self.player_1_want_to_start()
        else:
            self.set_player_2_ready(not self.player_2_is_ready)
            self.ui.client.send_message(
                Server.Server.encode_message('_'.join(
                    (MESSAGE_SEND_READY, str(self.player_2_is_ready)))))
Esempio n. 22
0
from options import shooter as Options
from main import Game


Main = Game(Options, 'start')
Main.run()
Esempio n. 23
0
from main import Game
from utility import NonBlockingInput, keyPressed, clearScreen as c
from config import *
from time import sleep, monotonic
from objects import MandoBullet, BossBullet
import sys

g = Game(100)

keys = NonBlockingInput()
keys.NBISetupTerminal()

counter = 0
bulletFlag = False

coinLocations = []
lazerLocations = []

for location in g.screen.locationsUsed:

    if counter < COINB_COUNT:

        coinLocations.append(g.screen.map[location[0] - COIN_SIZE[0] : location[0], location[1] : location[1] + COIN_SIZE[1]])

    elif counter < COINB_COUNT + HLAZER_COUNT:
            
        lazerLocations.append(g.screen.map[location[0], location[1] : location[1] + HLAZER_SIZE[1]])

    elif counter < COINB_COUNT + HLAZER_COUNT + VLAZER_COUNT:
            
        lazerLocations.append(g.screen.map[location[0] - VLAZER_SIZE[0] : location[0], location[1]])
Esempio n. 24
0
from main import Game, select_action
import sys

states = {}

with open(sys.argv[1], "r") as f:
    line = f.readline()
    while line:
        data = line[:-1].split("#")
        states[eval(data[0])] = eval(data[1])
        line = f.readline()

game = Game()

while 1:
    state = game.get_state()
    if not state in states.keys():
        states[state] = {}
        for i in game.get_actions():
            states[state][i] = 0.0
    action = max(states[state], key=states[state].get)
    # print(states[state])
    game.do_action(action, 1)
    next_state = game.get_state()

    if game.is_end() != -1:
        game.print()
        print(f"game end {game.is_end()}")
        break

    actions = game.get_actions()
Esempio n. 25
0
from django.utils import simplejson
import feedparser
import re

from google.appengine.api import urlfetch

from BeautifulSoup import BeautifulSoup
import urllib,string,csv,sys,os
from string import replace

from main import Game

game = Game.gql("WHERE match = :1", 23).get()

url = "http://odds.football-data.co.uk/football/world-cup-2010/main-tournament/group-stage/group-%s/%s-v-%s/match-result/" % (game.group, game.home, game.away)

page = urlfetch.fetch(url, headers = {'User-Agent': "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3"}) 
html = page.read()

print html

soup = BeautifulSoup(html)
table = soup.find("td", "Competitor")

print table

from django.utils import simplejson
import feedparser
import re

from google.appengine.api import urlfetch
Esempio n. 26
0
from main import Game

g = Game()

g.run()
Esempio n. 27
0
def main():
    print("Starting the game")
    game = Game()
    game.play()
    print("Game Over")
Esempio n. 28
0
    assert(len(W) == 10)
    W -= (1,2,0,0,0,0)
    assert(len(W) == 7)
    assert(W[2] == 3)
    W += (4,4,1,0,0,0)
    assert(W.overmax())
    W -= (4,4,4,4,0,0)
    assert(W.negative() is False)
    
if __name__ == "__main__":
    _BLACK = 4
    C = Card(_BLACK,0,1,1,1,1,0)
    assert(C.cost() == (1,1,1,1,0))
    assert(C.color() == 'B')
    assert(C.points() == 0)
    C.set_key(0,3)
    assert(C.key() == (0, 3))

if __name__ == "__main__":
    G = Game()
    P1 = G.active_player()
    G.collect((1,1,1,0,0,0))
    P2 = G.active_player()
    assert(P2 is not P1)
    G.collect((0,1,1,1,0,0))
    G.board()

if __name__ == "__main__":
    N = Noble(3, 3, 3, 3, 0, 0)
    assert(N.cost() == (3, 3, 3, 0, 0))
Esempio n. 29
0
def training_loop(training_model, opponent_model, verbose=False):

    winner = None

    # for tensor board logging
    log_dir = ("logs/fit/" + training_model._name +
               datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
    tensorboard = ModifiedTensorBoard(log_dir=log_dir)

    # now execute the q learning
    y = 0.9
    eps = 0.5
    interval_size = 500
    num_episodes = interval_size * 1
    decay_factor = (1000 * eps)**(
        -1 / num_episodes
    )  # ensures that eps = 0.001 after `num_episodes` episodes

    r_avg_list = []
    sse_avg_list = []
    wins = []
    n_moves_list = []
    moves_played = [0] * BOARD_SIZE
    for i in tqdm(range(num_episodes), desc="Training"):

        as_player = random.choice([0, 1])
        eps *= decay_factor

        g = Game(verbose=verbose)

        if as_player == 1:  # Training as player 1 so opponent makes first move
            winner, board = g.move(opponent_model.move(g._board, 0))
        else:
            board = g._board

        done = False
        r_sum = 0
        sse_sum = 0
        move_num = 0
        while not done:
            random_move = False
            move_num += 1
            preds = training_model.predict(board, as_player)

            # To encourage early exploration
            if np.random.random() < eps:
                move = np.random.randint(0, BOARD_SIZE - 1)
                random_move = True
            else:
                move = training_model.move(board, as_player)
                moves_played.append(move)

            winner, new_board = g.move(move)

            if winner is None:
                opponent_move = opponent_model.move(new_board, 1 - as_player)
                winner, new_board = g.move(opponent_move)

            # Calculate reward amount
            if winner == as_player:
                done = True
                wins.append(1)
                r = 1000 - move_num**2
            elif winner == 1 - as_player:
                done = True
                wins.append(0)
                r = -(1000 - move_num**2)
            elif winner == -1:
                done = True
                wins.append(None)
                r = 1000
            else:
                r = move_num

            if winner is None:
                target = r + y * np.max(
                    training_model.predict(new_board, as_player))
            else:
                target = r

            target_vec = deepcopy(preds[0])
            target_vec[move] = target

            training_model.fit_one(
                as_player,
                board,
                np.array([target_vec]),
                epochs=1,
                verbose=0,
                callbacks=[tensorboard],
            )

            new_preds = training_model.predict(board, as_player)

            sse = sum([(x - y)**2 for x, y in zip(preds[0], target_vec)])
            new_sse = sum([(x - y)**2
                           for x, y in zip(new_preds[0], target_vec)])
            sse_sum += sse

            if verbose:
                print(f"""
                    {training_model._name} training as player: {as_player}, move: {move_num}, eps: {round(eps, 2)},
                    old preds: {[round(p, 2) for p in preds[0]]}, rand move: {random_move},
                    tgt preds: {[round(p, 2) for p in target_vec]}, reward: {r},
                    new preds: {[round(p, 2) for p in new_preds[0]]}, average last 20 games: {round(sum(r_avg_list[-20:])/20, 2)} 
                    sse: {round(sse, 4)} >> {round(new_sse, 4)}
                    """)

            board = new_board
            r_sum += r

        if verbose and ((i % interval_size == 0 and i > 0) or
                        (i == num_episodes - 1)):
            run_game(training_model, opponent_model, verbose=True)

        # Collect game level metrics
        r_avg_list.append(round(r_sum, 2))
        n_moves_list.append(move_num)

        tensorboard.update_stats(reward_sum=r_sum,
                                 wins=wins[-1],
                                 n_moves_avg=n_moves_list[-1])
        tensorboard.update_dist(moves_played=moves_played)
Esempio n. 30
0

def make_app():

    return tornado.web.Application([
        (r"/", MainHandler),
    ])


def start_asyncio_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()


if __name__ == "__main__":
    app = make_app()
    app.listen(8888)

    print(f'(test) Game name: <{ppretty(Game)}>.')
    print(f'(test) Game name: <{ppretty(Game.name)}>.')
    print(f'(test) Element hill notation: <{Element.hill_notation}>.')
    print(f'(test) Hydrogen hill notation: <{Hydrogen.hill_notation}>.')
    game = Game()

    game_loop = asyncio.new_event_loop()
    #game_loop.call_soon_threadsafe(game.start_loop, )
    game_loop.call_soon_threadsafe(game.loop, )
    game_loop_thread = Thread(target=start_asyncio_loop, args=(game_loop, ))
    game_loop_thread.start()

    tornado.ioloop.IOLoop.current().start()
Esempio n. 31
0
from main import Game
from constants import Constants


__author__ = 'capt_MAKO'
__since__ = '30/December/2015 21:45:00'
__version__ = '1.0'


constants = Constants()
main = Game(constants)
main.intro()
main.main_loop()
Esempio n. 32
0
					fighter=objects.Fighter(
						hp=doc['hp'],
						defense=doc['defense'],
						power=doc['power'],
						death_function=death_func
					),
					ai=ai_class().load_data(cls_data),
					level=level
				)
			)(doc), doc['spawn_chance'])

Game.register_monster_type(
	lambda map,level, con,x,y: objects.Object(map, con,
		x,y, '\x02', '%s the Orc' % libtcod.namegen_generate('Fantasy male'),
			libtcod.blue, True,

		fighter=objects.Fighter(hp=10, defense=2, power=3, death_function=monster_death),
		ai=AdvancedMonster(),
		level=level
), 8)

Game.register_monster_type(
	lambda map,level, con,x,y: objects.Object(map, con,
		x,y, '\x01', '%s the Troll' % libtcod.namegen_generate('Norse male'),
			libtcod.orange, True,

		fighter=objects.Fighter(hp=16, defense=1, power=4, death_function=monster_death),
		ai=AdvancedMonster(),
		level=level
), 2)
Esempio n. 33
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from main import Game
import json, queue

NBTHREADS = 4
MAXSIZE = -1
SCORETARGET = 600000

boundary = queue.LifoQueue(MAXSIZE)

boundary.put(Game())

maxscore = -1
nbgames = 1
bgame = None
while not boundary.empty():
    game = boundary.get()
    game.init_turn()
    moves = game.avail_moves(game.table)
    if not moves:
        if game.score > maxscore:
            print("new maxscore (%s branch): %s" % (nbgames, maxscore))
            maxscore = game.score
            bgame = game
        if maxscore > SCORETARGET:
            break
    nbgames += len(moves) - 1
    for move in moves:
        game2 = game.copy()
        game2.play(move)
Esempio n. 34
0
def main():
    Game().run()
Esempio n. 35
0
class BattleshipCLI(Cmd):
    prompt = 'battleship> '
    intro = "{} \n Welcome to Battleship CLI! Type ? to list commands \n ".format(HEADER)

    logger = get_logger()

    ALL_SHIPS = list(Ship.get_ship_map().keys())
    ALL_ALIGMENTS = ShipPosition.ALL
    ALL_COLS = GameBoard.COLS_NAMES
    ALL_ROWS = GameBoard.ROWS_NAMES

    def do_exit(self, inp):
        '''exit the application.'''
        self.logger.info("Bye! Thanks for playing!")
        return True

    def do_basic(self, _):
        print(GAMEPLAY)

    def help_basic(self, _):
        print("Battleship Gameplay")

    def do_intro(self, _):
        print(INSTRUCTIONS)

    def help_intro(self, _):
        print("Battleship CLI Instructions.")

    def do_p1(self, name):
        if not name:
            self.logger.error("Name cannot be empty.".format(name))
            return None
        try:
            if str(self.player_2.name).lower() == str(name).lower():
                self.logger.error("Name '{}' already taken for the Player 2".format(name))
                return None
        except AttributeError:
            pass

        self.player_1 = Player(name=name)

    def help_p1(self):
        print("Set Player 1")

    def do_p2(self, name):
        if not name:
            self.logger.error("Name cannot be empty.".format(name))
            return None
        try:
            if str(self.player_1.name).lower() == str(name).lower():
                self.logger.error("Name '{}' already taken for the Player 1".format(name))
                return None
        except AttributeError:
            pass

        self.player_2 = Player(name=name)

    def help_p2(self):
        print("Set Player 2")

    def do_start(self, _):
        try:
            self.game = Game(
                player_1=self.player_1,
                player_2=self.player_2,
            )
        except AttributeError as exc:
            if 'player_1' in str(exc):
                self.logger.error("Game cannot start: You need to create the Player 1: p1 <name> .")

            elif 'player_2' in str(exc):
                self.logger.error("Game cannot start: You need to create the Player 2: p2 <name> .")

        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_start(self):
        print("Start game")

    def do_place_ship_p1(self, row_col_ship_aligment):
        row, col, ship, aligment = row_col_ship_aligment.split(' ')
        try:
            self.game.place_ships_for_player_1([
                ShipPosition(
                    row=row,
                    col=col,
                    ship=Ship.get_ship(ship),
                    aligment=ShipPosition.get_aligment(aligment)
                ),
            ])
        except AttributeError as exc:
            self.logger.error("Error: Game not started. Details: {}".format(str(exc)))
        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_place_ship_p1(self):
        print(
            (
                "Place ships for Player 1: Format: row col ship aligment "
                "Example: place_ship_p1 A 1 carrier h"
            )
        )

    def do_place_ship_p2(self, row_col_ship_aligment):
        row, col, ship, aligment = row_col_ship_aligment.split(' ')
        try:
            self.game.place_ships_for_player_2([
                ShipPosition(
                    row=row,
                    col=col,
                    ship=Ship.get_ship(ship),
                    aligment=ShipPosition.get_aligment(aligment)
                ),
            ])
        except AttributeError as exc:
            self.logger.error("Error: Game not started. Details: {}".format(str(exc)))
        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_place_ship_p2(self):
        print(
            (
                "Place ships for Player 2: Format: row col ship aligment "
                "Example: place_ship_p1 A 1 carrier h"
            )
        )

    def do_play(self, _):
        try:
            self.game.play()
        except AttributeError as exc:
            self.logger.error("Error: Game not started. Details: {}".format(str(exc)))
        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_play(self):
        print("Start shooting!")

    def do_shoot(self, row_col):
        row, col = row_col.split(' ')
        try:
            self.game.shoot(row, col)
        except AttributeError as exc:
            self.logger.error("Error: Game not started. Details: {}".format(str(exc)))
        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_shoot(self):
        print(
            (
                "Shoot ships according to the turn. Format: row col "
                "Example: shoot A 1"
            )
        )

    def do_ls(self, resource):
        resource_map = {
            'ships': self.ALL_SHIPS,
            's': self.ALL_SHIPS,
            'aligments': self.ALL_ALIGMENTS,
            'a': self.ALL_ALIGMENTS,
            'rows': self.ALL_ROWS,
            'r': self.ALL_ROWS,
            'cols': self.ALL_COLS,
            'c': self.ALL_COLS,
        }
        try:
            print(resource_map[str(resource).lower()])
        except KeyError as exc:
            self.logger.error("Resource not found: {}".format(str(exc)))
        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_ls(self):
        print(
            (
                "List resource: Format: ls <resource> "
                "Example: ls ships"
            )
        )

    def do_stats(self, _):
        try:
            self.game.display_stats()
        except AttributeError as exc:
            self.logger.error("Error: Game not started. Details: {}".format(str(exc)))
        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_stats(self):
        print("Display game stats")

    def do_restart(self, _):
        try:
            self.game.restart()
        except AttributeError as exc:
            self.logger.error("Error: Game not started. Details: {}".format(str(exc)))
        except Exception as exc:
            self.logger.error("Error: {}".format(str(exc)))

    def help_restart(self):
        print("Restart the game, Using the same players.")
Esempio n. 36
0
    menu = Menu()

    menu.load.screen.blit(menu.background, (0, 0))
    menu.init(['Play', 'Quit'], menu.load.screen)
    menu.draw()
    pygame.key.set_repeat(199, 69)  # (delay,interval)
    pygame.display.update()

    while 1:
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_UP:
                    menu.draw(-1)
                if event.key == K_DOWN:
                    menu.draw(1)
                if event.key == K_RETURN:
                    if menu.get_position() == 0:
                        game = Game()
                        game.game_loop()
                    if menu.get_position() == 1:
                        pygame.display.quit()
                        sys.exit()
                if event.key == K_ESCAPE:
                    pygame.display.quit()
                    sys.exit()
                pygame.display.update()
            elif event.type == QUIT:
                pygame.display.quit()
                sys.exit()
        pygame.time.wait(8)
Esempio n. 37
0
    def __init__(self, master, ui,
                 player_1=Player.Player(TokenState.TokenState.Player_1, TokenStyle.TokenStyle.Blue),
                 player_2=Player.Player(TokenState.TokenState.Player_2, TokenStyle.TokenStyle.Green),
                 game=Game.Game(), disable_end_button=False, delay=Preferences.DEFAULT_DELAY):
        """
        Constructor
        :param player_1: the player 1
        :param player_2: the player 2
        :param game: a link to the game
        :param disable_end_button: if need to disable end buttons (for the client)
        :param delay: the delay between click in ms
        :param master: see Panel class
        :param ui: see Panel class
        """
        super().__init__(master, ui)

        self.turn_text_format = self.ui.translation.get_translation("game_panel_turn_format")
        self.win_text_format = self.ui.translation.get_translation("game_panel_win_format")

        self.grid_canvas = tkinter.tix.Canvas(self)
        self.grid_canvas.pack(expand=True, fill=tkinter.tix.BOTH)

        self.after(500, lambda: self.grid_canvas.bind("<Button>", self.grid_canvas_on_click))

        self.game = game

        self.players = {
            TokenState.TokenState.Player_1: player_1,
            TokenState.TokenState.Player_2: player_2
        }

        self.token_square_size = 0

        self.height_center = 0
        self.width_center = 0

        self.button_main_menu = tkinter.tix.Button(
            self,
            # text=self.ui.translation.get_translation("game_panel_main_menu_button"),
            command=self.button_main_menu_command, image=self.ui.image_getter.door_exit_icon)
        self.button_main_menu.place(x=0, y=0)

        self.grid_image_create = []
        self.turn_text_id = -1
        self.turn_image_id = - 1
        self.win_line_id = -1
        self.win_icon_id = -1
        self.win_icon_background_id = -1

        self.win_text_frame = tkinter.tix.Frame(self, relief=tkinter.tix.RAISED, borderwidth=2)

        self.win_text_label = tkinter.tix.Label(self.win_text_frame)
        self.win_text_label.grid(row=0, column=0)

        if not disable_end_button:
            self.end_buttons_frame = tkinter.tix.Frame(self.win_text_frame)
            self.end_buttons_frame.columnconfigure(0, weight=1)
            self.end_buttons_frame.columnconfigure(1, weight=1)
            self.end_buttons_frame.grid(row=1, column=0)

            max_width = max(len(self.ui.translation.get_translation("back")),
                            len(self.ui.translation.get_translation("restart")),
                            len(self.ui.translation.get_translation("main_menu")))

            self.button_main_menu_end = tkinter.tix.Button(
                self.end_buttons_frame,
                text=self.ui.translation.get_translation("main_menu"),
                command=self.button_main_menu_command, width=max_width
            )
            self.button_main_menu_end.grid(row=0, column=0, sticky=tkinter.tix.NSEW, padx=5)

            self.back_button = tkinter.tix.Button(
                self.end_buttons_frame,
                text=self.ui.translation.get_translation("back"),
                command=self.button_back_command, width=max_width
            )
            self.back_button.grid(row=0, column=1, sticky=tkinter.tix.NSEW, padx=5)

            self.restart_button = tkinter.tix.Button(
                self.end_buttons_frame,
                text=self.ui.translation.get_translation("restart"),
                command=self.button_restart_command, width=max_width
            )
            self.restart_button.grid(row=0, column=2, sticky=tkinter.tix.NSEW, padx=5)

        for x in range(0, self.game.grid_width):
            self.grid_image_create.append([])
            for y in range(0, self.game.grid_height):
                self.grid_image_create[x].append(-1)

        self.token_animation_list = []

        self.delay = delay / 1000.  # convert in second
        self.last_click_time = time.time()

        self.ai_turn_start_time = time.time()

        self.ai_progress_bar = tkinter.ttk.Progressbar(self.grid_canvas, orient=tkinter.tix.HORIZONTAL,
                                                       mode='determinate')
        self.ai_progress_bar_show = False
Esempio n. 38
0
 def setUp(self):
     self.questions_storage = QuestionStorage('')
     self.game = Game(self.questions_storage)