Exemplo n.º 1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--size", help="grid size",
                        type=int, default=DEFAULT_GRID_SIZE)
    parser.add_argument("-d", "--debug", help="debug mode",
                        type=bool, default=DEBUG_MODE)
    parser.add_argument("-f", "--fps", help="frames per second",
                        type=int, default=DEFAULT_FPS)
    args = parser.parse_args()

    gm = GameManager(size=args.size, debug_mode=args.debug, fps=args.fps)
    gm.game_loop()
Exemplo n.º 2
0
def main():
    game_manager = GameManager()

    game_manager.initialize()

    while game_manager.running():
        game_manager.tick()

    game_manager.clean_up()
Exemplo n.º 3
0
Arquivo: tct.py Projeto: delmoras/tct
def main():
    # change the current directory to the one of the game
    os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))

    # parse, get game's command line
    # options, return options' flags
    game_opts = get_parsed_opts()

    # make the window of the game always centered
    os.environ["SDL_VIDEO_CENTERED"] = "1"

    # set up the pygame system for the game
    pygame.init()

    # create game's window screen
    pygame.display.set_mode(
        (constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT),
        pygame.FULLSCREEN if game_opts.fullscreen else 0)

    # set game's window title
    pygame.display.set_caption(GAME_WINDOW_TITLE)

    # set game's window icon
    pygame.display.set_icon(load_image(
        constants.FILES['graphics']['window']['icon'][0])[0])

    # hide game's mouse cursor
    pygame.mouse.set_visible(False)

    # create the game manager
    gm = GameManager(game_opts)

    # main loop flag
    main_loop_running = True

    # main game event loop
    while main_loop_running:
        # run the game manager        
        gm.run_scene()

        # on quit exit the game
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                main_loop_running = False

    # uninitialize all the pygame systems
    pygame.quit()
Exemplo n.º 4
0
    def setUp(self):
        self.gm = GameManager()

        self.chat0 = Chat(0, 'group')
        self.chat1 = Chat(1, 'group')
        self.chat2 = Chat(2, 'group')

        self.user0 = User(0, 'user0')
        self.user1 = User(1, 'user1')
        self.user2 = User(2, 'user2')
Exemplo n.º 5
0
from game_manager import GameManager

game_manager = GameManager()
while True:
    game_manager.turn_manage()
class Test(unittest.TestCase):

    game = None

    def setUp(self):
        self.gm = GameManager()

        self.chat0 = Chat(0, 'group')
        self.chat1 = Chat(1, 'group')
        self.chat2 = Chat(2, 'group')

        self.user0 = User(0, 'user0')
        self.user1 = User(1, 'user1')
        self.user2 = User(2, 'user2')

    def test_new_game(self):
        g0 = self.gm.new_game(self.chat0)
        g1 = self.gm.new_game(self.chat1)

        self.assertListEqual(self.gm.chatid_games[0], [g0])
        self.assertListEqual(self.gm.chatid_games[1], [g1])

    def test_join_game(self):

        self.assertRaises(NoGameInChatError, self.gm.join_game,
                          *(self.user0, self.chat0))

        g0 = self.gm.new_game(self.chat0)

        self.gm.join_game(self.user0, self.chat0)
        self.assertEqual(len(g0.players), 1)

        self.gm.join_game(self.user1, self.chat0)
        self.assertEqual(len(g0.players), 2)

        g0.open = False
        self.assertRaises(LobbyClosedError, self.gm.join_game,
                          *(self.user2, self.chat0))

        g0.open = True
        self.assertRaises(AlreadyJoinedError, self.gm.join_game,
                          *(self.user1, self.chat0))

    def test_leave_game(self):
        g0 = self.gm.new_game(self.chat0)

        self.gm.join_game(self.user0, self.chat0)
        self.gm.join_game(self.user1, self.chat0)

        self.assertRaises(NotEnoughPlayersError, self.gm.leave_game,
                          *(self.user1, self.chat0))

        self.gm.join_game(self.user2, self.chat0)
        self.gm.leave_game(self.user0, self.chat0)

        self.assertRaises(NoGameInChatError, self.gm.leave_game,
                          *(self.user0, self.chat0))

    def test_end_game(self):
        g0 = self.gm.new_game(self.chat0)

        self.gm.join_game(self.user0, self.chat0)
        self.gm.join_game(self.user1, self.chat0)

        self.assertEqual(len(self.gm.userid_players[0]), 1)

        g1 = self.gm.new_game(self.chat0)
        self.gm.join_game(self.user2, self.chat0)

        self.gm.end_game(self.chat0, self.user0)
        self.assertEqual(len(self.gm.chatid_games[0]), 1)

        self.gm.end_game(self.chat0, self.user2)
        self.assertFalse(0 in self.gm.chatid_games)
        self.assertFalse(0 in self.gm.userid_players)
        self.assertFalse(1 in self.gm.userid_players)
        self.assertFalse(2 in self.gm.userid_players)
Exemplo n.º 7
0
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import json
from telegram.ext import Updater
from telegram.contrib.botan import Botan

from game_manager import GameManager
from database import db
import user_setting  # required to generate db mapping

db.bind('sqlite', 'uno.sqlite3', create_db=True)
db.generate_mapping(create_tables=True)

gm = GameManager()
with open("config.json","r") as f:
    config = json.loads(f.read())
updater = Updater(token=config.get("token"), workers=config.get("workers", 32))
dispatcher = updater.dispatcher

if config.get("botan_token"):
    botan = Botan(config.get("botan_token"))
else:
    botan = None
Exemplo n.º 8
0
from game_manager import GameManager
from game_state import GameState
"""This module represents the drop-token game service. All methods are 1:1 matches with api routes. Ideally documentation for the endpoints is done there."""

game_manager = GameManager()


def get_all_in_progress_games():
    output = {}
    output['games'] = get_all_games(game_state=GameState.IN_PROGRESS)
    return output


def create_new_game(players, columns, rows):
    output = {}
    new_game = game_manager.new_game(players, columns, rows)
    output['gameId'] = new_game.get_game_id()
    return output


def get_game_state(game_id):
    output = {}
    game = game_manager.get_game(game_id)
    output['players'] = game.get_players()
    game_state = game.get_game_state()
    output['state'] = game_state.name
    if game_state == GameState.DONE:
        output['winner'] = game.get_winner()
    return output

Exemplo n.º 9
0
def start_example_game():
    gm = GameManager()
    score = gm.start_game(RandomAgent(), display=True)
    print("Score:", score)
Exemplo n.º 10
0
 def check_hero_death(self):
     if self.game_manager.hero.current_health <= 0:
         self.canvas.delete("all")
         self.game_manager = GameManager()
         self.fill_canvas()
Exemplo n.º 11
0
 def __init__(self):
     """default constructor"""
     super(MainManager, self).__init__("main_manager")
     self.game_manager = GameManager()
     self.clock = None
Exemplo n.º 12
0
    # Card(name='5', suit='Sword'),
    # Card(name='7', suit='Star'),
    # Card(name='8', suit='Star'),
    # Card(name='6', suit='Star'),
    # Card(name='9', suit='Star'),
    # Card(name='4', suit='Star'),
    # Card(name='4', suit='Pagoda'),
    # Card(name='4', suit='Pagoda'),
    Phoenix(),
    # Dog(),
    # Mahjong(),
    # Mahjong(),
    # Dragon(),

]
test = [1, 2, 3, 4]

d = Dragon()

hand1 = Hand(cards_string='K_Pa, K_Sw')
hand2 = Hand(cards_string='Phoenix, A_Pa, Q_Pa')
hand3 = Hand(cards_string='K_Pa, Mahjong, 2_Pa, 3_Pa, 4_Pa, 5_Pa, 6_Pa')
hand4 = Hand(cards_string='J_Pa')
# players = [DumbAI(hand1, 'AI1'), DumbAI(hand2, 'AI2'), DumbAI(hand3, 'AI3'), DumbAI(hand4, 'AI4')]
# players = [DumbAI(Hand(), 'AI1'), DumbAI(Hand(), 'AI2'), DumbAI(Hand(), 'AI3'), DumbAI(Hand(), 'AI4')]

# gman = GameManager(players)
gman = GameManager()

gman.run_game()
Exemplo n.º 13
0
from game_objects.game_object import pg
from game_manager import GameManager
from game_objects.shell import Shell
from constants import BLACK, SCREEN_SIZE

go = Shell(0, 0)
screen = pg.display.set_mode(SCREEN_SIZE)
pg.display.set_caption("The cannon game")

done = False
clock = pg.time.Clock()

mg = GameManager()

while not done:
    clock.tick(200)
    screen.fill(BLACK)

    done = mg.process(pg.event.get(), screen)

    pg.display.flip()

pg.quit()

Exemplo n.º 14
0
screen = t.Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

snake = Snake()
screen.update()

food_spawner = FoodSpawner()
screen.update

collider = Collider(snake=snake, food_spawner=food_spawner)

game_manager = GameManager(snake=snake,
                           food_spawner=food_spawner,
                           collider=collider)
collider.ref_game_manager(game_manager)

screen.listen()
screen.onkey(key="Left", fun=snake.turn_left)
screen.onkey(key="Right", fun=snake.turn_right)
screen.onkey(key="Up", fun=snake.turn_up)
screen.onkey(key="Down", fun=snake.turn_down)

# write game logic below
while game_manager.game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()
    collider.check_collision()
from product import Product
from city import City
from game_manager import GameManager

def welcome_message():
    print("Welcome to Python Pirate Trader")

def get_firm_name():
    # firm_name = input("Please enter your Firm Name: ")
    return "Jack Sparrow Traders"

def get_starting_options():
    starting_options = input("How do you wish to start. 1) Cash & Debt 2) Cannons No debt. : ")
    if starting_options == "1":
        opts = (250, 2000, 0)
    else:
        opts = (0, 0, 5)
    # Tuples is a list of data that cannot be changed
    return opts

# Get Game Options
welcome_message()

firm_name = get_firm_name()

cash, debt, cannons = get_starting_options()

game = GameManager(shiphold=100, name=firm_name, cash=cash, debt=debt, cannons=cannons)  # Creating an instance of a Game Manager Class

# Start Up Game
game.start_up()
Exemplo n.º 16
0
from game_manager import GameManager
from agents import SLAgent

agent = SLAgent(n_frames_per_action=1)

gm = GameManager("pong.bin",
                 agent, 'results/testbed3',
                 remove_old_results_dir=True, use_minimal_action_set=True, 
                 visualise=None, min_time_between_frames=0.000001)
                 # visualise='rgb')

gm.run(n_episodes=500)
Exemplo n.º 17
0
def test_scoring():
    game = GameManager(width, ROW_COUNT, COLUMN_COUNT, SIDE)
    window = [1, 1, 1, 0, 2, 2, 2]
    assert game.scoring(window, game.AI_piece) == -70
Exemplo n.º 18
0
    #os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (300,300)

    pygame.mixer.pre_init(44100, -16, 2, 4096)
    pygame.init()

    # Game base settings
    FRAME_MODE = pygame.NOFRAME
    WINDOW_SIZE = constants.WINDOW_SIZE

    GAME = RushGame(WINDOW_SIZE)

    # Set up the display
    PYGAME_DISPLAY = pygame.display.set_mode((WINDOW_SIZE), FRAME_MODE)
    pygame.display.set_caption("Real Rush")

    manager = GameManager(PYGAME_DISPLAY)
    RUNNING = True
    CLOCK = pygame.time.Clock()

    while RUNNING:

        # Tick Clock
        CLOCK.tick(constants.FRAME_RATE)
        ELAPSED_TIME = CLOCK.get_time() / 1000

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                RUNNING = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    RUNNING = False
Exemplo n.º 19
0
def test_find_move():
    board = Board(8, 8, 100)
    gm = GameManager(board)

    gm.find_moves(gm.board.spaces[3][4], 255)
    assert gm.legal_move == {(5, 4): [(4, 4)], (3, 2): [(3, 3)]}

    gm.find_moves(gm.board.spaces[4][3], 255)
    assert gm.legal_move == {
        (5, 4): [(4, 4)],
        (2, 3): [(3, 3)],
        (4, 5): [(4, 4)],
        (3, 2): [(3, 3)]
    }

    # reset the dictionary to empty
    gm.legal_move = dict()

    gm.find_moves(gm.board.spaces[3][3], 0)
    assert gm.legal_move == {(3, 5): [(3, 4)], (5, 3): [(4, 3)]}

    gm.find_moves(gm.board.spaces[4][4], 0)
    assert gm.legal_move == {
        (3, 5): [(3, 4)],
        (5, 3): [(4, 3)],
        (4, 2): [(4, 3)],
        (2, 4): [(3, 4)]
    }
Exemplo n.º 20
0
class Test(unittest.TestCase):

    game = None

    def setUp(self):
        self.gm = GameManager()

        self.chat0 = Chat(0, 'group')
        self.chat1 = Chat(1, 'group')
        self.chat2 = Chat(2, 'group')

        self.user0 = User(0, 'user0')
        self.user1 = User(1, 'user1')
        self.user2 = User(2, 'user2')

    def test_new_game(self):
        g0 = self.gm.new_game(self.chat0)
        g1 = self.gm.new_game(self.chat1)

        self.assertListEqual(self.gm.chatid_games[0], [g0])
        self.assertListEqual(self.gm.chatid_games[1], [g1])

    def test_join_game(self):

        self.assertRaises(NoGameInChatError,
                          self.gm.join_game,
                          *(self.user0, self.chat0))

        g0 = self.gm.new_game(self.chat0)

        self.gm.join_game(self.user0, self.chat0)
        self.assertEqual(len(g0.players), 1)

        self.gm.join_game(self.user1, self.chat0)
        self.assertEqual(len(g0.players), 2)

        g0.open = False
        self.assertRaises(LobbyClosedError,
                          self.gm.join_game,
                          *(self.user2, self.chat0))

        g0.open = True
        self.assertRaises(AlreadyJoinedError,
                          self.gm.join_game,
                          *(self.user1, self.chat0))

    def test_leave_game(self):
        g0 = self.gm.new_game(self.chat0)

        self.gm.join_game(self.user0, self.chat0)
        self.gm.join_game(self.user1, self.chat0)

        self.assertRaises(NotEnoughPlayersError,
                          self.gm.leave_game,
                          *(self.user1, self.chat0))

        self.gm.join_game(self.user2, self.chat0)
        self.gm.leave_game(self.user0, self.chat0)

        self.assertRaises(NoGameInChatError,
                          self.gm.leave_game,
                          *(self.user0, self.chat0))

    def test_end_game(self):
        g0 = self.gm.new_game(self.chat0)

        self.gm.join_game(self.user0, self.chat0)
        self.gm.join_game(self.user1, self.chat0)

        self.assertEqual(len(self.gm.userid_players[0]), 1)

        g1 = self.gm.new_game(self.chat0)
        self.gm.join_game(self.user2, self.chat0)

        self.gm.end_game(self.chat0, self.user0)
        self.assertEqual(len(self.gm.chatid_games[0]), 1)

        self.gm.end_game(self.chat0, self.user2)
        self.assertFalse(0 in self.gm.chatid_games)
        self.assertFalse(0 in self.gm.userid_players)
        self.assertFalse(1 in self.gm.userid_players)
        self.assertFalse(2 in self.gm.userid_players)
Exemplo n.º 21
0
def test_player_make_move():
    board_1 = Board(4, 4, 100)
    gm_1 = GameManager(board_1)
    gm_1.player_make_move(10, 100)
    assert gm_1.legal_move == {
        (0, 1): [(1, 1)],
        (1, 0): [(1, 1)],
        (2, 3): [(2, 2)],
        (3, 2): [(2, 2)]
    }
    assert gm_1.board.spaces[0][1].color == 0

    board_2 = Board(8, 8, 100)
    gm_2 = GameManager(board_2)
    gm_2.player_make_move(10, 10)
    assert gm_2.legal_move == {
        (5, 4): [(4, 4)],
        (2, 3): [(3, 3)],
        (4, 5): [(4, 4)],
        (3, 2): [(3, 3)]
    }
    assert not gm_2.board.spaces[0][0]

    board_3 = Board(6, 6, 100)
    gm_3 = GameManager(board_3)
    gm_3.player_make_move(400, 300)
    assert gm_3.legal_move == {
        (1, 2): [(2, 2)],
        (4, 3): [(3, 3)],
        (3, 4): [(3, 3)],
        (2, 1): [(2, 2)]
    }
    assert gm_3.board.spaces[4][3].color == 0
Exemplo n.º 22
0
from game_manager import GameManager
from agents import UniformRandomAgent
from . import get_results_path

results_path = get_results_path(__name__)

agent = UniformRandomAgent()
gm = GameManager("pong.bin",
                 agent,
                 results_path,
                 n_epochs=3,
                 n_episodes=10,
                 remove_old_results_dir=True,
                 use_minimal_action_set=True)
gm.run()
Exemplo n.º 23
0
def test_player_make_move():
    board_1 = Board(4, 4, 100)
    gm_1 = GameManager(board_1)
    gm_1.ai_make_move()
    assert gm_1.legal_move == {
        (0, 2): [(1, 2)],
        (1, 3): [(1, 2)],
        (2, 0): [(2, 1)],
        (3, 1): [(2, 1)]
    }

    board_2 = Board(8, 8, 100)
    gm_2 = GameManager(board_2)
    gm_2.ai_make_move()
    assert gm_2.legal_move == {
        (2, 4): [(3, 4)],
        (3, 5): [(3, 4)],
        (4, 2): [(4, 3)],
        (5, 3): [(4, 3)]
    }

    board_3 = Board(6, 6, 100)
    gm_3 = GameManager(board_3)
    gm_3.ai_make_move()
    assert gm_3.legal_move == {
        (1, 3): [(2, 3)],
        (2, 4): [(2, 3)],
        (3, 1): [(3, 2)],
        (4, 2): [(3, 2)]
    }
Exemplo n.º 24
0
class App:
    def __init__(self):
        self.setup_gui()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)
        self.key_listener()
        self.move_monsters()  # enable: monsters move periodically
        self.root.mainloop()

    def setup_gui(self):
        self.create_window()
        self.game_manager = GameManager()
        self.create_canvas()
        self.create_stat_bar()
        self.create_description()
        self.create_info_bar()

    def create_window(self):
        self.root = Tk()
        self.root.title("Wanderer by Mark Ambrus")

    def create_canvas(self):
        self.size = self.game_manager.area.size
        self.canvas = Canvas(self.root, width=self.size, height=self.size)
        self.canvas.pack()
        self.fill_canvas()

    def fill_canvas(self):
        self.game_manager.area.draw_map(self.canvas)
        self.game_manager.spawn_characters(self.canvas)

    def create_stat_bar(self):
        self.hero_stat_bar = Label(text=self.game_manager.hero.introduce())
        self.hero_stat_bar.pack()

    def create_description(self):
        self.game_description = Label(text='''Welcome to the Wanderer game!
            Let's play! Use the arrow keys or WASD to move the hero.
            Cross path with monsters to fight them.
            Collect the key and kill the boss to go to the next level.''')
        self.game_description.pack()

    def create_info_bar(self):
        self.progress_info = Label(
            text="Area: " + str(self.game_manager.area_number) + " | " +
            str(self.game_manager.kill_count) + " monsters slayed.")
        self.progress_info.pack()

    def key_listener(self):
        self.canvas.bind("<KeyPress>", self.on_key_press)
        self.canvas.focus_set()

    def on_key_press(self, e):
        # W or w or up arrow key
        if e.keycode == 87 or e.keycode == 119 or e.keycode == 8320768:
            direction = 'up'
        # S or s or down arrow key
        elif e.keycode == 83 or e.keycode == 115 or e.keycode == 8255233:
            direction = 'down'
        # A or a or left arrow key
        elif e.keycode == 65 or e.keycode == 97 or e.keycode == 8124162:
            direction = 'left'
        # D or d or right arrow key
        elif e.keycode == 68 or e.keycode == 100 or e.keycode == 8189699:
            direction = 'right'
        else:
            return
        self.game_turn(direction)

    def game_turn(self, direction):
        self.game_manager.set_hero_position(self.canvas, direction)
        self.after_move()

    def move_monsters(self):
        wait = self.calculate_wait()
        self.game_manager.move_monsters(self.canvas)
        self.after_move()
        self.root.after(wait, self.move_monsters)

    def calculate_wait(self):
        difficulty = (self.game_manager.area_number - 1) * 40
        wait = 1500 - difficulty  # max 1.5 sec wait
        min_wait = 300  # min 0.3 sec wait
        if wait < min_wait:
            return min_wait
        else:
            return wait

    def after_move(self):
        self.check_hero_death()
        self.game_manager.check_next_area(self.canvas)
        self.config_labels()

    def check_hero_death(self):
        if self.game_manager.hero.current_health <= 0:
            self.canvas.delete("all")
            self.game_manager = GameManager()
            self.fill_canvas()

    def config_labels(self):
        self.progress_info.config(
            text="Area: " + str(self.game_manager.area_number) + " | " +
            str(self.game_manager.kill_count) + " monsters slayed.")
        self.hero_stat_bar.config(text=self.game_manager.hero.introduce())

    def callback(self):
        self.root.quit()
Exemplo n.º 25
0
    def on_close(self):
        print("client disconnected")

    def check_origin(self, origin):
        return True

    def send_message(self, action, **data):
        message = {"action": action, "data": data}
        try:
            self.write_message(json.dumps(message))

        except tornado.WebSocketClosedError:
            #logger.warning("WS_CLOSED", "Could Not send Message: " + json.dumps(message))
            # Send Websocket Closed Error to Paired Opponent
            #self.send_pair_message(action="pair-closed")
            self.close()


gameManager = GameManager()

urls = [
    (r"/", MainHandler),
    (r"/demo/ws", SocketHandler, dict(game_manager=gameManager)),
]

port = int(os.environ.get('PORT', 5000))

if __name__ == "__main__":
    app = tornado.web.Application(urls, **settings)
    app.listen(port)
    tornado.ioloop.IOLoop.current().start()
Exemplo n.º 26
0
class GameManagerTest(unittest.TestCase):
    """Unit tests for game manager module."""
    def setUp(self):
        """Initialises all test cases."""
        self.game = GameManager()
        self.game.frame_counter = 0
        self.game.frame_scores = None
        self.game.roll = 0
        self.maxDiff = None

    def test_get_score(self):
        """Verifies, score is fetched in expected format when is ongoing.

        And if game has not started yet, error string should be returned."""
        # Case 1: Game is not started yet, should return error message.
        self.assertEqual(self.game.get_score(),
                         {'message': constants.GAME_NOT_STARTED})

        # Case 2: No pins knocked, should return initial score.
        self.game.start_new_game()
        frame_scores = {
            frame_id: {
                'roll': {
                    0: -1,
                    1: -1
                },
                'score': -1
            }
            for frame_id in range(constants.TOTAL_FRAMES)
        }
        expected_rsp = {'frame-scores': frame_scores, 'total-score': 0}
        self.assertEqual(self.game.get_score(), expected_rsp)

    def test_pins_knocked_negative(self):
        """Verifies that if pins knocked is invalid, error is returned."""
        # Case 1: Game not started, should return relevant error message.
        self.assertEqual(
            self.game.pins_knocked('5'),
            {'message': constants.PINS_KNOCKED_BEFORE_GAME_STARTED})

        self.game.start_new_game()

        # Case 2: Pins knocked is not number, should return relevant error.
        self.assertEqual(self.game.pins_knocked('a'),
                         {'message': constants.INVALID_PINS_KNOCKED})

        # Case 3: Pins knocked more than 10, should return relevant error.
        self.assertEqual(self.game.pins_knocked('20'),
                         {'message': constants.INVALID_PINS_KNOCKED})

        # Case 4: Sum of pins knocked in first and second roll exceeds 10.
        roll1 = '8'
        roll2 = '5'
        self.assertEqual(self.game.pins_knocked(roll1),
                         {'message': constants.SCORES_UPDATED})

        err_msg = constants.INVALID_SECOND_ROLL.format(first_roll_pins=roll1)
        self.assertEqual(self.game.pins_knocked(roll2), {'message': err_msg})

        # Case 5: Pins knocked received when game has ended, should ask for
        # starting new game.
        self.game.start_new_game()
        for roll in range(2 * constants.TOTAL_FRAMES):
            self.assertEqual(self.game.pins_knocked('1'),
                             {'message': constants.SCORES_UPDATED})

        self.assertEqual(self.game.pins_knocked('1'),
                         {'message': constants.GAME_ENDED})

    def test_pins_knocked_all_strikes(self):
        """Verifies perfect 300 case."""
        self.game.start_new_game()
        # Last frame has 3 rolls so +2.
        for roll in range(constants.TOTAL_FRAMES + 2):
            self.assertEqual(self.game.pins_knocked('10'),
                             {'message': constants.SCORES_UPDATED})

        # Verify score after all strikes.
        scores = {}
        for frame in range(constants.TOTAL_FRAMES - 1):
            scores[frame] = {'roll': {0: 10, 1: -1}, 'score': 30}

        # Update score for last frame.
        scores[constants.TOTAL_FRAMES - 1] = {
            'roll': {
                0: 10,
                1: 10,
                2: 10
            },
            'score': 30
        }

        self.assertEqual(self.game.get_score(), {
            'frame-scores': scores,
            'total-score': 300
        })

    def test_pins_knocked_all_spares(self):
        """Verifies case when all frames knocked with a spare."""
        self.game.start_new_game()
        # Last frame has 3 rolls so +1.
        for roll in range(2 * constants.TOTAL_FRAMES + 1):
            self.assertEqual(self.game.pins_knocked('5'),
                             {'message': constants.SCORES_UPDATED})

        # Verify score after all spares.
        scores = {}
        for frame in range(constants.TOTAL_FRAMES - 1):
            scores[frame] = {'roll': {0: 5, 1: 5}, 'score': 15}

        # Update score for last frame.
        scores[constants.TOTAL_FRAMES - 1] = {
            'roll': {
                0: 5,
                1: 5,
                2: 5
            },
            'score': 15
        }

        self.assertEqual(self.game.get_score(), {
            'frame-scores': scores,
            'total-score': 150
        })

    def test_pins_knocked_normal(self):
        """Verifies case when no frame is knocked with a strike or spare."""
        self.game.start_new_game()
        for roll in range(2 * constants.TOTAL_FRAMES):
            self.assertEqual(self.game.pins_knocked('4'),
                             {'message': constants.SCORES_UPDATED})

        scores = {}
        for frame in range(constants.TOTAL_FRAMES):
            scores[frame] = {'roll': {0: 4, 1: 4}, 'score': 8}

        self.assertEqual(self.game.get_score(), {
            'frame-scores': scores,
            'total-score': 80
        })
Exemplo n.º 27
0
def main():
    game_manager = GameManager()
    game_manager.run_game()
Exemplo n.º 28
0
import random
from game_manager import GameManager
gm = GameManager.instance()


class GameObject:
    def __init__(self, pos, size, color):
        self.x = pos[0]
        self.y = pos[1]
        self.width = size[0]
        self.heigth = size[1]
        self.color = color
        self.pivot = (self.x - self.width / 2, self.y - self.heigth / 2)

    def getpos(self):
        return (self.x, self.y)

    def setpos(self, value):
        self.x = value[0]
        self.y = value[1]

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, value):
        self.__x = value

    @property
    def y(self):
Exemplo n.º 29
0
import pygame
import os
from game_manager import GameManager
from board import Board
from constants import WIDTH, HEIGHT

pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
pygame.display.set_caption("Chess")
pygame.display.set_icon(
    pygame.image.load(f"{os.getcwd()}\images\\white_king.png"))
screen = pygame.display.set_mode((WIDTH, HEIGHT))

game = GameManager(screen)

while True:
    clock.tick(60)
    game.draw()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game.quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = game.get_clicked()
            game.select(x, y)

        if event.type == pygame.KEYDOWN:
            game.started = True
            if event.key == pygame.K_r:
Exemplo n.º 30
0
import os
import pandas as pd
from threading import Thread
import queue
import requests
import threading
#from predict_cards import predict_box, show_class, draw_bounding_box#, predictThread # , predict_image
from predict_cards_RetNet import draw_detections, predict_image, predictThread, predict_cropped
from game_manager import GameManager

labels_to_names = pd.read_csv('classes.csv', header=None,
                              index_col=0).to_dict()[1]

WIDTH = 1280  #1920
HEIGHT = 720  #1080
Manager = GameManager(WIDTH, HEIGHT)

url = "http://192.168.1.113:8080/shot.jpg"


def show_webcam(mirror=False):
    #cam = cv2.VideoCapture(1)   # 0 for build in cam, 1 for usb cam
    #if not cam.isOpened():
    #    print('Could not open video')
    #    return
    pred_thread = predictThread()
    bboxes = []
    classes = []
    confis = []
    frame = 0
    cv2.namedWindow('webcam', cv2.WINDOW_NORMAL)
Exemplo n.º 31
0
    i: int = 25

    while i > 0:

        print(
            "\n-----------------------\n-----------------------\n-----------------------\nSTORY {}\n"
            .format(25 - i))

        GameManager.new_game(player_data=[{
            "name": 'Player 1',
            "spotlight_modifier": 4
        }, {
            "name": 'Player 2'
        }, {
            "name": 'Player 3'
        }, {
            "name": 'Player 4'
        }],
                             mps={
                                 "mental": 0,
                                 "physical": 0,
                                 "social": 1
                             },
                             story_template="journey")

        GameManager.run_story_introduction()
        n: int = GameManager.storyworld.story_template.scene_length
        while n > 0:
            GameManager.run_scene()
            n -= 1
        GameManager.run_story_ending()
Exemplo n.º 32
0
import pygame
from game_manager import GameManager

# Initialize pygame
pygame.init()
clock = pygame.time.Clock()
pygame.display.set_caption('Man\'s Labyrinth')

gameExit = False
generated = False

# Initialize the game manager
gm = GameManager()

while not gameExit:
    # Keep generating the maze if not done generating
    if not gm.maze.generated:
        gm.generate_maze()

    # Handle user events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

        gm.handle_event(event)

    gm.menu.update(gm.disp)
    pygame.display.update()  # draw to screen
    clock.tick(60)  # fps limit

pygame.quit()
Exemplo n.º 33
0
from game_manager import GameManager
from agents import SmartAgent
from . import get_results_path

results_path = get_results_path(__name__)

agent = SmartAgent()

gm = GameManager("pong.bin",
                 agent, results_path,
                 n_epochs=5, n_episodes=8,
                 remove_old_results_dir=True, use_minimal_action_set=True, 
                 min_time_between_frames=0.0)

gm.run()
Exemplo n.º 34
0
from game_manager import GameManager


game_manager = GameManager()
game_manager.start_game(2, 3)
Exemplo n.º 35
0
#!/usr/bin/env python

from game_manager import GameManager

manager = GameManager()
manager.menu()
Exemplo n.º 36
0
from game_manager import GameManager
from agents import UniformRandomAgent

agent = UniformRandomAgent()
gm = GameManager("pong.bin", agent, 'results/testbed2',
                 remove_old_results_dir=True, use_minimal_action_set=True, visualise='rgb')
gm.run(n_episodes=10)
Exemplo n.º 37
0
        if s is not '':
            mct.deserialize(s)
    with open('mct_states', 'w') as mf:
        mf = mf.write(str(mct.record_length()))

game_state = StateMap()
states_in_game = []
is_discard_locked = False
game_count = 0
game_win = 0
game_lost = 0
prev_tiles = []
is_declare_updated = True

# Initializes game manager
game_mgr = GameManager()

# PLAY FUNCTION


def lets_play_it():
    global game_mgr, game_state, mct, is_discard_locked, prev_tiles, is_declare_updated
    if not game_mgr.is_game_active():
        return
    if game_mgr.is_game_paused():
        print('Game paused. Our state is {}'.format(game_mgr.are_we_ready()))
        if not game_mgr.are_we_ready():
            game_mgr.send_ready()
        return
    if game_mgr.get_game_state() == client.DeclaringSpecials and \
            game_mgr.is_our_turn() and not game_mgr.is_finish_declaring() \
Exemplo n.º 38
0
from fastapi.responses import JSONResponse, RedirectResponse
from pyaxidraw.axidraw import AxiDraw
from pydantic import BaseModel
from quickdraw import QuickDrawData
import urllib
from game_manager import GameManager

app = FastAPI()

logging.basicConfig(level=logging.DEBUG)

log = logging.getLogger(__name__)

axidraw_client = AxiDraw()
quickdraw_client = QuickDrawData()
game_manager = GameManager(axidraw_client, quickdraw_client)
game_thread = None


class GuessRequest(BaseModel):
    guess: str


@app.on_event("shutdown")
def shutdown_event():
    log.info("shutting down")
    if game_thread is not None:
        log.debug("Joining game thread")
        game_thread.join()
        log.debug("game thread joined")
Exemplo n.º 39
0
'''
Created on Jul 2, 2015

@author: jobota
'''
import os
import ConfigParser

from game_manager import GameManager
from event_factory import EventFactory
from dialog_factory import DialogFactory

cfg = ConfigParser.ConfigParser()
cfg.read(os.getcwd() + "\src\config.ini")
dia = cfg.get("settings", "dialog.xml")
eve = cfg.get("settings", "event.xml")
dif = float(cfg.get("settings", "difficulty"))

gm = GameManager(dia, eve, dif)
gm.update()
"""eve = EventFactory(eve)
dia = DialogFactory(dia)
eve.generate_event()
dia.generate_dialog()

print dia.dialog_name()
print dia.dialog_text()
print dia.dialog_options()"""

    
Exemplo n.º 40
0
def change_turn():
    GameManager.change_turn()
Exemplo n.º 41
0
from game_manager import GameManager
import object
import threading


#if __name__ == "__main__":
GameManager.init()
#key = GameManager.create_object(object.MovingObject())
#GameManager.get_object(key).set_accelerate((1, 1))
GameManager.create_object(object.StaticObject(position=(300, 300), size=(300, 300)))
GameManager.create_object(object.StaticObject(position=(0, 748), size=(1376, 20)))
#GameManager.create_object((object.MovingObject(position=(100, 100), size=(100, 50))))
GameManager.start()