Ejemplo n.º 1
0
def _add_gender():
    Chargen.x1=5
    Chargen.y1=5
    Chargen.ww=25
    Chargen.hh=6
    #get new gender name
    _genderName=rog.prompt(Chargen.x1,Chargen.y1,Chargen.ww,Chargen.hh,maxw=20, q="what is your gender?", mode="text")
    #pronouns
    #subject pronoun
    _pronoun1=rog.prompt(
        Chargen.x1,Chargen.y1,Chargen.ww,Chargen.hh,maxw=10,
        q="what are your pronouns?\n\tsubject pronoun:",
        default="they",mode="text",insert=True
        )
    #object pronoun
    _pronoun2=rog.prompt(
        Chargen.x1,Chargen.y1,Chargen.ww,Chargen.hh,maxw=10,
        q="what are your pronouns?\n\tobject pronoun:",
        default="them",mode="text",insert=True
        )
    #possessive pronoun
    _pronoun3=rog.prompt(
        Chargen.x1,Chargen.y1,Chargen.ww,Chargen.hh,maxw=10,
        q="what are your pronouns?\n\tpossessive pronoun:",
        default="their",mode="text",insert=True
        )
    #confirm
    success=rog.prompt(Chargen.x1,Chargen.y1,50,15,
q='''confirm gender: {}\nsubject pronoun: {}\nobject pronoun: {}
possessive pronoun: {}
\nConfirm (y) or Cancel (n)'''.format(
        _genderName,_pronoun1,_pronoun2,_pronoun3),
        mode='wait'
        )
    if success:
        #add the gender into the genders text file for next game
        genderFileName="genders.txt"
        genderFileDir=os.path.join(
            os.path.curdir,os.path.pardir,"settings",genderFileName)
        def writeGender(n,p1,p2,p3):
            with open(genderFileDir, "a+") as file:
                file.write("{}:{},{},{}\n".format(n,p1,p2,p3))
        try:
            writeGender(_genderName,_pronoun1,_pronoun2,_pronoun3)
        except FileNotFoundError:
            print("Failed to load {}, creating new file...".format(genderFileName))
            with open(genderFileDir, "w+") as file:
                file.write("\n") #nothing needed in the file
            writeGender(_genderName,_pronoun1,_pronoun2,_pronoun3) #then write
            
        #return gender information for chargen
        return (_genderName,(_pronoun1,_pronoun2,_pronoun3,),)
    else: #failure
        return ("",())
Ejemplo n.º 2
0
def pickup_pc(pc):
    rog.alert("Pick up what?{d}".format(d=dirStr))
    args=rog.get_direction()
    if not args:
        rog.alert()
        return
    dx,dy,dz=args
    xx,yy=pc.x + dx, pc.y + dy
    
    things=rog.thingsat(xx,yy)
    if pc in things:
        things.remove(pc)

    choice=None
    if len(things) > 1:
        rog.alert("There are multiple things here. Pick up which item?")
        choices = [] #["all",] #should player be able to pickup multiple things at once? Maybe could be a delayed action?
        for thing in things:
            choices.append(thing)
        choice=rog.menu(
            "pick up", rog.view_port_x()+2, rog.view_port_y()+2, choices
            )
    else:
        if things:
            choice=things[0]

    if (choice and not choice == "all"):

        if choice == K_ESCAPE:
            return
        
        #thing is creature! You can't pick up creatures :(
        if choice.isCreature:
            rog.alert("You can't pick that up!")
            return
        #thing is on fire! What are you doing trying to pick it up??
        if rog.on(choice,FIRE):
            answer=""
            while True:
                answer=rog.prompt(0,0,rog.window_w(),1,maxw=1,
                    q="That thing is on fire! Are you sure? y/n",
                    mode='wait',border=None)
                answer=answer.lower()
                if answer == "y" or answer == " " or answer == K_ENTER:
                    rog.alert("You burn your hands!")
                    rog.burn(pc, FIRE_BURN)
                    rog.hurt(pc, FIRE_HURT)
                    break
                elif answer == "n" or answer == K_ESCAPE:
                    return
        # put in inventory
        pocketThing(pc, choice)
    #elif choice == "all":
    #    
    else:
        rog.alert("There is nothing there to pick up.")
Ejemplo n.º 3
0
def _get_gift_for(ent:int) -> tuple:
    opt = rog.prompt(
        0,0,rog.window_w(),4,q='Offer money or possessions? $/i',
        mode='wait',default='$'
        )
    if opt=='$':
        value = rog.prompt(
            0,0,rog.window_w(),4,q='Offer how much money?',
            mode='wait',default=0
            )
    elif opt=='i':
        options = {
            "cancel" : 0,
            "item from inventory" : -100,
            }
        body = world.component_for_entity(rog.pc(), cmp.Body)
        i=-1
        for arm in body.parts[cmp.BPC_Arms].arms:
            i+=1
            if (arm and arm.hand.held.item):
                options.update({"{}".format(item) : item})
        opt = rog.menu("Offer what item?",0,0,menu)
        if opt==-1: return ("money",0,)
        item = options[opt]
        if item==0: return ("money",0,)
        if item==-100:
            # temporary
            # TODO: get from inventory
            return ("money",0,)
        itemn = world.component_for_entity(item, cmp.Name)
        entn = world.component_for_entity(ent, cmp.Name)
        ans = rog.prompt(
            "Offer {ti}{i} to {tn}{n}?".format(
            i=itemn.name,n=entn.name,
            it=TITLES[itemn.title],
            tn=TITLES[entn.title]
            ),
            0,0, mode='wait'
            )
        if ans=='y':
            return ("item",item,)
    return ("money",0,) # if we made it this far
Ejemplo n.º 4
0
def _select_mass():
    _kg=rog.prompt( Chargen.x1,Chargen.y1+Chargen.iy,Chargen.ww,6,maxw=20,
        q="How heavy are you? (press a key from 1 to 9. 3 is average)",
        mode="wait" )
    try:
        _kg = int(_kg)
    except:
        _kg = 3
    if (_kg==0 or not _kg): _kg=3
    _kgMult = 1 + (_kg - 3)/8

    # save selected data
    Chargen._kg = _kg
    Chargen._kgMult = _kgMult
    # print char data so far
    _printElement("name: {}".format(Chargen._name), Chargen.iy-3)
    _printElement("gender: {}".format(Chargen._genderName), Chargen.iy-2)
    _printElement("height: {} / 9".format(Chargen._cm), Chargen.iy-1)
    Chargen.iy=_printElement("mass: {} / 9".format(Chargen._kg), Chargen.iy)
    print("mass chosen: ", Chargen._kg)
Ejemplo n.º 5
0
def _select_height():
    Chargen.ww=rog.window_w()
    avg = 3 if Chargen.female else 5
    _cm=rog.prompt( Chargen.x1,Chargen.y1+Chargen.iy,Chargen.ww,6,maxw=20,
        q="How tall are you? (press a key from 1 to 9. {} is average)".format(avg),
        mode="wait" )
    try:
        _cm = int(_cm)
    except:
        _cm = avg
    if (_cm==0 or not _cm): _cm=avg
    _cmMult = 1 + (_cm - 5)/20
    
    # save selected data
    Chargen._cm = _cm
    Chargen._cmMult = _cmMult
    # print char data so far
    _printElement("name: {}".format(Chargen._name), Chargen.iy-2)
    _printElement("gender: {}".format(Chargen._genderName), Chargen.iy-1)
    Chargen.iy=_printElement("height: {} / 9".format(Chargen._cm), Chargen.iy)
    print("height chosen: ", Chargen._cm)
Ejemplo n.º 6
0
def chargen(sx, sy):
    world = rog.world()
    # init
    x1 = 0
    y1 = 0
    xx = 0
    yy = 4
    iy = 0
    ww = rog.window_w()
    hh = 5

    # _printElement - local function
    # draw the string to con_game at (x1,y1) then move y vars down
    def _printElement(elemStr):
        #global yy,y1,x1
        rog.dbox(x1,
                 y1 + iy,
                 ROOMW,
                 3,
                 text=elemStr,
                 wrap=False,
                 border=None,
                 con=rog.con_game(),
                 disp='mono')
        rog.blit_to_final(rog.con_game(), 0, 0)
        rog.refresh()

    # get char data from player

    # name
    _name = rog.prompt(x1,
                       y1,
                       ww,
                       hh,
                       maxw=20,
                       q="What is your name?",
                       mode="text")
    _title = ""
    print("Name chosen: ", _name)
    _printElement("Name: {}".format(_name))
    iy += 1

    # load saved game
    loadedGame = False
    savedir = os.listdir(os.path.join(os.path.curdir, "save"))
    for filedir in savedir:
        if ".save" != filedir[-5:]:
            continue  #wrong filetype
        try:
            with open(filedir, "r") as save:
                line = save.readline()
                if ("name:{}\n".format(_name) == line):
                    #found a match. Begin reading data
                    pc = loadFromSaveFile(save)
                    return pc
        except FileNotFoundError:
            pass
        except:
            print("ERROR: Corrupted save file detected.")
            print("Continuing chargen...")
            break

    if not loadedGame:
        #continue chargen...

        # gender
        rog.dbox(x1,
                 y1 + iy,
                 ROOMW,
                 3,
                 text="What is your gender?",
                 wrap=True,
                 border=None,
                 con=rog.con_final(),
                 disp='mono')
        rog.refresh()
        #get added genders
        _genderList = {}
        genderFileDir = os.path.join(os.path.curdir, "settings", "genders.txt")
        try:
            with open(genderFileDir, "r") as file:
                for line in file:
                    if "//" in line: continue
                    data = line.split(':')
                    if len(data) < 2: continue
                    gname = data[0]
                    data = data[1].split(',')
                    gpronouns = data
                    _genderList.update({gname: gpronouns})
        except FileNotFoundError:
            print("ALERT: file '{}' not found. Creating new file...")
            with open(genderFileDir, "w+") as file:
                file.write("\n")

        #gender selection
        _gender = ''
        while (_gender == ''):
            _menuList = {
                'm': 'male',
                'f': 'female',
                'n': 'nonbinary',
                '*': 'random',
            }
            #read genders from genders.txt

            _gender = rog.menu("Gender Select",
                               xx,
                               yy,
                               _menuList,
                               autoItemize=False)
            if _gender == 'nonbinary':
                #select gender from list of added genders
                _menuNonbin = []
                for jj in _genderList.keys():
                    _menuNonbin.append(jj)
                _menuNonbin.append('add new gender')
                choice = rog.menu("Nonbinary Genders", xx, yy, _menuNonbin)
                #add gender
                if choice == 'add new gender':
                    _genderName, _pronouns = _add_gender()
                else:
                    _genderName = choice
                    _pronouns = _genderList[_genderName]
                if _genderName == '':  #failed to select or add new gender
                    _gender = ''  #prompt user again for gender
            else:  #random, male and female
                if _gender == 'random':
                    _gender = random.choice((
                        "male",
                        "female",
                    ))
                if _gender == 'male':
                    _genderName = "male"
                    _pronouns = (
                        'he',
                        'him',
                        'his',
                    )
                elif _gender == 'female':
                    _genderName = "female"
                    _pronouns = (
                        'she',
                        'her',
                        'hers',
                    )
        print("Gender chosen: ", _genderName)
        _printElement("Gender: {}".format(_genderName))
        iy += 1

        # class
        rog.dbox(x1,
                 y1 + iy,
                 ROOMW,
                 3,
                 text="What is your profession?",
                 wrap=True,
                 border=None,
                 con=rog.con_final(),
                 disp='mono')
        rog.refresh()
        _classList = {
        }  #stores {className : (classChar, classID,)} #all classes
        #create menu options
        _menuList = {}  #stores {classChar : className} #all playable classes
        _randList = []  #for random selection.
        for k, v in jobs.getJobs().items():  # k=ID v=charType
            if v not in rog.playableJobs():
                continue  #can't play as this class yet
            ID = k  # get ID of the class
            typ = v  # get chartype of the class
            name = jobs.getName(ID)
            _classList.update({name: (
                typ,
                ID,
            )})
            _menuList.update({typ: name})
            _randList.append(ID)
        _menuList.update({'*': 'random'})
        #user selects a class
        _className = rog.menu("Class Select",
                              xx,
                              yy,
                              _menuList,
                              autoItemize=False)
        #random
        if _className == 'random':
            _classID = random.choice(_randList)
            _className = jobs.getName(_classID)
        #get the relevant data
        _type = _classList[_className][0]  # get the class Char value
        _mask = _type
        _classID = _classList[_className][1]

        #grant stats / abilities of your chosen class

        print("Class chosen: ", _className)
        _printElement("Class: {}".format(_className))
        iy += 1

        # skill
        rog.dbox(x1,
                 y1 + iy,
                 ROOMW,
                 3,
                 text="In which skill are you learned?",
                 wrap=True,
                 border=None,
                 con=rog.con_final(),
                 disp='mono')
        #rog.refresh()
        #get list of all skills
        _skillName = rog.menu("Skill Select", xx, yy, SKILLS.values())
        #get the skill ID
        for skid, name in SKILLS.items():
            if name == _skillName:
                _skillID = name
                break
        print("Skill chosen: ", _skillName)
        #should show ALL skills you're skilled in, not just the one you pick
        #for skill in jobs.getSkills(_skillID):
        _printElement("Skills: {}".format(_skillName))
        iy += 1

        #stats?
        _stats = {}
        #gift?
        _gift = 0

        #create pc object from the data given in chargen

##        pc = world.create_entity( # USE create_monster function!!!!
##            cmp.Position(sx,sy),
##            cmp.Name(_name, title=_title,pronouns=_pronouns),
##            cmp.Draw('@', COL['white']),
##            cmp.Form(
##            )

##        pc = rog.create_monster('@',0,0,COL['white'],mutate=0)
##        pc.name = _name
##        pc.title = _title
##        pc.mask = '@'
##        pc.job = _className
##        pc.gender = _genderName
##        pc.pronouns = _pronouns
##        pc.faction = FACT_ROGUE
##        #add additional skill
##        rog.train(pc,_skillID)
##        #add specific class stats

    return pc
Ejemplo n.º 7
0
def pickup_pc(pc):
    world = rog.world()
    pos = world.component_for_entity(pc, cmp.Position)
    pcx = pos.x
    pcy = pos.y
    rog.alert("Pick up what?{d}".format(d=dirStr))
    args=rog.get_direction()
    if not args:
        rog.alert()
        return
    dx,dy,dz=args
    xx,yy = pcx + dx, pcy + dy
    
    things=rog.thingsat(xx,yy)
    if pc in things: #can't pick yourself up.
        things.remove(pc)

    choice=None
    if len(things) > 1:
        rog.alert("There are multiple things here. Pick up which item?")
        choices = [] #["all",] #should player be able to pickup multiple things at once? Maybe could be a delayed action?
        for thing in things:
            choices.append(thing)
        choice=rog.menu(
            "pick up", rog.view_port_x()+2, rog.view_port_y()+2, choices
            )
    else:
        if things:
            choice=things[0]

    if (choice and not choice == "all"):

        if choice == K_ESCAPE:
            return
        
        #thing is creature! You can't pick up creatures :( or can you...?
        if world.has_component(choice, cmp.Creature):
            rog.alert("You can't pick that up!")
            return
        #thing is on fire, prompt user & burn persistent rogues
        if rog.on(choice,FIRE):
            answer=""
            while True:
                answer=rog.prompt(0,0,rog.window_w(),1,maxw=1,
                    q="That thing is on fire! Are you sure? y/n",
                    mode='wait',border=None)
                answer=answer.lower()
                if answer == "y" or answer == " " or answer == K_ENTER:
                    rog.alert("You burn your hands!")
                    rog.burn(pc, FIRE_BURN)
                    rog.hurt(pc, FIRE_HURT)
                    break
                elif answer == "n" or answer == K_ESCAPE:
                    return
        # put in inventory
        pocketThing(pc, choice)
##    elif choice == "all":
##        for tt in things:
##            pocketThing(pc, tt)
    else:
        rog.alert("There is nothing there to pick up.")
Ejemplo n.º 8
0
def rest_pc(pc):
    turns=rog.prompt(0,0,rog.window_w(),1,maxw=3,
                     q="How long do you want to rest? Enter number of turns:",
                     mode='wait',border=None)
    for t in range(turns):
        rog.queue_action(pc, wait)
Ejemplo n.º 9
0
def commands(pc, pcAct):
    world = rog.world()

    directional_command = 'move'
    
    for act,arg in pcAct:

##        print(act)
##        print(arg)
        
        rog.update_base()
        
        #----------------#
        # convert action #
        #----------------#
        
        if act =='context-dir':
            act=directional_command
##        if act =='context':
##            pass
        # moving using the menu move keys
        if (act =='menu-nav' and rog.game_state()=="normal"):
            act=directional_command
        
        
        #----------------#
        # perform action #
        #----------------#
#-----------MOUSE ACTION----------------------------#
        
        if act == 'lclick':
            mousex,mousey,z=arg
            if rog.wallat(mousex,mousey):
                return
            pos = world.component_for_entity(pc, cmp.Position)
            print("Left click unimplemented")
##            rog.path_compute(pc.path, pos.x,pos.y, rog.mapx(mousex), rog.mapy(mousey))
            #rog.occupation_set(pc,'path')

        if act == 'rclick':
            pass
        
#------------OTHER ACTION--------------------------#
        
        if act == 'help':
            rog.help()

        # "move-prompt" : True
        # prompt for a direction
        #   and then perform the move action in that direction
        if act == 'move-prompt':
            pass

        # "attack-prompt" : True
        # prompt for a direction
        #   and then perform the attack action in that direction
        if act == 'attack-prompt':
            pass
        
        # "move" : (x_change, y_change, z_change,)
        if act == 'move':
            _Update()
            dx,dy,dz=arg
            pos = world.component_for_entity(pc, cmp.Position)
            actor = world.component_for_entity(pc, cmp.Actor)
            xto=pos.x + dx
            yto=pos.y + dy

            # wait
            if (xto==pos.x and yto==pos.y):
                actor.ap = 0
                return

            # out of bounds
            if ( not rog.is_in_grid_x(xto) or not rog.is_in_grid_y(yto) ):
                return

            # warning for slow move speed
            if rog.allow_warning_msp():
                msp=rog.getms(pc, 'msp')
                if msp <= 10:
                    inp=rog.prompt(
                        0,0,rog.window_w(), 6, mode='wait',
                        q='''Warning: your movement speed is critically slow
(MSP: {}). Are you sure you want to move? y/n'''.format(msp)
                        )
                    if inp!='y':
                        return
                    else:
                        rog.expire_warning_msp() #TODO: when is best time to reset this warning?
            # end if
            
            # choose context-sensitive action #
            
            # fight if there is a monster present
            mon = rog.monat(xto,yto)
            if mon: # and mon != pc):
                action.fight(pc,mon)
            # or move
            elif not rog.solidat(xto,yto):
                # space is free, so we can move
                if action.move(pc, dx,dy):
                    rog.view_center_player()
            else:
                rog.alert("That space is occupied.")
        # end conditional
        
        # "attack" : (x, y, z,)
        if act == 'attack':
            _Update()
            xto,yto,zto=arg
            pos = world.component_for_entity(pc, cmp.Position)
            actor = world.component_for_entity(pc, cmp.Actor)

            # out of bounds
            if ( not rog.is_in_grid_x(xto) or not rog.is_in_grid_y(yto) ):
                return
            
            # fight if there is a monster present
            mon = rog.monat(xto,yto)
            # ... but don't attack yourself!
            if mon == pc:
                rog.alert("You can't fight yourself!")
                return
            
            if mon:
                action.fight(pc,mon)
            else:
                ent = rog.thingat(xto,yto)
                if ent:
                    action.fight(pc,ent)
                else:
                    rog.msg("You strike out at thin air, losing your balance.")
                    actor.ap = 0
                    rog.set_status(
                        pc, cmp.StatusOffBalance,
                        t=2, q=-MISS_BAL_PENALTY
                        )
        # end conditional

        # chat with closest speaking entity;
        #   if multiple good options, prompt for which one.
        if act == "chat-context":
            action.chat_context(pc)
            _Update()
            return
        if act == "change-pos": # change body position
            action.change_bodypos_pc(pc)
            _Update()
            return
        if act == "change-msp": # change speed of movement (walking, running, jogging, etc.)
            action.change_speed_pc(pc)
            _Update()
            return
        if act == "msp-up": # change from walk to powerwalk, to trot, jog, etc.
            action.speed_up_pc(pc)
            _Update()
            return
        if act == "msp-down": # change from sprint to run, to jog, to trot, etc.
            action.slow_down_pc(pc)
            _Update()
            return
        if act == "target-prompt": #target entity + fire / throw / attack
            action.target_pc_generic(pc)
            _Update()
            return
        if act == "get-prompt":
            action.pickup_pc(pc)
            _Update()
            return
        if act == "openclose-prompt": #open or close
            action.open_pc(pc)
            _Update()
            return
        if act == "open-prompt": #open or close
            action.open_pc(pc)
            _Update()
            return
        if act == "close-prompt": #open or close
            action.open_pc(pc)
            _Update()
            return
        if act == "jog": #begin jogging
            action.jog_pc(pc)
            _Update()
            return
        if act == "run": #begin running
            action.run_pc(pc)
            _Update()
            return
        if act == "sprint": #begin sprinting
            action.sprint_pc(pc)
            _Update()
            return

        #unused actions
        '''if act == "bomb":
            action.bomb_pc(pc)
            return'''
        
        #
        #
        # special actions #
        #
        
        if act == 'find player': #useful to immediately show where the player is
            pos = world.component_for_entity(pc, cmp.Position)
            rog.view_center_player()
            rog.update_game()
            rog.update_final()
            rog.game_update() #call all the updates
            rog.alert('press any key to continue...')
            rog.Input(rog.getx(pos.x), rog.gety(pos.y), mode='wait')
            rog.update_base()
            rog.alert('')
            return
        if act == "look":
            pos = world.component_for_entity(pc, cmp.Position)
            rog.routine_look(pos.x,pos.y)
            return
        if act == "move view":
            rog.routine_move_view()
            return
        if act == "fixed view":
            rog.fixedViewMode_toggle()
            return  
        if act == 'select':
            # TESTING
            print(rog.Input(0,0,20))
            return
        if act == 'exit':
            return
Ejemplo n.º 10
0
def _select_class():
    _classList={} #stores {className : (classChar, classID,)} #all classes
    #create menu options
    _menuList={} #stores {classChar : className} #all playable classes
    _randList=[] #for random selection.
    for k,v in entities.getJobs().items(): # k=ID v=charType
##        if v not in rog.playableJobs(): continue #can't play as this class yet
        ID=k        # get ID of the class
        typ=v       # get chartype of the class
        name=entities.getJobName(ID)
        _classList.update({name:(typ,ID,)})
        _menuList.update({typ:name})
        _randList.append(ID)
    _menuList.update({'*':'random'})

    classSelected = False
    while not classSelected:
        _printChargenData(showclass=False)
        rog.dbox(
            Chargen.x1,Chargen.y1+Chargen.iy,Chargen.ww,3,
            text="what is your profession?",
            wrap=True,border=None,con=rog.con_final(),disp='mono'
            )
        rog.refresh()
        #user selects a class
        _className = rog.menu(
            "class select",Chargen.xx,Chargen.yy+Chargen.iy,_menuList,
            autoItemize=False
            )
        #random
        if (_className == 'random' or _className == -1):
            _classID = random.choice(_randList)
            _className = entities.JOBS[_classID][1]
        #get the relevant data
        _type = _classList[_className][0] # get the class Char value
        _mask = _type
        _classID = _classList[_className][1]
        _mass = entities.getJobMass(_classID)
        _jobstats = entities.getJobStats(_classID).items()
        _jobskills = entities.getJobSkills(_classID)
        _jobmoney = entities.getJobMoney(_classID)
        _jobitems = entities.getJobItems(_classID)
        _jobkeys = entities.getJobClearance(_classID)
        
        # for display by confirmation prompt
        _classDescription = entities.getJobDescription(_classID)
        # create class stats info
        _classStats=""
        if _jobstats:
            for k,v in _jobstats:
                _classStats += "{}: {}, ".format(STATS[k],v)
            _classStats=_classStats[:-2]
        # create class items info
        _classItems = ""
        if _jobitems:
            for tupl in _jobitems:
                name,table,quantity,slot,mat,script = tupl
                matname = "{} ".format(rog.getMatName(mat)) if mat else ""
                _classItems += "{}{}, x{}; ".format(matname, name, quantity)
            _classItems=_classItems[:-2]
        
        # info about class && confirmation
        while True:
            ph=4
            text = '''Class: {name}.
{desc}
Mass: {kg} KG.
Starts with (${money}, {items}).
[ {stats} ]'''.format(
                name=_className,
                kg=_mass,
                money=_jobmoney,
                items=_classItems,
                desc=_classDescription,
                stats=_classStats
                )
            rog.dbox(
                0,0,rog.msgs_w(),12,text,
                wrap=True,border=1,con=rog.con_final()
                )
            ans=rog.prompt(
                0,rog.window_h()-ph,rog.window_w(),ph,
                q='''Choose this class? y/n''',
                mode="wait",default='n',wrap=False
                )
            if ans=='y':
                classSelected=True
                break
            elif ans=='n':
                libtcod.console_clear(rog.con_final())
                rog.refresh()
                break
            else:
                continue
        # end while
    # end while
    
    # confirmed class selection
    Chargen._type = _type
    Chargen._classID = _classID
    Chargen._className = _className
    Chargen._jobstats = _jobstats
    Chargen._jobskills = _jobskills
    Chargen._jobmoney = _jobmoney
    Chargen._jobitems = _jobitems
    Chargen._jobkeys = _jobkeys
    Chargen._jobmass = _mass
    
    #add specific class skills
    for sk_id,sk_lv in Chargen._jobskills.items():
        rog.setskill(Chargen.pc, sk_id, sk_lv)
    
    # print char data so far
    _printChargenData()
    rog.refresh()
    print("class chosen: ", _className)
Ejemplo n.º 11
0
def chargen(sx, sy):
    ''' character generation function
    # Create and return the player Thing object,
    #   and get/set the starting conditions for the player
    # Arguments:
    #   sx, sy: starting position x, y of player entity
    '''
    # TODO: saving/loading game
    
    # init
    world = rog.world()
    __init__Chargen()   # init some global vars for use during chargen
    height_default = AVG_HUMAN_HEIGHT
    libtcod.console_clear(0)
    libtcod.console_clear(rog.con_game())
    libtcod.console_clear(rog.con_final())
    #
    
    # get character data from player input #
    
    # name
    ans=""
    while (not ans or ans=='0'):
        ans=rog.prompt(
            Chargen.x1,Chargen.y1,Chargen.ww,Chargen.hh,maxw=20,
            q="what is your name?", mode="text"
            )
    Chargen._name = ans
    _title = 0
    
    # print char data so far
    print("name chosen: ", Chargen._name)
    libtcod.console_clear(rog.con_final())
    Chargen.iy=_printElement("name: {}".format(Chargen._name), Chargen.iy)
    #
    
    # load saved game
    loadedGame = False
    
        # TODO: forget this -- use Pickle or similar
    
##    savedir=os.listdir(os.path.join(
##        os.path.curdir,os.path.pardir,"save"))
##    for filedir in savedir:
##        if ".save" != filedir[-5:] :
##            continue #wrong filetype
##        try:
##            with open(filedir, "r") as save:
##                line = save.readline()
##                if ("name:{}\n".format(Chargen._name) == line):
##                    #found a match. Begin reading data
##                    pc=loadFromSaveFile(save)                    
##                    return pc
##        except FileNotFoundError:
##            pass
##        except:
##            print("ERROR: Corrupted save file detected.")
##            print("Continuing chargen...")
##            break
    # end for
    
    if loadedGame:
        # load old character (TODO)
        pass
    else:
        # make a new character

        # create a basic entity for the PC, with no defining characteristics
        Chargen.skillsCompo = cmp.Skills()
        Chargen.flags = cmp.Flags(IMMUNERUST,)
        Chargen.pc = world.create_entity(
            Chargen.skillsCompo, Chargen.flags)
        #continue chargen by refining the details of the PC...
        
        #gender selection
        _select_gender()
        
        # body type
        _select_height()
        _select_mass()
        
        # class
        _select_class()
        
        
        #----------------------------------#
        # start creating player components #
        #----------------------------------#
        
        # create stats component
        Chargen.statsCompo=cmp.Stats(
            hp=BASE_HP, mp=BASE_MP, mpregen=BASE_MPREGEN*MULT_STATS,
            mass=0, # base mass before weight of water and blood and fat is added
            encmax=BASE_ENCMAX,
            resfire=BASE_RESFIRE, rescold=BASE_RESCOLD,
            resbio=BASE_RESBIO, reselec=BASE_RESELEC,
            resphys=BASE_RESPHYS,
            reslight=BASE_RESLIGHT, ressound=BASE_RESSOUND,
            _str=BASE_STR*MULT_ATT, _con=BASE_CON*MULT_ATT,
            _int=BASE_INT*MULT_ATT, _agi=BASE_AGI*MULT_ATT,
            _dex=BASE_DEX*MULT_ATT, _end=BASE_END*MULT_ATT,
            atk=BASE_ATK*MULT_STATS, dmg=BASE_DMG*MULT_STATS,
            pen=BASE_PEN*MULT_STATS, dfn=BASE_DFN*MULT_STATS,
            arm=BASE_ARM*MULT_STATS, pro=BASE_PRO*MULT_STATS,
            gra=BASE_GRA*MULT_STATS, bal=BASE_BAL*MULT_STATS,
            ctr=BASE_CTR*MULT_STATS,
            reach=BASE_REACH*MULT_STATS,
            spd=BASE_SPD, asp=BASE_ASP, msp=BASE_MSP,
            sight=0, hearing=0, # senses gained from Body component now. TODO: do the same things for monster gen...
            scary=BASE_SCARY,
            beauty=BASE_BEAUTY
            )
        Chargen.fearCompo=cmp.FeelsFear(BASE_COURAGE + PLAYER_COURAGE)
        #add specific class stats
        for stat, val in Chargen._jobstats:
            value=val*MULT_STATS if stat in STATS_TO_MULT.keys() else val
            Chargen.statsCompo.__dict__[stat] += value
        #
        
        
        #----------------#
        #    big menu    #
        #----------------#
        
        # (attributes/stats/skills/characteristics)
        
        # menu loop until uer selects "<confirm>"
        while(not Chargen.confirm):
            Chargen.menu={}
            Chargen.menu.update({"<confirm>" : "confirm"})
            _chargen_attributes()
            _chargen_stats()
            _chargen_skills()
            _chargen_traits()
            _selectFromBigMenu()
        # end while

        # choose a personality
        personality = random.choice(MAIN_PERSONALITIES)
##        print("personality: ", personality)
        
        
        # continue creating player entity #
        
            # calculate some stats
        cm = int(height_default * Chargen._cmMult * Chargen.mcm)
        kg = int((Chargen._jobmass + Chargen.mass) * Chargen._kgMult * Chargen.mmass)
        
            # mass stat mods
        fatratio=DEFAULT_BODYFAT_HUMAN
        if Chargen._kg >= 5:
            fatratio += (Chargen._kg-4)/16
        elif Chargen._kg < 3:
            fatratio -= fatratio*(3-Chargen._kg)/3
        fatratio += Chargen.bodyfat/100
        fatratio *= Chargen.mbodyfat
##        print("bodyfat: ", fatratio)
        
            # height stat mods
        reachMult = 1 + (Chargen._cm-5)/20 #/10
        reachMult *= Chargen.mreach
        if Chargen._cm < 5:
            mspMult = 1 + (Chargen._cm-5)/24 #/12
        else:
            mspMult = 1 + (Chargen._cm-5)/32 #/16
        mspMult *= Chargen.mmsp
            #
        
        # create body
        body, basemass = rog.create_body_humanoid(
            kg=kg, cm=cm, female=Chargen.female,
            bodyfat=fatratio)
        body.hydration = body.hydrationMax * 0.98
        body.satiation = body.satiationMax * 0.85
        # body temperature
        meters = cmp.Meters()
        meters.temp = BODY_TEMP[BODYPLAN_HUMANOID][0]
        
        # confirmation #
        
        # print char data
        libtcod.console_clear(rog.con_final())
        Chargen.iy=0
        Chargen.iy=_printElement("name: {}".format(Chargen._name), Chargen.iy)
        Chargen.iy=_printElement("gender: {}".format(Chargen._genderName), Chargen.iy)
        Chargen.iy=_printElement("class: {} ({})".format(Chargen._className, Chargen._type), Chargen.iy)
        Chargen.iy=_printElement("height: {} cm ({} / 9)".format(cm, Chargen._cm), Chargen.iy)
        Chargen.iy=_printElement("mass: {} kg ({} / 9)".format(kg, Chargen._kg), Chargen.iy)
        _drawskills(rog.con_final())
        _drawtraits(rog.con_final())
        rog.refresh()
        #
        
        # prompt to continue or restart chargen
        _ans=''
        while _ans!='y':
            # roll character
##            reroll(statsCompo, Chargen.skillsCompo)
            _ans=rog.prompt(Chargen.x1,rog.window_h()-4,Chargen.ww,4,maxw=20,
                            q="continue with this character? y/n", #/r (reroll)
                            mode="wait"
                            )
            if _ans.lower()=='n':
                return chargen(sx,sy)
##            if _ans.lower()=='r':
##                reroll(statsCompo, Chargen.skillsCompo)
        # end if
        

            #----------------------------------#
            #     finish creating player       #
            #----------------------------------#

        # apply any stat changes from Chargen that haven't been applied

        Chargen.statsCompo.mass += basemass
        Chargen.statsCompo.reach = round(reachMult*Chargen.statsCompo.reach)
        Chargen.statsCompo.msp = round(mspMult*Chargen.statsCompo.msp)
        if Chargen.fastLearner:
            world.add_component(pc, cmp.FastLearner())
        if Chargen.attractedMen:
            world.add_component(pc, cmp.AttractedToMen())
        if Chargen.attractedWomen:
            world.add_component(pc, cmp.AttractedToWomen())
        
        #create pc object from the data given in chargen
        
        # add components to entity
        pc=Chargen.pc
        world.add_component(pc, Chargen.statsCompo)
        world.add_component(pc, body)
        world.add_component(pc, meters)
        world.add_component(pc, cmp.Player())
        world.add_component(pc, cmp.Name(Chargen._name, title=_title))
        world.add_component(pc, cmp.Draw('@', COL['white'], COL['deep']))
        world.add_component(pc, cmp.Position(sx, sy))
        world.add_component(pc, cmp.Actor())
        world.add_component(pc, cmp.Form(
            mat=MAT_FLESH, val=VAL_HUMAN*MULT_VALUE ))
        world.add_component(pc, cmp.Creature(
            job = Chargen._className,
            faction = FACT_ROGUE,
            species = SPECIE_HUMAN
            ))
        world.add_component(pc, cmp.SenseSight())
        world.add_component(pc, cmp.SenseHearing())
        world.add_component(pc, cmp.Mutable())
        world.add_component(pc, cmp.Inventory())
        world.add_component(pc, cmp.Gender(Chargen._gender))
        world.add_component(pc, cmp.Job(Chargen._classID))
        world.add_component(pc, cmp.Speaks())
        world.add_component(pc, cmp.Personality(personality))
        world.add_component(pc, cmp.Wets(BASE_RESWET))
        world.add_component(pc, cmp.Dirties(BASE_RESDIRT))
        world.add_component(pc, cmp.Bleeds(BASE_RESBLEED))
        world.add_component(pc, cmp.FeelsPain(BASE_RESPAIN))
        world.add_component(pc, Chargen.fearCompo)
        world.add_component(pc, cmp.Insulated(BASE_INSUL))
        world.add_component(pc, cmp.GetsSick())
    # end if
    
    # init PC entity
    pc=Chargen.pc
    rog.register_entity(pc)
    rog.add_listener_sights(pc)
    rog.add_listener_sounds(pc)
    rog.grid_insert(pc)
    rog.update_fov(pc)
    init(pc)

    # give items
    for itemdata in Chargen._jobitems:
        name, func, quantity, eq_const, material, script = itemdata
        for _ in range(quantity):
            item = func(name, sx,sy, mat=material)
            rog._initThing(item) # register (init stats), fill HP,
            rog.give(pc, item)
            if script: script(item)
            if eq_const: rog.equip(pc, item, eq_const)
    # end for
    
    return pc
Ejemplo n.º 12
0
def _select_trait(_trait):
    pc=Chargen.pc
    pts = CHARACTERISTICS[_trait][0]
    # already have
    if _trait in Chargen._traits:
        _alreadyHaveTrait(_trait)
        return False
    # confirmation prompt
    description = CHARACTERISTICS_DESCRIPT[_trait]
    c = "Costs" if pts < 0 else "Gives"
    description = '{}: {}. {}: {} pts. Points remaining: {}'.format(
        _trait, description, c, abs(pts), Chargen.traitPts)
    rog.dbox( 0,0,Chargen.ww,8,
              text=description, wrap=True, con=rog.con_final() )
    inp=rog.prompt(0,10,Chargen.ww,4,q="select this trait? y/n", mode='wait')
    if inp!='y':
        return False
    # insufficient points
    if Chargen.traitPts < -pts:
        _insufficientPoints(Chargen.traitPts, -pts, "trait")
        return False
    
    success = False
    
    # (attempt to) apply trait
    data = CHARACTERISTICS[_trait][1]
    for k,v in data.items():
                # meta traits
        if k=="skillPts":
            Chargen.skillPts += v
            success = True
        elif k=="statPts":
            Chargen.statPts += v
            success = True
        elif k=="attPts":
            Chargen.attPts += v
            success = True
                # component flags
        elif k=="astigmatism": # TODO: make these apply components in chargen
            Chargen.astigmatism=True
            success = True
        elif k=="cancer":
            Chargen.cancer=True
            success = True
        elif k=="rapidMetabolism":
            Chargen.rapidMetabolism=True
            success = True
        elif k=="ironGut":
            Chargen.ironGut=True
            success = True
        elif k=="immuneVenom":
            Chargen.immuneVenom=True
            success = True
        elif k=="immunePoison":
            Chargen.immunePoison=True
            success = True
        elif k=="immunePain":
            Chargen.immunePain=True
            success = True
        elif k=="hydrophobia":
            Chargen.hydrophobia=True
            success = True
        elif k=="attractedMen":
            Chargen.attractedMen=True
            success = True
        elif k=="attractedWomen":
            Chargen.attractedWomen=True
            success = True
        elif k=="fastLearner":
            Chargen.fastLearner=True
            success = True
                # sub-menu traits
        elif k=="talent":
            success = _select_talent()
        elif k=="trauma":
            success = _select_trauma()
        elif k=="addict":
            success = _select_addict()
        elif k=="allergy":
            success = _select_allergy()
        elif k=="scarred":
            success = _select_scar()
                # body stats
        elif k=="mfat":
            Chargen.mbodyfat *= v
            success = True
        elif k=="fat":
            Chargen.bodyfat += v
            success = True
        elif k=="mgut":
            Chargen.mgut *= v #(TODO: make these change stats in chargen)
            success = True
        elif k=="mvision":
            Chargen.mvision *= v #(TODO: make these change stats in chargen)
            success = True
                # stats
        elif k=="mmass":
            Chargen.mmass *= v
            success = True
        elif k=="mass":
            Chargen.mass += v
            success = True
        elif k=="mcm":
            Chargen.mcm *= v
            success = True
        elif k=="mreach":
            Chargen.mreach *= v
            success = True
        elif k=="mreach":
            Chargen.mreach *= v
            success = True
        elif k=="mmsp":
            Chargen.mmsp *= v
            success = True
        elif k=="bea":
            Chargen.statsCompo.bea += v
            success = True
        elif k=="idn":
            Chargen.statsCompo.idn += v
            success = True
        elif k=="cou":
            Chargen.statsCompo.cou += v
            success = True
        elif k=="str":
            Chargen.statsCompo.str += v*MULT_STATS
            success = True
        elif k=="agi":
            Chargen.statsCompo.agi += v*MULT_STATS
            success = True
        elif k=="dex":
            Chargen.statsCompo.dex += v*MULT_STATS
            success = True
        elif k=="end":
            Chargen.statsCompo.end += v*MULT_STATS
            success = True
        elif k=="con":
            Chargen.statsCompo.con += v*MULT_STATS
            success = True
        elif k=="int":
            Chargen.statsCompo.int += v*MULT_STATS
            success = True
        elif k=="resbio":
            Chargen.statsCompo.resbio += v
            success = True
        elif k=="resfire":
            Chargen.statsCompo.resfire += v
            success = True
        elif k=="rescold":
            Chargen.statsCompo.rescold += v
            success = True
        elif k=="respain":
            Chargen.statsCompo.respain += v
            success = True
    # end for
    
    if success:
        # trait chosen successfully
        Chargen.traitPts += pts
        if Chargen.traitPts <= 0:
            Chargen.open_traits = False
        Chargen._traits.append(_trait)
        print("trait chosen: {} (pts: {})".format(_trait, Chargen.traitPts))
        return True
    return False