Exemple #1
0
    def __init__(self, gameEngine):
        super().__init__(gameEngine)

        self.window = GameEngine.GameWindow(1600, 800)

        # Initialise cameras

        self.cameras = []

        screen0 = GameEngine.GameScreen(self.window, 0, 0, 800, 800)
        screen1 = GameEngine.GameScreen(self.window, 800, 0, 800, 800)

        self.cameras.append(GameEngine.GameCamera(screen0, (0, 0, -20)))
        self.cameras.append(GameEngine.GameCamera(screen1, (0, 0, -20), 120))

        for i, cam in enumerate(self.cameras):
            cam.setName("Cam{:}".format(i))

        self.activeCamera = self.cameras[0]

        # Initialise GameObjects

        self.cube = Object3D.Cube((0, 0, 0), (10, 10, 10))

        self.change = 100
Exemple #2
0
    def test_multigame_support(self):
        game_type = GameType.NERF_ASSASSIN
        game_name = "Test Game 2"
        game_start = datetime.now()

        game1 = GameEngine.new_game(game_type, game_name, game_start)
        game2 = GameEngine.new_game(game_type, game_name, game_start)
        self.assertNotEqual(game1.id, game2.id)
def post_move():
    start = request.json.get('start')
    end = request.json.get('end')
    is_white = request.json.get('isWhite')
    game_id = request.json.get('gameId')

    user = users.get_current_user()
    logging.info(user.user_id())

    oldBoard = models.Gameboard.query().filter(models.Gameboard.gameID == game_id).fetch(1)

    if len(oldBoard) == 0:
        logging.info("board is of length 0")

    positions = oldBoard[0].board

    move = GameEngine.isValidMove(positions, oldBoard[0].promotions, is_white, start, end)

    logging.info("move made")
    logging.info(start)
    logging.info(end)
    logging.info(game_id)

    if move >= 3:
        oldBoard[0].lastMove = end
        oldBoard[0].isWhite = not is_white
        if move >= 4:
            positions[move - 4] = 0

        for loc in range(0, 32):
            if positions[loc] == start:
                positions[loc] = end
                break

        oldBoard[0].board = positions
        oldBoard[0].promotions = promote_pawn(oldBoard[0])
        oldBoard[0].put()

    checkLocs = GameEngine.inCheckLocs(oldBoard[0].board, oldBoard[0].promotions, not oldBoard[0].isWhite)

    if GameEngine.inCheckMate(oldBoard[0].board, oldBoard[0].promotions, True):
        oldBoard[0].loser = 1
        oldBoard[0].put()
    elif GameEngine.inCheckMate(oldBoard[0].board, oldBoard[0].promotions, False):
        oldBoard[0].loser = 2
        oldBoard[0].put()

    response.content_type = 'application/json'
    return models.move_response_to_json(move, oldBoard[0].board, oldBoard[0].loser, checkLocs, oldBoard[0].promotions)
Exemple #4
0
    def test01_adding_participants(self):
        assassin1_id = GameEngine.new_user("Ass", "Assin1")
        self.assertGreaterEqual(assassin1_id, 0)
        assassin2_id = GameEngine.new_user("Ass", "Assin2")
        self.assertGreaterEqual(assassin2_id, 0)
        assassin3_id = GameEngine.new_user("Ass", "Assin3")
        self.assertGreaterEqual(assassin3_id, 0)

        self.assertEqual(self.game.num_participants, 0)
        self.game.add_participant(assassin1_id, "Assassin1")
        self.assertEqual(self.game.num_participants, 1)
        self.game.add_participant(assassin2_id, "Assassin2")
        self.assertEqual(self.game.num_participants, 2)
        self.game.add_participant(assassin3_id, "Assassin3")
        self.assertEqual(self.game.num_participants, 3)
Exemple #5
0
 def generateThrow(self, scoreLeft, dartsLeft):
     # normally get score remaining and dart remaining for player
     # scoreLeft = game.currentPlayer.score
     # dartLeft = game.dartsLeft 
     (score, multiplier) = self.selectTarget(scoreLeft, dartsLeft)
     # pass target (score, multipler) to bryan
     # ======= dart = getTarget (score, multiplier) ======
     (magnitude, angle) = dartRegion.RegionToLocation(score, multiplier)
     print "The mag: " + str(magnitude) + " and the angle: " + str(angle)
     magnitude = random.gauss(magnitude, self.difficulty)
     angle = random.gauss(angle, self.difficulty)
     
     (score, multiplier) = dartRegion.LocationToRegion(angle, magnitude)
     print "The score: " + str(score) + " and the multi: " + str(multiplier)
     
     # scale the angle and magnitude
     angle = math.radians(angle)
     magnitude = magnitude * (380./calibration.ring_radius[5]) 
     #if multiplier == 3:
         #multiplierWord = "triple "
     #elif multiplier == 2:
         #multiplierWord = "double "
     #else:
         #multiplierWord = "single "
     #print "aim at " + multiplierWord + str(score) + " when " + str(scoreLeft) + " Left"
     dartThrow = GameEngine.dartThrow()
     dartThrow.base = score
     
     dartThrow.multiplier = multiplier
     dartThrow.magnitude = magnitude
     dartThrow.angle = angle
     return dartThrow
Exemple #6
0
    def testDealerP2(self):
        deck = copy.deepcopy(self.deck)
        players = [Player(), Player()]
        GameEngine.deal(players, deck, 1)

        actualCards = []
        for card in players[1].hand:
            actualCards.append((card['suit'], card['rank']))
        self.assertEqual([('S', 8), ('C', 9), ('H', 10), ('S', 8), ('C', 9),
                          ('H', 10)], actualCards)

        actualCards = []
        for card in players[0].hand:
            actualCards.append((card['suit'], card['rank']))
        self.assertEqual([('H', 8), ('S', 7), ('H', 10), ('H', 8), ('S', 7),
                          ('H', 10)], actualCards)
def new_game():
    oldBoard = models.Gameboard.query().order(-models.Gameboard.gameID).fetch(1)

    if len(oldBoard) > 0 and not oldBoard[0].hasStarted:
        oldBoard[0].hasStarted = True
        user = users.get_current_user()
        oldBoard[0].blackId=user.user_id()
        oldBoard[0].put()
        response.content_type = 'application/json'
        return models.new_game_to_json('black', oldBoard[0].gameID)
    else:
        id = 0

        if len(oldBoard) == 1:
            id = oldBoard[0].gameID+1

        user = users.get_current_user()
        board = models.Gameboard(isWhite=True,
                                 board=GameEngine.getInitialState(),
                                 gameID=id,
                                 hasStarted=False,
                                 lastMove=0,
                                 whiteId=user.user_id(),
                                 promotions=[False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False]
        )

        board.put()
        response.content_type = 'application/json'
        return models.new_game_to_json('white', board.gameID)
Exemple #8
0
    def generateThrow(self, scoreLeft, dartsLeft):
        # normally get score remaining and dart remaining for player
        # scoreLeft = game.currentPlayer.score
        # dartLeft = game.dartsLeft
        (score, multiplier) = self.selectTarget(scoreLeft, dartsLeft)
        # pass target (score, multipler) to bryan
        # ======= dart = getTarget (score, multiplier) ======
        (magnitude, angle) = dartRegion.RegionToLocation(score, multiplier)
        print "The mag: " + str(magnitude) + " and the angle: " + str(angle)
        magnitude = random.gauss(magnitude, self.difficulty)
        angle = random.gauss(angle, self.difficulty)

        (score, multiplier) = dartRegion.LocationToRegion(angle, magnitude)
        print "The score: " + str(score) + " and the multi: " + str(multiplier)

        # scale the angle and magnitude
        angle = math.radians(angle)
        magnitude = magnitude * (380. / calibration.ring_radius[5])
        #if multiplier == 3:
        #multiplierWord = "triple "
        #elif multiplier == 2:
        #multiplierWord = "double "
        #else:
        #multiplierWord = "single "
        #print "aim at " + multiplierWord + str(score) + " when " + str(scoreLeft) + " Left"
        dartThrow = GameEngine.dartThrow()
        dartThrow.base = score

        dartThrow.multiplier = multiplier
        dartThrow.magnitude = magnitude
        dartThrow.angle = angle
        return dartThrow
Exemple #9
0
 def __init__(self, map, seekerRowPos, seekerColPos, hiderList,stack):
     p.init()
     self.seekerRowPos = seekerRowPos
     self.seekerColPos = seekerColPos
     self.hiderList = hiderList
     self.gs = GameEngine.GameState(map)
     self.loadImage()
     self.stack = stack
Exemple #10
0
def printMenu(selected_row):
    renderer.erase()
    dbgText = GameEngine.RenderObject()
    selection = GameEngine.RenderObject()
    for i, row in enumerate(menuSelection):
        x = renderer.xBorder//2 - len(row)//2
        y = (renderer.yBorder//2 - len(menuSelection)//2 + i) + 3
        if i == selected_row:
            #dbgText.drawObject(2, y+1, "Row:{} X:{} Y:{}".format(row, x, y))
            selection.enableColor(GameEngine.PAIR_HIGHLIGHT, GameEngine.WR)
            selection.drawObject(x,y, row,GameEngine.WR)
            selection.disableColor(GameEngine.PAIR_HIGHLIGHT, GameEngine.WR)
        else:
           # dbgText.drawObject(2, y + 1, "Row:{} X:{} Y:{}".format(row, x, y))
            selection.drawObject(x, y, row, GameEngine.WR)

    renderer.refresh()
Exemple #11
0
    def test_game_creation(self):

        game_type = GameType.NERF_ASSASSIN
        game_name = "Test Game 1"
        game_start = datetime.now()

        game = GameEngine.new_game(game_type, game_name, game_start)
        self.assertEqual(game_type, game.type)
Exemple #12
0
    def test02_adding_duplicate_participant(self):

        assassin2_id = GameEngine.new_user("Ass", "Assin2")
        self.assertGreaterEqual(assassin2_id, 0)

        self.game.add_participant(assassin2_id, "Assassin2")
        self.assertRaises(UserCommunicationException,
                          self.game.add_participant, assassin2_id, "Assassin2")
        self.assertEqual(self.game.num_participants, 1)
Exemple #13
0
def GameOver(score):
    renderer.erase()
    border = GameEngine.RenderObject()
    GameOver = GameEngine.RenderObject()
    yourName = GameEngine.InputHandler()
    border.drawBorder()
    scoreStr = "SCORE : {}".format(score)
    GameOver.drawObject((renderer.xBorder//2) - len("Game Over!")//2, renderer.yBorder//2, "Game Over!")
    GameOver.drawObject((renderer.xBorder // 2) - len(scoreStr) // 2, (renderer.yBorder // 2)+1, scoreStr)
    GameOver.drawObject((renderer.xBorder // 2) - len("Your Name:") // 2, (renderer.yBorder // 2) + 2, "Your Name: ")
    curses.echo()
    curses.curs_set(1)
    name = yourName.getStringInput(((renderer.xBorder // 2) + len("Your Name:")//2) + 1 ,  (renderer.yBorder // 2) + 2)
    curses.curs_set(0)
    curses.noecho()

    FileHandler.saveScore(name.decode("utf-8"), score)
    time.sleep(5)
    Leaderboard()
Exemple #14
0
    def test03_register_kill_before_start(self):

        assassin1_id = GameEngine.new_user("Ass", "Assin1")
        self.assertGreaterEqual(assassin1_id, 0)
        assassin2_id = GameEngine.new_user("Ass", "Assin2")
        self.assertGreaterEqual(assassin2_id, 0)
        assassin3_id = GameEngine.new_user("Ass", "Assin3")
        self.assertGreaterEqual(assassin3_id, 0)

        self.assertEqual(self.game.num_participants, 0)
        self.game.add_participant(assassin1_id, "Assassin1")
        self.assertEqual(self.game.num_participants, 1)
        self.game.add_participant(assassin2_id, "Assassin2")
        self.assertEqual(self.game.num_participants, 2)
        self.game.add_participant(assassin3_id, "Assassin3")
        self.assertEqual(self.game.num_participants, 3)

        self.assertRaises(UserCommunicationException, self.game.register_kill,
                          "Assassin1", "Assassin2")
Exemple #15
0
    def test04_adding_pariticpant_after_start(self):

        self.game.change_start_date(datetime.now())
        self.game.start_game()

        assassin6_id = GameEngine.new_user("Ass", "Assin6")
        self.assertGreaterEqual(assassin6_id, 0)

        self.assertRaises(UserCommunicationException,
                          self.game.add_participant, assassin6_id, "Assassin6")
Exemple #16
0
    def test_valueable_object(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)

        beh = b.ValuableObject()

        assert beh.name == 'ValuableObject'
        assert beh.cost == 0

        beh.set_cost(100)
        assert beh.cost == 100
Exemple #17
0
    def test_game_types(self):

        from NerfAssassin import NerfAssassin
        #from NerfZombie import NerfZombie
        #from TeamAssassin import TeamAssassin

        nerf_assassin = GameEngine.new_game(GameType.NERF_ASSASSIN,
                                            "Nerf Assasin Test Game 0",
                                            datetime.now())
        self.assertIsNotNone(nerf_assassin)
        self.assertIsInstance(nerf_assassin, NerfAssassin)
Exemple #18
0
def Leaderboard():
    renderer.erase()
    border = GameEngine.RenderObject()
    LeaderboardTitle = GameEngine.RenderObject()
    rectangle = GameEngine.RenderObject()
    LeaderboardObj = GameEngine.RenderObject()
    border.drawBorder()
    LeaderboardTitle.enableColor(GameEngine.PAIR_HIGHLIGHT)
    LeaderboardTitle.drawObject(renderer.xBorder // 2 - len("LEADERBOARD")//2, renderer.yBorder // 2 - 13, "LEADERBOARD")
    LeaderboardTitle.disableColor(GameEngine.PAIR_HIGHLIGHT)
    rectangle.drawRect((renderer.xBorder//2) - len("LEADERBOARD") - 10, (renderer.yBorder//2) - 10,40,20)
    scores = FileHandler.readScore()
    scores.sort(key= lambda x: x[1], reverse=True)
    for num, line in enumerate(scores):
        leaderboardLine = "{}. {} ........ SCORE: {}"
        LeaderboardObj.drawObject((renderer.xBorder//2) - len("LEADERBOARD") - 9, (renderer.yBorder//2) - 9 + 2*num, leaderboardLine.format(num+1,line[0].upper(),line[1]))
        if num > 8:
            break
    renderer.refresh()
    time.sleep(10)
    main()
Exemple #19
0
def MainMenu():
    renderer.erase()
    row = 0
    selectedRow = 0
    printMenu(row)
    input = GameEngine.InputHandler()
    dbgText = GameEngine.RenderObject()
    logoDrawer = GameEngine.RenderObject()
    border = GameEngine.RenderObject()
    box = GameEngine.RenderObject()
    copyrightText = "© 2019 Kelompok KebalSP - LD01 -  BINUS University @Bandung"
    copyrightDrawer = GameEngine.RenderObject()
    border.drawBorder()
    while(True):
        box.drawRect(54, 15, 12, 5, GameEngine.WR)
        border.drawBorder(GameEngine.WR)
        for yPos, lines in enumerate(title):
            logoDrawer.drawObject((renderer.xBorder//2) - 25, 5+yPos, lines, GameEngine.WR)
        copyrightDrawer.drawObject((renderer.xBorder//2) - len(copyrightText)//2, renderer.yBorder-2, copyrightText )
        key = input.getInput()
        if key == curses.KEY_UP and row > 0:
            row -= 1
        elif key == curses.KEY_DOWN and row < len(menuSelection)-1:
            row += 1
        elif key == curses.KEY_ENTER or key in [10, 13]:

            break
        printMenu(row)

    return row
Exemple #20
0
    def test_defence_tower_attack(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)

        beh = b.DefenceTowerAttack()

        assert beh.name == 'DefenceTowerAttack'
        assert beh.attack_radius == 150
        beh.set_attack_radius(100)
        assert beh.attack_radius == 100
        assert beh.damage == 3
        beh.set_damage(5)
        assert beh.damage == 5
Exemple #21
0
    def test_gold_manager(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)

        beh = b.GoldManager()

        assert beh.name == 'GoldManager'

        beh.set_gold(100)
        assert beh.gold == 100

        beh.change_gold(100)
        assert beh.gold == 200
Exemple #22
0
    def testDiscard(self, input):
        deck = copy.deepcopy(self.deck)
        players = [Player(), Player()]
        GameEngine.deal(players, deck, 0)
        crib = (GameEngine.discard(players))

        actualCards = []
        for card in players[0].hand:
            actualCards.append((card['suit'], card['rank']))
        self.assertEqual([('H', 10), ('S', 8), ('C', 9), ('H', 10)],
                         actualCards)

        actualCards = []
        for card in players[1].hand:
            actualCards.append((card['suit'], card['rank']))
        self.assertEqual([('H', 10), ('H', 8), ('S', 7), ('H', 10)],
                         actualCards)

        actualCards = []
        for card in crib:
            actualCards.append((card['suit'], card['rank']))
        self.assertEqual([('S', 8), ('C', 9), ('H', 8), ('S', 7)], actualCards)
def opponent_moved():

    game_id = request.json.get('gameId')

    oldBoard = models.Gameboard.query().filter(models.Gameboard.gameID == game_id).fetch(1)

    response.content_type = 'application/json'

    if GameEngine.inCheckMate(oldBoard[0].board, oldBoard[0].promotions, True):
        oldBoard[0].loser = 1
        oldBoard[0].put()
    elif GameEngine.inCheckMate(oldBoard[0].board, oldBoard[0].promotions, False):
        oldBoard[0].loser = 2
        oldBoard[0].put()

    pawnLocs = GameEngine.pawnAttacks(oldBoard[0].board, oldBoard[0].promotions, oldBoard[0].isWhite)
    checkLocs = GameEngine.inCheckLocs(oldBoard[0].board, oldBoard[0].promotions, oldBoard[0].isWhite)

    if len(oldBoard) > 0 and oldBoard[0].isWhite:
        return models.opponent_moved_to_json('0', oldBoard[0].board, oldBoard[0].loser, pawnLocs, checkLocs, oldBoard[0].isWhite)
    else:
        return models.opponent_moved_to_json('1', oldBoard[0].board, oldBoard[0].loser, pawnLocs, checkLocs, oldBoard[0].isWhite)
Exemple #24
0
    def test_gold_label(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)

        beh = b.GoldLabel()
        beh.start(self.session, self.object)

        assert beh.name == 'GoldLabel'
        assert beh.text == 'Gold: '

        beh.set_text('gaaaaaaaaameeeeeeeee')

        assert beh.text == 'gaaaaaaaaameeeeeeeee'
Exemple #25
0
    def test_enemy_attack(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)

        beh = b.EnemyAttack()

        assert beh.name == 'EnemyAttack'
        assert beh.attack_radius == 400
        beh.set_attack_radius(100)
        assert beh.attack_radius == 100
        assert beh.damage == 1
        beh.set_damage(5)
        assert beh.damage == 5
Exemple #26
0
    def test_health_system(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)

        beh = b.HealthSystem()
        beh.start(self.session, self.object)

        assert beh.health == 300

        beh.set_health(400)
        assert beh.health == 400

        beh.change_health(-200)
        assert beh.health == 200
Exemple #27
0
def start():
    win_offset_y = 25
    os.environ['SDL_VIDEO_WINDOW_POS'] = str(0) + "," + str(win_offset_y)
    pygame.init()
    info_obj = pygame.display.Info()
    #print(info_obj)
    screen_dim = Vec2d(int(info_obj.current_w),
                       int(info_obj.current_h - win_offset_y))

    em = EventManager.EventManager()
    game_engine = GameEngine.GameEngine(em, screen_dim)
    renderer = Renderer.Renderer(em, game_engine, screen_dim)
    controller = Controller.Controller(em, game_engine)

    game_engine.run()
Exemple #28
0
    def setUp(self):
        database.start_unittest_mode()

        self.game = NerfAssassin("Test Game", datetime.now())
        self.assertIsNotNone(self.game)
        database.add_game(self.game)

        for i in range(
                random.randint(self.MIN_NUM_PARTICIPANTS,
                               self.MAX_NUM_PARTICIPANTS)):
            user_id = GameEngine.new_user("Ass", "Assin" + str(i))
            self.assertGreaterEqual(user_id, 0)
            self.game.add_participant(user_id, "Assassin" + str(i))

        self.game.start_game()
Exemple #29
0
    def test_enemys_manager(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)

        beh = b.Manager()
        beh.start(self.session, self.object)

        assert beh.name == 'Manager'
        assert beh.count_of_enemys == 0
        assert beh.max_count_of_enemys == 0
        assert beh.enemy_id == 0

        beh.count_of_enemys_on_scene = 5
        beh.on_destroy_enemy()
        assert beh.count_of_enemys_on_scene == 4
Exemple #30
0
def game_start(args):
    engine = g.GameEngine(int(args.size))
    re = None
    num_games = int(args.number)
    num_humans = int(args.humans)
    board_size = int(args.size)
    gui = int(args.graphical)

    if gui:
        re = r.Renderer(engine)
        re.window_setup(500, 500)

    for i in range(num_games):
        winner, num_moves = play_game(engine, num_humans, re, FIRST_AI,
                                      SECOND_AI, board_size)
        print('Player', i, 'won in', num_moves, 'moves.')
Exemple #31
0
    def test_scene_manager(self):
        self.session = GameEngine.GameSession(o.FirstSceneLoader(), True)
        self.object = s.GameObject('GameObject', 0, 0, 0, 0)
        self.session._add_game_object(s.GameObject('GoldManager', 0, 0, 0, 0))

        beh = b.SceneManager()
        beh.start(self.session, self.object)
        beh.set_creating_object(self.object, 100)

        assert beh.name == 'SceneManager'
        assert beh.object == self.object
        assert not beh.tracking

        beh.start_tracking()

        assert beh.tracking
Exemple #32
0
def joue(evt):
    if enCourDeJeu == True:

        if canPlay == True:
            global score
            pos_y = int(evt.x / tailleCase)
            pos_x = int(evt.y / tailleCase)

            finJeu = True

            nombreCouleurADetruire = GameEngine.VerificationDestruction(
                pos_x, pos_y, plateau, True)
            global scorePasse
            scorePasse = nombreCouleurADetruire
            destructionSelection = GameEngine.PeutOnDetruire(
                nombreCouleurADetruire)
            if destructionSelection == True:
                #Si on est on mode multiplayer, les deux joueur ont le plateau bloqué
                if multiplayer == True:
                    ChangeCanPlay(False)
                    Reseaux.EnvoieMessage("[Bloque Plateau] : " + pseudo)
                tailleGrille = len(plateau)
                for i in range(tailleGrille):
                    GameEngine.ReplacementDesCubes(plateau)
                for i in range(tailleGrille):
                    GameEngine.ReplacementDesCubesHorizontal(plateau)
                score = GameEngine.CalculScore(score, nombreCouleurADetruire)
                #Changement dynamique du score --------------------------------------------------------
                scoreMessage = Label(root, text=score)
                scoreMessage.config(font=('courier', 15, 'bold'))
                scoreMessage.grid(row=0, column=1)
                finJeu = GameEngine.VerificationFinJeu(plateau)

            else:
                print("Impossible de détruire la sélection")
                print("i = " + str(pos_x))
                print("j = " + str(pos_y))

            #AffichePlateau(plateau)
            print("------")
            AfficheCouleur(plateau, tailleCase)

            if finJeu == True:
                finJeu = GameEngine.VerificationFinJeu(plateau)
                if finJeu == True:
                    FinDuJeu()
            if multiplayer == True:
                Reseaux.EnvoieMessage("[Partage Plateau] : " +
                                      Plateau2Str(plateau))
Exemple #33
0
    def __init__(self):
        pygame.init()
        pygame.font.init()
        self.myFont = pygame.font.SysFont('Comic Sans MS', 15)
        self.screen = pygame.display.set_mode((const.WIDTH, const.HEIGHT))
        self.screenBoard = pygame.Surface(
            (const.WIDTH_BOARD, const.HEIGHT_BOARD))
        self.screenScore = pygame.Surface(
            (const.WIDTH_SCORE, const.HEIGHT_SCORE))

        self.screen = pygame.display.set_mode((const.WIDTH, const.HEIGHT))
        self.screen.fill(pygame.Color(const.BOARD_COLOR_WHITE))
        self.clock = pygame.time.Clock()
        self.gameState = GameEngine.GameState(pygame, self.screen,
                                              self.screenBoard,
                                              self.screenScore)
        self.squareSize = const.HEIGHT_BOARD // len(self.gameState.board)
        self.running = True
        self.squareSelected = []
        self.movementsPossibles = []
Exemple #34
0
    def __init__(self, fileName,engine,speed = 1):
      Task.__init__(self)
      if not engine:
        engine = GameEngine.getEngine()
      self.engine       = engine
      self.fileName     = fileName
      self.channel      = None
      self.playing      = False
      self.bufferSize   = 1024 * 64
      self.bufferCount  = 8
      self.volume       = 1.0
      self.event = None
      self.speed = speed

        #myfingershurt: buffer is 2D array (one D for each channel) of 16-bit UNSIGNED integers / samples
        #  2*1024*64 = 131072 samples per channel
      self.buffer       = np.zeros((2 * self.bufferSize, 2),dtype=np.int16)

      self.decodingRate = 4
      self._reset()
Exemple #35
0
async def SendUserStats(Context, CmdName):
    UserInfo = GameEngine.GetAllUserInfo(Context)  #TODO::Use ImageLib here
    print(UserInfo)
    user = Context.author
    embed = discord.Embed(colour=discord.Colour(0xE5E242),
                          title=f"{user.name}'s Stats and Information.")
    embed.set_thumbnail(url=user.avatar_url_as(format="png"))
    embed.add_field(
        name="__**General information:**__",
        value=f"**Discord Name:** {user}\n"
        f"**Account created:** {user.created_at.__format__('%A %d %B %Y at %H:%M')}\n"
    )
    embed.add_field(
        name="__**Server-related information:**__",
        value=f"**Nickname:** {user.nick}\n"
        f"**Joined server:** {user.joined_at.__format__('%A %d %B %Y at %H:%M')}\n"
        f"**Roles:** {' '.join([r.mention for r in user.roles[1:]])}\n"
        f"**Level:** {UserInfo['Level']}\n"
        f"**XP:** {UserInfo['XP']}\n"
        f"**XP Next Level:** {UserInfo['NextLevelXP']}\n")

    await Context.send(embed=embed)
Exemple #36
0
import os, sys
import getopt
from GameEngine import *

def usage():
    """Imprime informacoes de uso"""
    print "Uso: cicfighter.py"
    print
    print "Opcoes:"
    print "  -f | --fullscreen       : Modo em tela cheia"
    print "  -h | --help             : Esta tela"

if __name__ == "__main__":
    try:
        opts, args = getopt.getopt(sys.argv[1:], "fh", ["fullscreen","help"])
    except getopt.GetoptError:
        usage()
        sys.exit(1)
        
    fullscreen = False
    for opt, arg in opts:
        if opt in ('-f', '--fullscreen'):
            fullscreen = True
        if opt in ('-h', '--help'):
            usage()
            sys.exit(1)            

    Engine = GameEngine(fullscreen)
    Engine.run()
    
def LocationToRegion(angle, magnitude):
    try:
        if calibration.calibrationComplete:
            #print "Finding dart throw information"

            dartInfo = GameEngine.dartThrow()

            angleDiffMul = int((angle - calibration.ref_angle) / 18.0)

            #starting from the 20 points
            if angleDiffMul == 0:
                dartInfo.base = 20
            elif angleDiffMul == 1:
                dartInfo.base = 5
            elif angleDiffMul == 2:
                dartInfo.base = 12
            elif angleDiffMul == 3:
                dartInfo.base = 9
            elif angleDiffMul == 4:
                dartInfo.base = 14
            elif angleDiffMul == 5:
                dartInfo.base = 11
            elif angleDiffMul == 6:
                dartInfo.base = 8
            elif angleDiffMul == 7:
                dartInfo.base = 16
            elif angleDiffMul == 8:
                dartInfo.base = 7
            elif angleDiffMul == 9:
                dartInfo.base = 19
            elif angleDiffMul == 10:
                dartInfo.base = 3
            elif angleDiffMul == 11:
                dartInfo.base = 17
            elif angleDiffMul == 12:
                dartInfo.base = 2
            elif angleDiffMul == 13:
                dartInfo.base = 15
            elif angleDiffMul == 14:
                dartInfo.base = 10
            elif angleDiffMul == 15:
                dartInfo.base = 6
            elif angleDiffMul == 16:
                dartInfo.base = 13
            elif angleDiffMul == 17:
                dartInfo.base = 4
            elif angleDiffMul == 18:
                dartInfo.base = 18
            elif angleDiffMul == 19:
                dartInfo.base = 1
            else:
                #something went wrong
                dartInfo.base = -300

            #Calculating multiplier (and special cases for Bull's Eye):
            for i in range(0, len(calibration.ring_radius)):
                #print calibration.ring_radius[i]
                #Find the ring that encloses the dart
                if magnitude <= calibration.ring_radius[i]:
                    #Bull's eye, adjust base score
                    if i == 0:
                        dartInfo.base = 25
                        dartInfo.multiplier = 2
                    elif i == 1:
                        dartInfo.base = 25
                        dartInfo.multiplier = 1
                    #triple ring
                    elif i == 3:
                        dartInfo.multiplier = 3
                    #double ring
                    elif i == 5:
                        dartInfo.multiplier = 2
                    #single
                    elif i == 2 or i == 4:
                        dartInfo.multiplier = 1
                    #finished calculation
                    break

            #miss
            if magnitude > calibration.ring_radius[5]:
                dartInfo.base = 0
                dartInfo.multiplier = 0

            return (dartInfo.base, dartInfo.multiplier)
        

    #system not calibrated
    except AttributeError as err1:
        print err1
        return (-1, -1)

    except NameError as err2:
        print err2
        return (-2, -2)
def DartRegion(dart_loc):
    try:
        if calibration.calibrationComplete:
            print "Finding dart throw information"
            dartInfo = GameEngine.dartThrow()

            #find the magnitude and angle of the dart
            tempX_mat = cv.CreateMat(1, 1, cv.CV_32FC1)
            cv.mSet( tempX_mat, 0, 0, dart_loc[0] - calibration.center_dartboard[0] )
            tempY_mat = cv.CreateMat(1, 1, cv.CV_32FC1)
            #adjust the origin of y to fit a Cartesian plane
            cv.mSet( tempY_mat, 0, 0, dart_loc[1] - (calibration.image.height - calibration.center_dartboard[1]) )
            dart_mag_mat = cv.CreateMat(1, 1, cv.CV_32FC1)
            dart_angle_reversed_mat = cv.CreateMat(1, 1, cv.CV_32FC1)

            #each point region is 360/12 = 18 degrees large
            cv.CartToPolar(tempX_mat, tempY_mat, dart_mag_mat, dart_angle_reversed_mat, angleInDegrees=True)

            dart_angle_val = 360.0 - cv.mGet(dart_angle_reversed_mat, 0, 0)

            dartInfo.magnitude = cv.mGet(dart_mag_mat, 0, 0)
            dartInfo.angle = dart_angle_val

            #Calculating score:
            #Find base point
            if dart_angle_val < calibration.ref_angle:         #make sure dart's angle is always greater
                dart_angle_val += 360.0
                
            angleDiffMul = int((dart_angle_val - calibration.ref_angle) / 18.0)

            #starting from the 20 points
            if angleDiffMul == 0:
                dartInfo.base = 20
            elif angleDiffMul == 1:
                dartInfo.base = 5
            elif angleDiffMul == 2:
                dartInfo.base = 12
            elif angleDiffMul == 3:
                dartInfo.base = 9
            elif angleDiffMul == 4:
                dartInfo.base = 14
            elif angleDiffMul == 5:
                dartInfo.base = 11
            elif angleDiffMul == 6:
                dartInfo.base = 8
            elif angleDiffMul == 7:
                dartInfo.base = 16
            elif angleDiffMul == 8:
                dartInfo.base = 7
            elif angleDiffMul == 9:
                dartInfo.base = 19
            elif angleDiffMul == 10:
                dartInfo.base = 3
            elif angleDiffMul == 11:
                dartInfo.base = 17
            elif angleDiffMul == 12:
                dartInfo.base = 2
            elif angleDiffMul == 13:
                dartInfo.base = 15
            elif angleDiffMul == 14:
                dartInfo.base = 10
            elif angleDiffMul == 15:
                dartInfo.base = 6
            elif angleDiffMul == 16:
                dartInfo.base = 13
            elif angleDiffMul == 17:
                dartInfo.base = 4
            elif angleDiffMul == 18:
                dartInfo.base = 18
            elif angleDiffMul == 19:
                dartInfo.base = 1
            else:
                #something went wrong
                dartInfo.base = -300

            #Calculating multiplier (and special cases for Bull's Eye):
            for i in range(0, len(calibration.ring_radius)):
                print calibration.ring_radius[i]
                #Find the ring that encloses the dart
                if dartInfo.magnitude <= calibration.ring_radius[i]:
                    #Bull's eye, adjust base score
                    if i == 0:
                        dartInfo.base = 25
                        dartInfo.multiplier = 2
                    elif i == 1:
                        dartInfo.base = 25
                        dartInfo.multiplier = 1
                    #triple ring
                    elif i == 3:
                        dartInfo.multiplier = 3
                    #double ring
                    elif i == 5:
                        dartInfo.multiplier = 2
                    #single
                    elif i == 2 or i == 4:
                        dartInfo.multiplier = 1
                    #finished calculation
                    break

            #miss
            if dartInfo.magnitude > calibration.ring_radius[5]:
                dartInfo.base = 0
                dartInfo.multiplier = 0

            return dartInfo


    #system not calibrated
    except AttributeError as err1:
        print err1
        dartInfo = GameEngine.dartThrow()
        return dartInfo

    except NameError as err2:
        #not calibrated error
        print err2
        dartInfo = GameEngine.dartThrow()
        return dartInfo
Exemple #39
0
Level Read
Level Editor
Finish Cat Art
'''

import pygame, sys, os
from pygame.locals import *
from GameEngine import *
from CatPlayer import *
from SceneSprite import *
from EnemySprite import *
from ItemSprite import *



bubbleCats = GameEngine((800,600), "BubbleCats", 40)

screenHeight = bubbleCats.screenRect.height
for i in range(220):
    sprite = SceneSprite("CarpetTile.bmp", (0, 0), None)
    sprite.move(i*sprite.rect.width-150, screenHeight-sprite.rect.height)
    bubbleCats.addPlatform(sprite)
    sprite = SceneSprite("RunningBoardTile.bmp", (0,0), None)
    sprite.move(i*sprite.rect.width-150, screenHeight-94)
    bubbleCats.addBackground(sprite)
    
for i in range(15):
    bubbleCats.addBackground(SceneSprite("OutletTile.bmp", (i*1000, screenHeight-170)))

bubbleCats.addBackground(SceneSprite("CouchTop.bmp", (14000, 281), pygame.Color(131,131,131)))
bubbleCats.addBackground(SceneSprite("BethGoalTop.bmp", (14220, 195), pygame.Color(131,131,131)))
Exemple #40
0
#!/usr/bin/env python3


# engine/test.py
# A generic testing script for the engine.  Modify as much as you want... it's just for testing.

import sys

from DrawableObject import *
from GameEngine import *

print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nTESTING SCRIPT BEGIN\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")



try:
    testObj = DrawableObject()
    testObj.characterMapForDrawingContext(0, 100, 100)
except Exception as ex:
    print("Caught exception: " + str(ex))



# now try a fake GameEngine - this will crash
engine = GameEngine()
engine.start()