示例#1
0
    def prepareGame(self):
        if self.camera:
            # Disable Mouse Control for camera
            self.disableMouse()

            self.camera.setPos(0, 0, 500)
            self.camera.lookAt(0, 0, 0)

        self.gameData = GameData(True)

        # game data
        self.broadcastData(('gamedata', self.gameData.packageData()))
        self.broadcastData(('state', 'preround'))
        print "Preparing Game"
        self.gameTime = 0
        self.tick = 0

        usersData = []
        for user in self.currentPlayers:
            user.gameData = UserData()
            usersData.append(user.gameData)
        print usersData
        self.game = Game(self, usersData, self.gameData)
        self.taskMgr.doMethodLater(0.5, self.roundReadyLoop, 'Game Loop')
        print "Round ready State"
示例#2
0
 def on_players(self, instance, value):
     GameData.set_players(value)
     count_players = 0
     for player in self.players:
         count_players = count_players + (1 if player else 0)
     self.allPlayersSet = (count_players == 4)
     self.ids.topbar.isNextEnabled = self.allPlayersSet
示例#3
0
 def __handle_goal(self, data):
     # 0 : home, 1: away
     if data in ["0", "1"]:
         team_id = int(data)
         GameData.add_goal(team_id)
         # play goal sound
         SoundManager.play(Trigger.GOAL)
         # update local match data
         self.update_match()
         # highlight score board
         HighlightOverlay(orig_obj=self.score_objects[team_id], parent=self).animate(font_size=500, color=(1, 1, 1, 0), d=2.0)
示例#4
0
    def __handle_goal(self, team):
        if team == '1':
            GameData.add_goal(0)
            obj = self.ids.labelHome
        else:
            GameData.add_goal(1)
            obj = self.ids.labelAway

        self.score = GameData.get_score()
        HighlightOverlay(orig_obj=obj, parent=self).animate(font_size=500, color=(1, 1, 1, 0), d=2.0)
        SoundManager.play(Trigger.GOAL)
示例#5
0
 def testSaveData(self):
     g = GameData('PlanetWars')
     g_id = g.get_next_game_id()
     result = {}
     if random.randint(0,1) == 0:
         result = {1: 1, 2: 2}
     else:
         result = {2: 1, 1: 2}
     player1 = random.randint(1,8)
     player2 = random.randint(1,8)
     g.save_game(g_id, result, 'bla', {player1: self.names[player1],
                                       player2: self.names[player2]})
示例#6
0
 def testSaveData(self):
     g = GameData('PlanetWars')
     g_id = g.get_next_game_id()
     result = {}
     if random.randint(0, 1) == 0:
         result = {1: 1, 2: 2}
     else:
         result = {2: 1, 1: 2}
     player1 = random.randint(1, 8)
     player2 = random.randint(1, 8)
     g.save_game(g_id, result, 'bla', {
         player1: self.names[player1],
         player2: self.names[player2]
     })
示例#7
0
文件: game.py 项目: bull313/pokerAI
 def __init__(self):
     """
     Properties
     """
     self._blinds_maxed_out = False  ### Are the blinds at the highest value?
     self._board_name_idx = 0  ### List address for the name of the board
     self._game_data = GameData()  ### Poker Data Interface Object
     self._game_play_code = GameCode.NEW_GAME  ### What kind of game are we playing or playing back (new/load)?
     self._game_save = None  ### Object that manages saving a game finished or in progress
     self._game_theater = None  ### Plays back a finished game
     self._hand_actions = list(
     )  ### List of actions that were made in a hand
     self._ui = GameUI()  ### User Interface Object
     self._num_remaining_players = 0  ### Number of remaining players in the game
示例#8
0
 def update_match(self):
     # fetch score from GameData
     self.score = GameData.get_score()
     # update kickoff information
     self.handle_kickoff(False)
     # check max goal during match
     if self.state == 'running':
         if GameData.is_match_finished():
             self.state = 'finished'
             self.stop_time = self.get_time()
             SoundManager.play(Trigger.GAME_END)
     # manual swiping can resume a finished match
     elif self.state == 'finished' and not GameData.is_match_finished():
         self.state = 'running'
         SoundManager.play(Trigger.GAME_RESUME)
示例#9
0
 def __reset(self):
     self.state = ''
     GameData.reset_match()
     self.update_match()
     self.set_custom_text('')
     self.timer_mode_elapsed_time = True
     self.ids.btnSubmit.blocking = False
     container = self.ids.kickoff_ball.parent
     self.ids.kickoff_ball.pos = (container.x + container.width / 2.0, container.y + container.height)
     self.score_touch = None
     self.players = [{}] * 4
     self.kickoff_team = -1
     self.elo = 0.0
     Clock.unschedule(self.__update_timer_view)
     Clock.unschedule(self.__animate_kickoff)
示例#10
0
 def __reset(self):
     self.state = ''
     GameData.reset_match()
     self.score = GameData.get_score()
     self.set_custom_text('00:00')
     self.ids.topbar.customlabel.opacity = 1
     self.ids.btnSubmit.blocking = False
     container = self.ids.kickoff_ball.parent
     self.ids.kickoff_ball.pos = (container.x + container.width / 2.0, container.y + container.height)
     self.score_touch = None
     self.players = [{}] * 4
     self.kickoff_team = -1
     self.elo = 0.0
     Clock.unschedule(self.__update_match_timer)
     Clock.unschedule(self.__animate_kickoff)
示例#11
0
 def on_enter(self):
     self.__reset()
     self.state = 'running'
     self.start_time = time.time()
     self.players = GameData.get_players()
     self.__set_submit_icon(icons.cloud_upload)
     Clock.schedule_interval(self.__update_match_timer, 1.0)
     self.handle_kickoff(True)
示例#12
0
 def on_enter(self):
     # reset and start match
     self.__reset()
     self.state = 'running'
     self.start_time = self.get_time()
     self.players = GameData.get_players()
     self.__set_submit_icon(icons.cloud_upload)
     self.restart_timer()
     self.handle_kickoff(True)
示例#13
0
    def __submit_score_thread(self):
        # submit score to remote server
        (error, elo) = ServerCom.submit_score(self.players, GameData.get_score())
        if error is None:
            self.submit_success = True
            self.elo = elo
            Logger.info('{}'.format(self.elo))

        else:
            self.submit_success = False
            self.elo = 0.0
示例#14
0
 def on_score(self, instance, value):
     # update kickoff information
     self.handle_kickoff(False)
     # check max goal during match
     if self.state == 'running':
         if GameData.is_match_finished():
             self.state = 'finished'
             SoundManager.play(Trigger.GAME_END)
     # manual swiping can resume a finished match
     elif self.state == 'finished':
         self.state = 'running'
         SoundManager.play(Trigger.GAME_RESUME)
示例#15
0
def save_game(exit=False):
    gamedata = GameData(
        **{
            "player": player,
            "dungeon_room": dungeon.cur_room,
            "bonus_tasks": bonus_tasks,
            "savefile": savefile
        })
    json_serialization.save_file(gamedata, savefile)
    print("Game saved to " + savefile)
    if not exit:
        village.show()
示例#16
0
    def preprocess_command(self, sound_type):
        ''' special handling for goal sounds'''
        # skip unless goal
        if sound_type != 'goal':
            return sound_type

        # check tie
        new_type = 'goal-tie'
        if GameData.is_tie() and self.has_files_for(new_type) and random.random() < 0.3:
            return new_type
        # check almost tie
        new_type = 'goal-almost-tie'
        if GameData.is_almost_tie() and self.has_files_for(new_type) and random.random() < 0.3:
            return new_type
        # check absolute score
        score = GameData.get_score()
        new_type = 'goal-{}-{}'.format(score[0], score[1])
        if self.has_files_for(new_type) and random.random() < 0.3:
            return new_type
        # default
        return 'goal'
示例#17
0
 def handle_score_touch_up(self, event):
     if self.state not in ['running', 'finished']:
         return
     if self.score_touch:
         score_id = self.score_touch['id']
         dist = event.pos[1] - self.score_touch['startPos']
         if abs(dist) > self.MIN_SCORE_MOVE_PX:
             goal_up = dist > 0
             if goal_up:
                 swipe_allowed = GameData.add_goal(score_id)
             else:
                 swipe_allowed = GameData.revoke_goal(score_id)
             if swipe_allowed:
                 self.score = GameData.get_score()
                 HighlightOverlay(orig_obj=self.score_objects[score_id], parent=self).animate(font_size=500, color=(1, 1, 1, 0))
                 if goal_up:
                     SoundManager.play(Trigger.GOAL)
                 else:
                     SoundManager.play(Trigger.OFFSIDE)
             else:
                 # TODO: "Rote Karte"
                 pass
         self.score_objects[score_id].color = (1, 1, 1, 1)
     self.score_touch = None
示例#18
0
 def __submit_score_thread(self):
     # submit score to remote server
     (error, elo) = ServerCom.submit_score(self.players, GameData.get_score())
     if error is None:
         self.submit_success = True
         self.__set_elo(elo)
         # fetch ranking
         ranking_attacker = ServerCom.fetch_ranking('attacker')
         if ranking_attacker:
             PlayerData.set_ranking('attacker', ranking_attacker)
         ranking_defender = ServerCom.fetch_ranking('defender')
         if ranking_defender:
             PlayerData.set_ranking('defender', ranking_defender)
     else:
         self.submit_success = False
示例#19
0
    def handle_score_touch_up(self, event):
        if self.state not in ['running', 'finished']:
            return
        if self.score_touch:
            score_id = self.score_touch['id']
            dist = event.pos[1] - self.score_touch['startPos']
            if abs(dist) > settings.SCORE_SWIPE_DISTANCE:
                goal_up = dist > 0
                if goal_up:
                    swipe_allowed = GameData.add_goal(score_id)
                else:
                    swipe_allowed = GameData.revoke_goal(score_id)
                if swipe_allowed:
                    self.update_match()
                    HighlightOverlay(orig_obj=self.score_objects[score_id], parent=self).animate(font_size=500, color=(1, 1, 1, 0))
                    if goal_up:
                        SoundManager.play(Trigger.GOAL)
                    else:
                        SoundManager.play(Trigger.OFFSIDE)
                else:
                    self.denied()

            self.score_objects[score_id].color = (1, 1, 1, 1)
        self.score_touch = None
示例#20
0
    def __animate_kickoff(self, dt):
        # animate ball
        obj = self.ids['kickoff_ball']
        x_current = obj.pos[0]
        x_target = obj.parent.x + (0.0 if GameData.get_kickoff_team() == 0 else obj.parent.width)
        y_high = obj.parent.y + 1.5 * obj.parent.height
        y_low = obj.parent.y + obj.parent.height / 2.0

        uptime_ratio = 0.3
        duration = 1.5
        duration_up = uptime_ratio * duration
        duration_down = (1.0 - uptime_ratio) * duration
        anim = Animation(x=x_current + uptime_ratio * (x_target - x_current), d=duration_up, t='linear') & Animation(y=y_high, d=duration_up, t='out_quad')
        anim += Animation(x=x_target, d=duration_down, t='out_quad') & Animation(y=y_low, d=duration_down, t='out_bounce')
        anim.start(obj)
        Clock.schedule_once(self.__animate_rotation, 0)
        Clock.schedule_once(lambda dt: Clock.unschedule(self.__animate_rotation), duration)
示例#21
0
 def updateLobby(self, task):
     temp = self.showbase.client.getData()
     for package in temp:
         if len(package) == 2:
             print 'Received: ', str(package)
             if package[0] == 'reset':
                 self.showbase.users = []
                 print 'cleared users'
             elif package[0] == 'client':
                 self.showbase.users.append(User(package[1]))
                 for user in self.showbase.users:
                     print user.name, user.ready
                 print 'all users'
             elif package[0] == 'ready':
                 for user in self.showbase.users:
                     if user.name == package[1][0]:
                         user.ready = package[1][1]
                 for user in self.showbase.users:
                     print user.name, user.ready
                 print 'all users'
             elif package[0] == 'disconnect':
                 for user in self.showbase.users:
                     if user.name == package[1]:
                         self.showbase.users.remove(user)
                 for user in self.showbase.users:
                     print user.name, user.ready
                 print 'all users'
             elif package[0] == 'gamedata':
                 self.showbase.gameData = GameData()
                 self.showbase.gameData.unpackageData(package[1])
             elif package[0] == 'state':
                 print 'state: ', package[1]
                 if package[1] == 'preround':
                     self.showbase.startRound()
                     return task.done
     return task.again
示例#22
0
        threading.Thread.__init__(self)
        self.game_data = game_data
        self.game_data_lock = game_data_lock

    def run(self):
        tcpserver.main(self.game_data, self.game_data_lock)


class WebThread(threading.Thread):
    def __init__(self, game_data, game_data_lock):
        threading.Thread.__init__(self)
        self.game_data = game_data
        self.game_data_lock = game_data_lock

    def run(self):
        webserver.main(self.game_data, self.game_data_lock)


if __name__ == '__main__':
    from gamedata import GameData
    game_data = GameData('PlanetWars')
    game_data_lock = threading.Lock()

    try:
        tcpthread = TCPThread(game_data, game_data_lock)
        tcpthread.start()
        webthread = WebThread(game_data, game_data_lock)
        webthread.start()
    except KeyboardInterrupt:
        pass
示例#23
0
#!/usr/bin/python3

# Created on 5/11/2021

from sys import exit
import webbrowser
from time import sleep
from random import randint
from other.colors import print_green, print_yellow, print_red, print_s, print_health
from classes import Player, Difficulty
from gamedata import GameData
from other.sounds_effects import GameSounds

player1 = Player()  # Player Instance
game_data = GameData()  # load/save functions Instance
sounds = GameSounds()  # audio that will be played Instance

# constants:
EXIT_MERCHANT_MENU = str(len(player1.weapon_dict))


def load_or_save_data():
    game_data.load_game(player1)


def game_intro_description():
    sounds.intro_sound()
    print_s('''This is a zombie survival game where you must make the best decisions possible in order to live.
As a survivor, you will encounter zombies, weapons, people, and a merchant to buy from with an
in-game currency. Every decision you make has a cause and effect while some lead you to fortune and others will 
lead you to death.\n''', 2.5)
示例#24
0
 def handle_kickoff(self, say_player):
     if not GameData.is_match_finished():
         delay = 1.0
         Clock.schedule_once(self.__animate_kickoff, delay)
         if say_player:
             SoundManager.play(Trigger.GAME_START, self.players[GameData.get_kickoff_team() * 2])
示例#25
0
class GameServer(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        self.server = Server(9099, compress=True)
        self.server.handleNewConnection = self.handleNewConnection
        self.server.handleLostConnection = self.handleLostConnection

        self.tempConnections = []
        self.currentPlayers = []

        self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop')

    def broadcastData(self, data):
        # Broadcast data out to all users
        for user in self.currentPlayers:
            if user.connection:
                self.server.sendData(data, user.connection)

    def getUsers(self):
        # return a list of all users
        return self.currentPlayers

    def getData(self):
        data = []
        for datagram in self.server.getData():
            connection = datagram[0]
            package = datagram[1]
            if package is None:
                continue
            if connection in self.tempConnections:
                self.processTempConnection(datagram)
                continue
            for authed in self.currentPlayers:
                if connection == authed.connection:
                    data.append((package, connection))
        return data

    def handleNewConnection(self, connection):
        print "handleNewConnection"
        self.tempConnections.append(connection)

    def handleLostConnection(self, connection):
        print "handleLostConnection"
        # remove from our activeConnections list
        if connection in self.tempConnections:
            self.tempConnections.remove(connection)
        for user in self.currentPlayers:
            if connection == user.connection:
                user.connection = None
                self.server.passData(('disconnect', user.name), None)

    def processTempConnection(self, datagram):
        connection = datagram[0]
        package = datagram[1]
        if len(package) == 2:
            if package[0] == 'username':
                print 'attempting to authenticate', package[1]
                self.tempConnections.remove(connection)

                user = User(package[1], connection)
                # confirm authorization
                self.server.sendData(('auth', user.name), user.connection)
                self.updateClient(user)
                self.currentPlayers.append(user)

    def updateClient(self, user):
        for existing in self.currentPlayers:
            if existing.name != user.name:
                self.server.sendData(('client', existing.name),
                                     user.connection)
                self.server.sendData(
                    ('ready', (existing.name, existing.ready)),
                    user.connection)
                if existing.connection:
                    self.server.sendData(('client', user.name),
                                         existing.connection)
        self.server.sendData(('client', user.name), user.connection)

    def returnToLobby(self):
        self.taskMgr.doMethodLater(0.5, self.cleanupAndStartLobby,
                                   'Return To Lobby')

    def cleanupAndStartLobby(self, task):
        self.cleanupGame()

        for currentPlayer in self.currentPlayers:
            self.server.sendData(('reset', 'bloop'), currentPlayer.connection)
            for existing in self.currentPlayers:
                self.server.sendData(('client', existing.name),
                                     currentPlayer.connection)
                self.server.sendData(
                    ('ready', (existing.name, existing.ready)),
                    currentPlayer.connection)

        self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop')

        return task.done

    def lobbyLoop(self, task):
        temp = self.getData()
        for package in temp:
            if len(package) == 2:
                packet = package[0]
                connection = package[1]

                print "Received: ", str(package)
                if len(packet) == 2:
                    # check to make sure connection has username
                    for user in self.currentPlayers:
                        if user.connection == connection:
                            # if chat packet
                            if packet[0] == 'chat':
                                print 'Chat: ', packet[1]
                                # Broadcast data to all clients ("username: message")
                                self.broadcastData(
                                    ('chat', (user.name, packet[1])))
                            # else if ready packet
                            elif packet[0] == 'ready':
                                print user.name, ' changed readyness!'
                                user.ready = packet[1]
                                self.broadcastData(
                                    ('ready', (user.name, user.ready)))
                            # else if disconnect packet
                            elif packet[0] == 'disconnect':
                                print user.name, ' is disconnecting!'
                                self.currentPlayers.remove(user)
                                self.broadcastData(('disconnect', user.name))
                            # break out of for loop
                            break
        # if all players are ready and there is X of them
        gameReady = True
        # if there is any clients connected
        if not self.getUsers():
            gameReady = False
        for user in self.currentPlayers:
            if not user.ready:
                gameReady = False
        if gameReady:
            self.prepareGame()
            return task.done
        return task.again

    def prepareGame(self):
        if self.camera:
            # Disable Mouse Control for camera
            self.disableMouse()

            self.camera.setPos(0, 0, 500)
            self.camera.lookAt(0, 0, 0)

        self.gameData = GameData(True)

        # game data
        self.broadcastData(('gamedata', self.gameData.packageData()))
        self.broadcastData(('state', 'preround'))
        print "Preparing Game"
        self.gameTime = 0
        self.tick = 0

        usersData = []
        for user in self.currentPlayers:
            user.gameData = UserData()
            usersData.append(user.gameData)
        print usersData
        self.game = Game(self, usersData, self.gameData)
        self.taskMgr.doMethodLater(0.5, self.roundReadyLoop, 'Game Loop')
        print "Round ready State"

    def cleanupGame(self):
        self.game.destroy()
        self.game = None

    def roundReadyLoop(self, task):
        temp = self.getData()
        for package in temp:
            if len(package) == 2:
                print "Received: ", str(package)
                if len(package[0]) == 2:
                    for user in self.currentPlayers:
                        if user.connection == package[1]:
                            if package[0][0] == 'round':
                                if package[0][1] == 'sync':
                                    user.sync = True
        # if all players are ready and there is X of them
        roundReady = True
        # if there is any clients connected
        for user in self.currentPlayers:
            if not user.sync:
                roundReady = False
        if roundReady:
            self.taskMgr.doMethodLater(2.5, self.gameLoop, 'Game Loop')
            print "Game State"
            return task.done
        return task.again

    def gameLoop(self, task):
        # process incoming packages
        temp = self.getData()
        for package in temp:
            if len(package) == 2:
                # check to make sure connection has username
                for user in self.currentPlayers:
                    if user.connection == package[1]:
                        try:
                            user.gameData.processUpdatePacket(package[0])
                        except AttributeError:
                            print "Player must have joined mid game! :O"

        # get frame delta time
        dt = self.taskMgr.globalClock.getDt()
        self.gameTime += dt
        # if time is less than 3 secs (countdown for determining pings of clients?)
        # tick out for clients
        while self.gameTime > gameTick:
            # update all clients with new info before saying tick
            for user in self.currentPlayers:
                try:
                    updates = user.gameData.makeUpdatePackets()
                    for packet in updates:
                        self.broadcastData((user.name, packet))
                except AttributeError:
                    print "Player must have joined mid game! :O"
            self.broadcastData(('tick', self.tick))
            self.gameTime -= gameTick
            self.tick += 1
            # run simulation
            if not self.game.runTick(gameTick, self.tick):
                print 'Game Over'
                self.broadcastData(("game", "over"))
                # send to all players that game is over (they know already but whatever)
                # and send final game data/scores/etc
                for user in self.currentPlayers:
                    user.ready = False
                self.returnToLobby()
                return task.done
        return task.cont
示例#26
0
 def __animate_rotation(self, dt):
     direction = 1.0 if GameData.get_kickoff_team() == 0 else -1.0
     self.kickoff_angle += 15.0 * direction
     Clock.schedule_once(self.__animate_rotation, 0.04)
示例#27
0
def main():
    game_data = GameData()

    try:
        game_data.initialize(settings.ck2_install_dir, settings.mod_dir)
    except InstallDirNotFoundError:
        print('Did not find CK2 install dir:', settings.ck2_install_dir)
        print('Please modify settings.py to use the correct path.')
        sys.stdin.readline()
        sys.exit()
    except Exception:
        if settings.debug:
            raise
        else:
            print('Error initializing game data.')
            print('Check that the locations in settings.py are correct.')
            print(
                'Otherwise please post to the Paradox Interactive Forums thread,',
            )
            print('noting any mods you are using.')
            sys.stdin.readline()
            sys.exit()

    filename = settings.save_file
    if filename == '':
        print('\nPlease enter the name of your save file, without the .ck2: ')

        filename = sys.stdin.readline().strip()

    print('\n')

    if filename[-4:] != '.ck2':
        filename += '.ck2'
    if not os.path.exists(filename):
        print('Could not find save file: ', filename + '.ck2')
        sys.stdin.readline()
        sys.exit()

    try:
        game_data.read_save(filename + '.ck2', settings.generate_titles)
    except Exception:
        if settings.debug:
            raise
        else:
            print('Error reading save file.')
            print('Please ensure that your save is UNENCRYPTED.')
            print('If that is not the problem, please post to the Paradox')
            print(
                'Interactive Forums thread, upload your save and note any mods'
            )
            print('you are using.')
            sys.stdin.readline()
            sys.exit()

    if not game_data.mark_characters(settings.real_fathers):
        sys.stdin.readline()
        sys.exit()

    gedcom_writer = GedcomWriter()

    try:
        gedcom_writer.initialize(game_data)
    except Exception:
        if settings.debug:
            raise
        else:
            print('Error generating GEDCOM family information.')
            print(
                'Please post to the Paradox Interactive Forums thread, upload')
            print('your save and note any mods you are using.')
            sys.stdin.readline()
            sys.exit()

    try:
        gedcom_writer.write_gedcom(filename + '.ged')
    except Exception:
        if settings.debug:
            raise
        else:
            print('Error writing GEDCOM file.')
            print(
                'Please post to the Paradox Interactive Forums thread, upload')
            print('your save and note any mods you are using.')
            sys.stdin.readline()
            sys.exit()
示例#28
0
文件: game.py 项目: bull313/pokerAI
class Game:
    """
    Constants
    """
    DEFAULT_BLIND_RAISING_SCHEME = lambda old_blinds, initial_blinds: old_blinds + initial_blinds  ### Default mechanism to increase blinds: add the initial blind to the new blind
    MIN_STARTING_CHIP_COUNT = 4  ### Absolute amount of starting chips per player
    NUM_CARDS_FOR_BOARD_TYPE = [3, 1,
                                1]  ### Number of cards to turn on each street
    NUM_HOLE_CARDS = 2  ### Number of hole cards per player
    NUM_PLAYERS_MIN = 2  ### Minimum number of players to start the game
    NUM_PLAYERS_MAX = 12  ### Maximum number of players to start the game
    REQUIRED_RAISE_MULTIPLE = 2  ### Required raise is this value times the current bet
    SHOW_FOLDED_HANDS = True  ### Show the remaining player's hand if folded to that player?
    """
    Constructor
    """
    def __init__(self):
        """
        Properties
        """
        self._blinds_maxed_out = False  ### Are the blinds at the highest value?
        self._board_name_idx = 0  ### List address for the name of the board
        self._game_data = GameData()  ### Poker Data Interface Object
        self._game_play_code = GameCode.NEW_GAME  ### What kind of game are we playing or playing back (new/load)?
        self._game_save = None  ### Object that manages saving a game finished or in progress
        self._game_theater = None  ### Plays back a finished game
        self._hand_actions = list(
        )  ### List of actions that were made in a hand
        self._ui = GameUI()  ### User Interface Object
        self._num_remaining_players = 0  ### Number of remaining players in the game

    """
    Public methods
    """

    def setup(self):
        """
        Set up the game structure with user-entered or loaded values
        
        Get the name of a game save and assume it is a new game
        """
        game_save_name = self._ui.get_game_save_name()
        self._game_save = GameSave(game_save_name)
        self._game_play_code = GameCode.NEW_GAME
        """
        If the save name exists, set up a saved (loaded) game
        """
        if self._game_save.save_exists():
            self._setup_saved_game()
        else:
            self._setup_new_game()
        """
        Set up the game's hot key commands
        """
        self._ui.setup_save_command(self._handle_save_game)

    def play_game(self):
        """
        Play or play back a game
        """
        if self._game_play_code == GameCode.PLAYBACK_GAME and self._game_theater is not None:
            """
            Play back a game
            """
            self._game_theater.playback_game()

        elif self._game_play_code != GameCode.NO_PLAY:
            """
            Play a game (new or loaded)
            """
            self._start_new_or_loaded_game()

    """
    Callback Methods
    """

    def _handle_save_game(self):
        """
        Serialize game save data and display a confirmation message to the user
        """
        save_successful = self._game_save.save()
        save_name = self._game_save.get_game_save_name()
        self._ui.display_game_save_confirm(save_successful, save_name)

    def _handle_time_expired(self):
        """
        Alert the user that time is up and set the next round number
        """
        self._ui.display_time_expired()
        self._game_data.mark_next_round()

    """
    Private Methods
    """

    def _start_new_or_loaded_game(self):
        """
        Start Game

        Activate hot key listeners
        """
        self._ui.listen_for_hot_keys()
        """
        Initialize the round number if this is a new game
        """
        if self._game_play_code == GameCode.NEW_GAME:
            self._game_data.mark_next_round()
        """
        Display welcome message
        """
        game_over = False
        winner = None

        self._welcome()
        """
        Game Loop
        """
        while not game_over:
            self._ui.display_round_border()
            self._setup_hand()
            self._play_hand()
            winner = self._cleanup_hand()
            game_over = winner is not None
        """
        Game Finished: Display the winner and attempt to save the game's history for playback
        """
        self._ui.display_winner(winner)
        self._attempt_save_game_history()

    def _setup_hand(self):
        """
        Check the timer, initialize hand players and pot, make blind bets, and pass out cards
        """
        current_time = self._manage_timer()
        self._game_data.setup_hand_players()
        self._game_data.setup_pot()
        self._game_data.make_blind_bets()
        self._game_data.pass_cards(Game.NUM_HOLE_CARDS)
        """
        Display all players with their positions
        """
        players_preflop = self._game_data.get_players()
        small_blind_pos, big_blind_pos = self._game_data.get_blind_positions()
        self._ui.display_player_data(players_preflop,
                                     self._game_data.get_button_positions())
        """
        Begin hand save snapshot
        """
        self._hand_actions.clear()
        round_number = self._game_data.get_round_number()
        self._game_save.begin_hand_snapshot(round_number, players_preflop,
                                            current_time)

    def _perform_showdown(self):
        """
        Find the best hand(s) and pay off the winning players
        """
        num_pots = self._game_data.get_num_pots()
        display_multiple_pots = num_pots > 1

        for pot in range(num_pots):
            """
            Determine winning players
            """
            ordered_player_hand_triples, winner_positions = self._game_data.evaluate_hands(
                pot)
            """
            Display winning players and pass the pot to them
            """
            self._ui.display_showdown_results(
                ordered_player_hand_triples,
                len(winner_positions),
                pot_idx=pot,
                display_multiple_pots=display_multiple_pots)
            self._game_data.pass_pot_to_winners(
                pot, player_pos_list=winner_positions)

    def _play_hand(self):
        """
        Execute a hand

        Preflop
        """
        round_folded = self._open_for_betting(preflop=True)

        if not round_folded:
            """
            Postflop streets
            """
            self._board_name_idx = 0

            while self._board_name_idx < len(
                    Game.NUM_CARDS_FOR_BOARD_TYPE) and round_folded is False:
                """
                Flip board cards and open the round for betting
                """
                board_cards = self._game_data.flip_board_cards(
                    Game.NUM_CARDS_FOR_BOARD_TYPE[self._board_name_idx])
                self._game_data.add_board_cards(board_cards)
                round_folded = self._open_for_betting()
                self._board_name_idx += 1

        if round_folded:
            """
            Pass pot to the only remaining player
            """
            num_pots = self._game_data.get_num_pots()

            for pot_idx in range(num_pots):
                self._game_data.pass_pot_to_winners(pot_idx)
                """
                Display results
                """
                remaining_player = self._game_data.get_hand_player(
                    pot_idx=pot_idx)
                self._ui.display_folded_round(remaining_player,
                                              Game.SHOW_FOLDED_HANDS,
                                              pot_idx=pot_idx)

        else:
            """
            Showdown
            """
            self._perform_showdown()

    def _cleanup_hand(self):
        """
        Remove any players who are out of chips
        """
        game_over = False
        winner = None
        eliminated_players = self._game_data.eliminate_busted_players()
        """
        Display eliminated players with their ranks
        And update the number of remaining players in the game
        """
        for player in eliminated_players:
            self._ui.display_player_eliminated(player,
                                               self._num_remaining_players)
            self._num_remaining_players -= 1
        """
        Get player data, current time stamp, and board cards to complete hand snapshot
        """
        players = self._game_data.get_players()
        timestamp = self._game_data.get_remaining_time()
        board = self._game_data.get_board()
        self._game_save.end_hand_snapshot(self._hand_actions, board, players,
                                          timestamp)
        """
        Check if there is a winner of the game and end the game if there is one
        """
        winner = self._game_data.get_winner()

        if winner is None:
            """
            If there are multiple players left, rotate the dealer, clear the game board, and reset cards
            """
            self._game_data.rotate_dealer()
            self._game_data.clear_board()
            self._game_data.reset_cards()
        else:
            game_over = True
        """
        Set the game code to continue to prevent reloading of saved values
        """
        self._game_play_code = GameCode.CONTINUE_GAME
        """
        Return game over status and winner if there is one
        """
        return winner

    def _setup_new_game(self):
        """
        Get setup information from the user
        """
        game_setup = GameSetup()
        game_setup.starting_num_players = self._ui.get_num_players(
            Game.NUM_PLAYERS_MIN, Game.NUM_PLAYERS_MAX)
        game_setup.starting_chip_count = self._ui.get_starting_chip_count(
            Game.MIN_STARTING_CHIP_COUNT)
        game_setup.starting_big_blind = self._ui.get_starting_big_blind(
            game_setup.starting_chip_count)
        game_setup.blind_increase_interval = self._ui.get_blind_increase_interval(
        )
        game_setup.handle_time_expired = self._handle_time_expired
        game_setup.blind_increase_scheme = Game.DEFAULT_BLIND_RAISING_SCHEME
        """
        Initialize the number of remaining players
        """
        self._num_remaining_players = game_setup.starting_num_players
        """
        Set up the game data
        """
        self._game_data.setup_game_data(game_setup)
        """
        Save the button positions
        """
        game_setup.button_positions = self._game_data.get_button_positions()
        """
        Snapshot the game setup for the game save
        """
        self._game_save.snap_game_setup(game_setup)

    def _setup_saved_game(self):
        """
        If this is a game in progress, prompt user to continue or overwrite
        If this is a complete game, prompt user for playback

        Load the existing game data to see if it is a finished or in-progress game
        """
        self._game_save.load()

        if self._game_save.is_game_complete():
            """
            Loaded game is already finished
            Prompt user to play back the completed game
            """
            load_game_history = self._ui.prompt_load_game_history()
            """
            If the user wishes to play back the loaded game, set up the theater
            Otherwise quit the game
            """
            if load_game_history:
                """
                Get the saved game data
                """
                loaded_game = self._game_save.get_game_save()
                """
                Parse the saved game data
                """
                game_setup, game_hands = loaded_game
                """
                Create a game theater and set the play protocol to playback
                """
                self._game_theater = GameTheater(game_setup, game_hands)
                self._game_play_code = GameCode.PLAYBACK_GAME
            else:
                """
                User cancellation: quit game
                """
                self._ui.display_load_game_history_cancellation()
                self._game_play_code = GameCode.NO_PLAY

        else:
            """
            Game is not complete yet
            Prompt user to load and continue this game or continue creating a new game with risk 
            of overwriting this one
            """
            load_existing_game = self._ui.prompt_load_game()

            if load_existing_game:
                """
                Get the loaded game data
                """
                loaded_game = self._game_save.get_game_save()
                """
                Parse loaded game data as setup and player state values
                """
                game_setup, game_hands = loaded_game
                round_number = GameData.INITIAL_ROUND_NUMBER
                player_state_final = None
                timestamp_final = None

                if len(game_hands) > 0:
                    """
                    If at least one hand was saved, load the player data and timestamp saved after the
                    last saved hand
                    Otherwise do not load any player or timestamp data

                    Also set the number of remaining players
                    """
                    last_hand = game_hands[-1]
                    round_number, _, _, _, _, player_state_final, timestamp_final = last_hand
                    self._num_remaining_players = len(player_state_final)
                else:
                    """
                    No hands played yet:
                        Set the number of remaining players to the initial number of players specified in setup
                    """
                    self._num_remaining_players = game_setup.starting_num_players
                """
                Package the load game values and set up the loaded game
                """
                game_setup.init_timestamp = timestamp_final
                game_setup.round_number = round_number
                game_setup.init_player_state = player_state_final
                game_setup.handle_time_expired = self._handle_time_expired
                game_setup.blind_increase_scheme = Game.DEFAULT_BLIND_RAISING_SCHEME

                self._game_data.setup_game_data(game_setup)
                self._game_play_code = GameCode.PLAY_LOAD_GAME

            else:
                """
                User decides to create and play a new game under the same name
                This means that if the user saves this new game at any point,
                the old game will be completely overwritten
                """
                self._game_save.clear_hand_history()
                self._ui.display_overwrite_warning()

    def _welcome(self):
        """
        Display the game title and hot key commands
        """
        self._ui.display_round_border()
        self._ui.display_title()
        self._ui.display_hot_key_commands()
        self._ui.display_round_border()

    def _attempt_save_game_history(self):
        """
        Prompt user for saving the game history at the end of the game
        """
        save_game_hist = self._ui.prompt_save_game_history()
        save_name = None

        if save_game_hist:
            """
            Attempt to save the game history, and if successful store the name of the file
            """
            save_success = self._game_save.save()

            if save_success:
                save_name = self._game_save.get_game_save_name()
        """
        Display confirmation message to user
        """
        self._ui.display_game_history_save_status(save_game_hist, save_name)

    def _manage_timer(self):
        """
        If the game is in load mode, start the timer now
        """
        if self._game_play_code == GameCode.PLAY_LOAD_GAME:
            self._game_data.start_timer()
        """
        Get the current round number and timestamp
        """
        round_number = self._game_data.get_round_number()
        remaining_time = self._game_data.get_remaining_time()
        """
        Reset the timer and increase the blinds if the timer is off
        """
        if remaining_time == 0:
            """
            Raise the blinds if they are not at their maximum value
            """
            if not self._blinds_maxed_out:
                """
                Raise the blinds if this is not the first round
                """
                if round_number != GameData.INITIAL_ROUND_NUMBER:
                    self._game_data.raise_blinds()
                """
                Determine if the blinds are now at the maximum
                """
                if self._game_data.blinds_maxed_out():
                    self._blinds_maxed_out = True
                """
                Set the timer and display a confirmation message
                """
                self._game_data.start_timer()
                remaining_time = self._game_data.get_remaining_time()
                big_blind = self._game_data.get_big_blind_amt()
                self._ui.display_timer_set(round_number, big_blind,
                                           remaining_time)

            else:
                """
                Display that the current big blind amount will not be raised
                Do not restart the timer
                """
                self._ui.display_blinds_maxed_out(
                    self._game_data.get_big_blind_amt())

        else:
            """
            If the timer is currently on, display the remaining time
            """
            self._ui.display_current_timer_value(round_number, remaining_time)
        """
        Return Result (remaining time)
        """
        return remaining_time

    def _get_available_moves(self, player, preflop=False):
        """
        Local Variables
        """
        available_moves = list()
        action_to_play = 0
        max_action = self._game_data.get_max_action()
        player_stack = player.get_stack_size()
        player_action = player.get_action()
        player_can_afford_to_raise = player_stack + player_action > max_action
        """
        If the player does not have any chips left, there are no options available
        """
        if player_stack > 0:
            """
            Available moves are dependent on the player's action relative to the current highest action
            (and one exception in the preflop round)
            """
            if player_action < max_action:
                available_moves.append(GameMove.CALL)
                """
                If all other players are all-in or this player cannot afford to raise the action 
                Then the player cannot raise the action
                """
                if self._has_multiple_available_betters(
                ) and player_can_afford_to_raise:
                    available_moves.append(GameMove.RAISE)
                """
                Minimum raise is a multiple of the current maximum bet in play
                """
                action_to_play = min(player_stack,
                                     Game.REQUIRED_RAISE_MULTIPLE * max_action)

            else:
                available_moves.append(GameMove.CHECK)
                """
                If all other players are all-in, this player cannot raise the action even higher
                """
                if self._has_multiple_available_betters():

                    if preflop and player_can_afford_to_raise:
                        available_moves.append(GameMove.RAISE)
                    else:
                        available_moves.append(GameMove.BET)
                """
                Minimum amount to introduce betting with is the size of the big blind
                EXCEPTION: On preflop, the big blind may raise the big blind
                """
                if preflop:
                    action_to_play = min(
                        player_stack,
                        Game.REQUIRED_RAISE_MULTIPLE *
                        self._game_data.get_big_blind_amt())
                else:
                    action_to_play = min(player_stack,
                                         self._game_data.get_big_blind_amt())
            """
            Folding is always an option if the player has chips left
            """
            available_moves.append(GameMove.FOLD)
        """
        Return result
        """
        return (available_moves, action_to_play)

    def _is_hand_over(self):
        """
        Determine if the hand is over
        Check if there is at least one side pot. In this case, the main pot must go to showdown
        Check if there are at least two players contending in the main pot. In this case, betting can still take place
        """
        num_pots = self._game_data.get_num_pots()
        num_players_in_hand = self._game_data.get_num_players_in_hand()
        return (num_pots < 2) and (num_players_in_hand < 2)

    def _has_multiple_available_betters(self):
        """
        Check if there is more than one available better in the current hand
        """
        return self._game_data.get_num_available_betters() > 1

    def _start_betting_round(self, preflop=False):
        """
        Local Variables
        """
        _, big_blind_idx = self._game_data.get_blind_positions()
        current_player_idx = None
        round_over = False
        """
        Get the position of the first player to act
        """
        if preflop:
            current_player_idx = self._game_data.get_next_player_pos(
                big_blind_idx)
        else:
            current_player_idx = self._game_data.get_next_player_pos(
                GameData.DEALER_IDX)
        """
        Game data setup for a betting round
        """
        self._game_data.init_betting_round()
        """
        Round loop: keep cycling turns until the round is over
        """
        while not round_over:
            """
            Setup: Get a copy of the acting player for UI puproses
            """
            player = self._game_data.get_hand_player(
                player_idx=current_player_idx)
            """
            Play: Determine, prompt, and play a legal move
            """
            available_moves, action_to_play = self._get_available_moves(
                player, preflop=preflop)

            if len(available_moves) > 0:
                """
                Show the pot and community cards if postflop
                """
                if preflop is False:
                    self._ui.display_board(self._game_data.get_board(),
                                           board_name_idx=self._board_name_idx)

                chosen_move, chosen_amount = self._ui.prompt_available_moves(
                    player, available_moves, action_to_play)
                adjusted_amount = self._game_data.play_move(
                    current_player_idx, chosen_move, chosen_amount)
                self._ui.display_move_made(player, chosen_move,
                                           adjusted_amount)
                """
                Store the action for the save snapshot
                """
                self._hand_actions.append(
                    (player.ID, chosen_move, adjusted_amount))

            else:
                """
                Player has no available moves: Skip player and move on
                """
                self._ui.display_no_moves_available(player)
                self._game_data.skip_player(current_player_idx)
            """
            Cleanup: Find the next player to act and determine if the round is over
            """
            current_player_idx = self._game_data.get_next_player_pos(
                current_player_idx)
            round_over = self._game_data.is_round_over()

    def _open_for_betting(self, preflop=False):
        """
        Display the current pot
        """
        self._ui.display_pot(self._game_data.get_pot())
        """
        Start a betting round if more than one player is able to bet
        """
        if preflop or self._has_multiple_available_betters():
            self._start_betting_round(preflop=preflop)
        else:

            if preflop is False:
                self._ui.display_board(self._game_data.get_board(),
                                       board_name_idx=self._board_name_idx)
            """
            Insufficient amount of remaining betters in the hand: no betting can take place
            """
            self._ui.display_no_bet_from_all_in()
        """
        Move all player action to the pot and display it
        """
        self._game_data.move_action_to_pot()
        """
        Determine if the hand has ended prematurely and return it
        """
        return self._is_hand_over()
示例#29
0
 def testLoadData(self):
     g = GameData('PlanetWars')
     print()
     print("last_game_id: %s" % g.last_game_id)
     print(g.games)
     print(g.results)
示例#30
0
文件: main.py 项目: DevFabrx/Dungeon
    parser = argparse.ArgumentParser(description="P0 Dungeon")
    parser.add_argument("-b", help="Activates b tasks", action='store_true')
    parser.add_argument("--savefile",
                        dest="savefile",
                        help="A player savefile")
    parser.add_argument(
        "--create-player",
        dest="create_player",
        action='store_true',
        help="Create a player save file. Stored to player.json by default")

    parser.set_defaults(create_player=False)
    args = parser.parse_args()

    # create gamedata object that holds game information
    gamedata = GameData()

    if args.savefile is not None:
        if args.b:
            gamedata.b = True
        else:
            gamedata.b = False
        gamedata.player = util.load_player(args.savefile)
        vil = Village(gamedata)
        vil_gd = vil.run()
    elif args.b is True:
        gamedata.b = True
        gamedata.player = Player()
        util.create_player_file(gamedata)
        char = CreateCharacter(gamedata)
        gd = char.run()
示例#31
0
    def loadProject(self, file_name):
        """Load project file data and populate UI elements/set up signals and slots
        """
        if file_name:
            try:
                self.data = GameData.fromFilename(file_name, self)
            except KeyError:
                QMessageBox(
                    QMessageBox.Critical,
                    "Error",
                    "Unable to load project due to malformed data",
                ).exec()
                return
            except OSError:
                QMessageBox(
                    QMessageBox.Critical,
                    "Error",
                    "Unable to open project file",
                ).exec()
                return
        else:
            return

        self.setWindowTitle("JIDE - " + self.data.getGameName())
        self.gendat_act.setEnabled(True)
        self.load_jcap.setEnabled(True)
        self.data.setUndoStack(self.undo_stack)
        self.sprite_scene = GraphicsScene(self.data, Source.SPRITE, self)
        self.tile_scene = GraphicsScene(self.data, Source.TILE, self)
        self.sprite_view = GraphicsView(self.sprite_scene, self)
        self.tile_view = GraphicsView(self.tile_scene, self)
        self.sprite_view.setStyleSheet("background-color: #494949;")
        self.tile_view.setStyleSheet("background-color: #494949;")

        sprite_pixel_palette = self.sprite_pixel_palette_dock.pixel_palette
        tile_pixel_palette = self.tile_pixel_palette_dock.pixel_palette
        sprite_color_palette = self.sprite_color_palette_dock.color_palette
        tile_color_palette = self.tile_color_palette_dock.color_palette

        sprite_pixel_palette.subject_selected.connect(
            self.sprite_scene.setSubject)
        self.sprite_scene.set_color_switch_enabled.connect(
            sprite_color_palette.color_preview.setColorSwitchEnabled)
        self.sprite_color_palette_dock.palette_updated.connect(
            self.sprite_scene.setColorPalette)
        self.sprite_color_palette_dock.palette_updated.connect(
            self.sprite_pixel_palette_dock.palette_updated)
        sprite_color_palette.color_selected.connect(
            self.sprite_scene.setPrimaryColor)
        tile_pixel_palette.subject_selected.connect(self.tile_scene.setSubject)
        self.tile_scene.set_color_switch_enabled.connect(
            tile_color_palette.color_preview.setColorSwitchEnabled)
        self.tile_color_palette_dock.palette_updated.connect(
            self.tile_scene.setColorPalette)
        self.tile_color_palette_dock.palette_updated.connect(
            self.tile_pixel_palette_dock.palette_updated)
        tile_color_palette.color_selected.connect(
            self.tile_scene.setPrimaryColor)

        self.sprite_color_palette_dock.setup(self.data)
        self.tile_color_palette_dock.setup(self.data)
        self.sprite_pixel_palette_dock.setup(self.data)
        self.tile_pixel_palette_dock.setup(self.data)
        self.canvas_tabs = QTabWidget()
        self.canvas_tabs.addTab(self.sprite_view, "Sprites")
        self.canvas_tabs.addTab(self.tile_view, "Tiles")
        self.canvas_tabs.setTabEnabled(0, True)
        self.canvas_tabs.setTabEnabled(1, True)
        self.setCentralWidget(self.canvas_tabs)
        self.canvas_tabs.currentChanged.connect(self.setCanvas)
        self.setCanvas(0)

        self.data.col_pal_updated.connect(
            lambda source, *_: self.canvas_tabs.setCurrentIndex(int(source)))
        self.data.col_pal_renamed.connect(
            lambda source, *_: self.canvas_tabs.setCurrentIndex(int(source)))
        self.data.col_pal_added.connect(
            lambda source, *_: self.canvas_tabs.setCurrentIndex(int(source)))
        self.data.col_pal_removed.connect(
            lambda source, *_: self.canvas_tabs.setCurrentIndex(int(source)))
        self.data.pix_batch_updated.connect(
            lambda source, *_: self.canvas_tabs.setCurrentIndex(int(source)))
        self.data.row_count_updated.connect(
            lambda source, *_: self.canvas_tabs.setCurrentIndex(int(source)))

        self.select_tool.triggered.connect(
            lambda checked, tool=Tools.SELECT: self.sprite_scene.setTool(tool))
        self.select_tool.triggered.connect(
            lambda checked, tool=Tools.SELECT: self.tile_scene.setTool(tool))
        self.pen_tool.triggered.connect(
            lambda checked, tool=Tools.PEN: self.sprite_scene.setTool(tool))
        self.pen_tool.triggered.connect(
            lambda checked, tool=Tools.PEN: self.tile_scene.setTool(tool))
        self.fill_tool.triggered.connect(lambda checked, tool=Tools.FLOODFILL:
                                         self.sprite_scene.setTool(tool))
        self.fill_tool.triggered.connect(lambda checked, tool=Tools.FLOODFILL:
                                         self.tile_scene.setTool(tool))
        self.line_tool.triggered.connect(
            lambda checked, tool=Tools.LINE: self.sprite_scene.setTool(tool))
        self.line_tool.triggered.connect(
            lambda checked, tool=Tools.LINE: self.tile_scene.setTool(tool))
        self.rect_tool.triggered.connect(lambda checked, tool=Tools.RECTANGLE:
                                         self.sprite_scene.setTool(tool))
        self.rect_tool.triggered.connect(lambda checked, tool=Tools.RECTANGLE:
                                         self.tile_scene.setTool(tool))
        self.ellipse_tool.triggered.connect(lambda checked, tool=Tools.ELLIPSE:
                                            self.sprite_scene.setTool(tool))
        self.ellipse_tool.triggered.connect(
            lambda checked, tool=Tools.ELLIPSE: self.tile_scene.setTool(tool))

        for tool in self.tools:
            tool.setEnabled(True)

        self.pen_tool.setChecked(True)
        self.pen_tool.triggered.emit(True)
示例#32
0
import txtgamelib
from txtgamelib import when, say

from gamedata import GameData

gameData = GameData()


@when('debug')
def debug():
    import pdb
    pdb.set_trace()  # Start debugger


@when('status')
def show_status():
    gameData.status()


@when('map info')
def show_map_info():
    gameData.show_map_info()


@when('gather RESOURCE PLACE NUMPEOPLE')
def gather(resource, place, numpeople):
    gameData.gather(resource, place, numpeople)


@when('show buildings')
def show_buildings():
示例#33
0
        return None, gamedata
    def next(self, next_state):
        pass


class Retailer(StateHandler):
    def __init__(self,gamedata):
        StateHandler.__init__(self, Retailer.start, [Retailer.start, Retailer.list, Retailer.choose], Retailer.quit, gamedata)


Retailer.start = Start()
Retailer.list = List()
Retailer.choose = Choose()
Retailer.quit = Quit()


if __name__ == '__main__':
    gamedata = GameData()
    gamedata.player = Player()
    gamedata.player.strength = 25
    gamedata.player.defense = 20
    gamedata.player.agility = 20
    gamedata.player.speed = 35
    gamedata.player.name = "Horst"
    gamedata.player.inventory = [Item(name="Potion", price=50, influenced_attribute="hp", value="30"),
                                 Item(name="Potion", price=50, influenced_attribute="hp", value="30"),
                                 Item(name="Potion", price=50, influenced_attribute="hp", value="30")]
    player_file = util.create_player_file(gamedata)
    gamedata.player = util.load_player("player.json")
    ret = Retailer(gamedata)
    ret_gd = ret.run()
示例#34
0
文件: main.py 项目: Herbsi/pathfinder
def main():
    parser = argparse.ArgumentParser(description="P0 Adventure")
    parser.add_argument(
        "--savefile",
        dest="savefile",
        default="game.json",
        help="The save file. default: 'game.json'",
    )
    parser.add_argument(
        "--new-game",
        dest="new_game",
        default=False,
        action="store_true",
        help="Create a new save file.",
    )
    parser.add_argument(
        "-b",
        dest="bonus_tasks",
        default=False,
        action="store_true",
        help="enable bonus tasks",
    )
    parser.add_argument(
        "--print-bonus",
        dest="print_bonus",
        default=False,
        action="store_true",
        help="print bonus task list and exit",
    )
    args = parser.parse_args()

    if args.print_bonus:
        print_bonus_tasks()
        return

    # your code starts here
    save = args.savefile
    if args.new_game:
        user = Player()
        user.createNewCharacter()
        gamedata = GameData(player=user, savefile=save, bonus_tasks=args.bonus_tasks)
        if args.bonus_tasks:
            totengraeber = Gravedigger()
            gamedata.gravedigger = totengraeber
            truhe = Chest()
            gamedata.chest = truhe

    else:
        gamedata = load_gamedata(save)
        user = gamedata.player
        if args.bonus_tasks:
            totengraeber = gamedata.gravedigger
            truhe = gamedata.chest

    schmied = Shopkeeper(name="blacksmith", inventory=blacksmith_items)
    druide = Shopkeeper(name="druid", inventory=druid_items)
    prog0 = Village(
        player=user, bonus_tasks=args.bonus_tasks, blacksmith=schmied, druid=druide
    )

    if args.bonus_tasks:
        prog0.gravedigger = totengraeber
        prog0.chest = truhe

    while True:
        user_choice = village(prog0)

        if user_choice == 5:
            dung0 = Dungeon(player=user, bonus_tasks=args.bonus_tasks)
            if args.bonus_tasks:
                dung0.gravedigger = totengraeber
            dungeon(dung0)
        elif user_choice == 6:
            save_gamedata(gamedata, save),
            print("Game saved to {}".format(save))
        elif user_choice == 0:
            quit(gamedata, save)
            break
        else:
            raise KeyError(
                "main.py Something went wrong with the user choosing what to do!"
            )

    sys.exit(0)