I have been working further on my text adventure (see thread: http://www.daniweb.com/forums/thread285737.html) and have come to the part where I would like to manage the change of time (of day) and adjust the date as time passes. I have some code that does it, but was wondering if there is a better way.

I have the following global variables:

# timeMgr variables
vtime = 4
vday = "Monday"
vdate = 14
vmonth = "March"
vyear = 514
vhour = "It is the morning of Monday, 14 March, 514"

and I call the following code after actions have occurred:

def timeMgr():
    """ Time Manager for the village """
    # global variables for the time manager
    global vtime, vhour, vday, vdate, vmonth, vyear

    # factor 1 hours for each activity
    vtime += 1
    if vtime < 12:      # morning indicator
        # format the vhour string for the time of day
        vhour = "It is the morning of "
        vhour += vday
        vhour += ", "
        vhour += str(vdate)
        vhour += " "
        vhour += vmonth
        vhour += ", "
        vhour += str(vyear)
        vhour += "."
        print vhour
    else:
        if vtime < 18:  # afternoon indicator
            vhour = "It is the afternoon of "
            vhour += vday
            vhour += ", "
            vhour += str(vdate)
            vhour += " "
            vhour += vmonth
            vhour += ", "
            vhour += str(vyear)
            vhour += "."
            print vhour
        else:
            if vtime < 24:  # evening indicator
                vhour = "It is the evening of "
                vhour += vday
                vhour += ", "
                vhour += str(vdate)
                vhour += " "
                vhour += vmonth
                vhour += ", "
                vhour += str(vyear)
                vhour += "."
                print vhour
            elif vtime == 24:   # end of day indicator
                vhour =  "The day has ended, you crawl to your bed and get some much needed rest!"
                print vhour
                vtime = 0
                if vdate != 30:
                    vdate +=1
                else:
                    vdate = 1
                    # cycle the end of the month to the next month
                    if vmonth == "March":
                        vmonth = "April"
                    elif vmonth == "April":
                        vmonth = "May"
                    elif vmonth == "May":
                        vmonth = "June"
                    elif vmonth == "June":
                        vmonth = "July"
                    elif vmonth == "July":
                        vmonth = "August"
                    elif vmonth == "August":
                        vmonth = "September"
                    elif vmonth == "September":
                        vmonth = "October"
                    elif vmonth == "October":
                        vmonth = "November"
                    elif vmonth == "November":
                        vmonth = "December"
                    elif vmonth == "December":
                        vmonth = "January"
                    elif vmonth == "January":
                        vmonth = "February"
                    elif vmonth == "February":
                        vmonth = "March"
                    else:
                        print "There is a month of the year problem!"
                # cycle the end of the day to the next day
                if vday == "Monday":
                    vday = "Tuesday"
                elif vday == "Tuesday":
                    vday = "Wednesday"
                elif vday == "Wednesday":
                    vday = "Thursday"
                elif vday == "Thursday":
                    vday = "Friday"
                elif vday == "Friday":
                    vday = "Saturday"
                elif vday == "Saturday":
                    vday = "Sunday"
                elif vday == "Sunday":
                    vday = "Monday"
                else:
                    print "There is a day of the week problem!"
            else:
                print "There is an hour of the day problem!"

I keep thinking it is too much code, but can't find an easier way to handle it. Any help, clues or other notes would be appreciated.

Recommended Answers

All 18 Replies

I didn't understand exactly your aim, but python has a time module which tells you the current time, month day year and so on.

import time
print time.strftime('%a%A%b%d%m%B')

TueTuesdayJunJuneTue Jun 15 15:53:00 2010150610

there is a long list of things you can get by this module
http://docs.python.org/library/time.html?highlight=time#module-time

hope it helps

This my code of parsing various dates in string format and finding next day could help you:

## request: possibility to parse dates with various separators
from datetime import timedelta,date

for datestring in ['01/23/2010','01.12.2020','1.1.1976',
                   '2 2 2000', ## if you do not make extra limitations this goes also
                   '3d2m1998' ## this gets the message
                   ]:
    sep=[s for s in datestring if not s.isdigit()]

    if len(sep)!=2 or sep[0] != sep [1]: print "Mixup in separators",sep
    else:
        print sep ## for testing
        datesep=sep[0]
        mm,dd,yy = (int(part) for part in datestring.split(datesep))
        print date(yy,mm,dd)+ timedelta(days=1) ## print tomorrow's date
    
"""Output:
>>> 
['/', '/']
2010-01-24
['.', '.']
2020-01-13
['.', '.']
1976-01-02
[' ', ' ']
2000-02-03
Mixup in separators ['d', 'm']
"""

My apologies, I do not want to work with real dates. I am currently using real days of the week and months of the year, but once I get this working smoothly, I would prefer to switch to created days of week and months of year.

So, as time progresses in the game, I would like to show the created day of week and the created month of year. This also means that I would not be measuring real time either.

Thank you AINT and TONYJV for you input.

Only difference I see is that you advance time one hour instead of one day like my code. You would just expand time representation with similar way for clock time or do:

from datetime import timedelta,date

d = date(2010,1,26)
t = 8
while d.day != 2:
    t += 1
    if t == 24:
        t = 0
        d += timedelta(days=1)
    print "%10s,%3i:00" % (d,t)

To get your style of textual date without year replace the print with:

print "%s,%3i:00" % (d.strftime("%d. %B"),t)

And the simpler way is:

from datetime import timedelta,datetime

d = datetime(2010,1,26,8,0,0)
while d.day != 2:
    d += timedelta(hours=1)
    print d.strftime("%d. %B %H:%M")

I think it's better to use turns as a time unit in text adventure (currently implementing). Also i think you should create your own "time" library module and class for your convinience

Thanks ULTIMATEBUSTER, I have the function for it, I've just been digesting the code from TONYJV. My plan was to fashion 30 day months, with a typical 24 hour day and 7 day week.

Thanks again to TONYJV for the input. Here is what I have right now. This will run an infinite loop even though my while loop says < 24, but it works for testing for me. Also, I still need to repress the time change comment at the end of the day and just display the end of day message.

class timeMgr(object):
    """ This is the time manager object for the village """
    def __init__ (self, vtime, vdaykey, vday, vdate, vmonthkey, vmonth, vyear):
    # initialize needed variables for the time manager object
        self.vdaykey = vdaykey
        self.vmonthkey = vmonthkey
        self.vtime = vtime
        self.vday = vday
        self.vdate = vdate
        self.vmonth = vmonth
        self.vyear = vyear
        self.vcomment = "It is the morning of "
        self.vhour = ""
        self.formatVhour()

    def Change(self):
        # setup time increment by 1 hour for activity
        self.vtime += 1
        self.formatVhour()

    def Show(self):
        # setup banner to display for the current date and time
        self.vhour = self.vcomment
        self.vhour += self.vday
        self.vhour += ", "
        self.vhour += str(self.vdate)
        self.vhour += " "
        self.vhour += self.vmonth
        self.vhour += ", "
        self.vhour += str(self.vyear)
        self.vhour += "."
        print self.vhour

    def formatVhour(self):
        # format the vhour comment based on date and time
        if self.vtime < 12:				# morning indicator
            self.vcomment = "It is the morning of "

        else:

            if self.vtime < 18:			# afternoon indicator
                self.vcomment = "It is the afternoon of "

            else:
                if self.vtime < 24:			# evening indicator
                    self.vcomment = "It is the evening of "

                elif self.vtime == 24:		# end of day indicator
                    self.vcomment =  "The day has ended, you crawl to your bed and get some much needed rest!"
                    self.hour = self.vcomment
                    print self.vhour
                    self.vtime = 5

                    if self.vdate != 30:
                        self.vdate +=1

                    elif self.vdate == 30:			# cycle the end of the month to the next month
                        self.vdate = 1
                        if self.vmonthkey < 11:
                            self.vmonthkey += 1
                        elif self.vmonthkey == 11:
                            self.vmonthkey = 0
                            self.vyear += 1
                        else:
                            print "There is a month of the year problem!"

                    vcmonth = ("January", "February", "March", "April", "May", "June", "July",
                               "August", "September", "October", "November", "December")
                    self.vmonth = vcmonth[self.vmonthkey]

                    # cycle the end of the day to the next day
                    if self.vdaykey != 6:
                        self.vdaykey += 1
                    elif self.vdaykey == 6:
                        self.vdaykey = 0
                    else:
                        print "There is a day of the week problem!"

                    vcday = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
                    self.vday = vcday[self.vdaykey]

                else:
                    print "There is an hour of the day problem!"

viltime = timeMgr(5, 1, "Monday", 14, 2, "March", 514)
while viltime.vtime < 24:
    viltime.Change()
    viltime.Show()

Please let me know if you find any areas where I could improve this and thank you in advance for any comments and/or suggestions.

Here I reformated your code little to use modulo (%) to cycle through various units. I also used the special ..if..else structure to have alternate values.

Looks month became 30 days during all these changes, I think you had it 31 days in beginning.

I removed the strings from initialization and changed the init parameters to work better as keywords.

class timeMgr(object):
    """ This is the time manager object for the village """
    vcmonth = ("January", "February", "March",
               "April", "May", "June",
               "July", "August", "September",
               "October", "November", "December")
    
    vcday = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
    dformat = "%s %s, %i %s, %s"

    def __init__ (self, time, weekday, date, month, year):
    # initialize needed variables for the time manager object
        self.vdaykey = weekday
        self.vmonthkey = month
        self.vtime = time
        self.vdate = date
        self.vyear = year
        self.formatVhour()

    def Change(self):
        # setup time increment by 1 hour for activity
        self.vtime = self.vtime % 24 + 1
        if self.vtime==1:
            self.vtime = 5
        self.formatVhour()

    def Show(self):
        # setup banner to display for the current date and time
        complete = self.vcomment, self.vday, self.vdate, self.vmonth, self.vyear
        print self.dformat % complete

    def formatVhour(self):
        # format the vhour comment based on date and time
            self.vcomment = ("It is the morning of " if self.vtime < 12
                             else ( "It is the afternoon of " if self.vtime < 18
                                    else ("It is the evening of " if self.vtime < 24
                                          else "The day has ended, you crawl to your bed and get some much needed rest!\n" )
                                    )
                             )
            self.vhour = self.vcomment
 
            if self.vtime == 5:
                self.vdate = (self.vdate + 1) % 30
                self.vdaykey = (self.vdaykey + 1) % 6

                if  self.vdate == 1:
                    
                    self.vmonthkey = (self.vmonthkey + 1) % 12 

                    if not self.vmonthkey:
                        self.vyear += 1 

            ## prepare string formats
            self.vday = self.vcday[self.vdaykey]
            self.vmonth = self.vcmonth[self.vmonthkey]

viltime = timeMgr(time = 7, weekday = 1, date = 30, month = 11, year = 514)
while viltime.vdate != 1:
    viltime.Change()
    print viltime.vtime,"o'clock: ",
    viltime.Show()

"""
8 o'clock:  It is the morning of  Monday, 30 December, 514
9 o'clock:  It is the morning of  Monday, 30 December, 514
10 o'clock:  It is the morning of  Monday, 30 December, 514
11 o'clock:  It is the morning of  Monday, 30 December, 514
12 o'clock:  It is the afternoon of  Monday, 30 December, 514
13 o'clock:  It is the afternoon of  Monday, 30 December, 514
14 o'clock:  It is the afternoon of  Monday, 30 December, 514
15 o'clock:  It is the afternoon of  Monday, 30 December, 514
16 o'clock:  It is the afternoon of  Monday, 30 December, 514
17 o'clock:  It is the afternoon of  Monday, 30 December, 514
18 o'clock:  It is the evening of  Monday, 30 December, 514
19 o'clock:  It is the evening of  Monday, 30 December, 514
20 o'clock:  It is the evening of  Monday, 30 December, 514
21 o'clock:  It is the evening of  Monday, 30 December, 514
22 o'clock:  It is the evening of  Monday, 30 December, 514
23 o'clock:  It is the evening of  Monday, 30 December, 514
24 o'clock:  The day has ended, you crawl to your bed and get some much needed rest!
 Monday, 30 December, 514
5 o'clock:  It is the morning of  Tuesday, 1 January, 515
"""

Suggesting name change:
time,vtime -> hour, vhour
date,vdate -> day, vday

there's a better idea. Instead of a bunch of argument, __init__ should take either an int, which is the time represented in a number that you can convert into days, hours, etc.

It should also maybe take a tuple or a list that has all the variables in it and create a map

Using keyword parameters makes this parameter arrangement quite usable. Or to use namedtuple or one parameter same format string as Show gives.
Nothing stops you giving tuple or list now. You only must put * in front.

TONYJV thank you again, though I do have a question. If I don't display the time of day

5 o'clock:

do I need the entire line:

dformat = "%s %s, %i %s, %s"

Also, where is some plain english documentation/explanation about using these, I have had no luck with plain english explanations yet.

ULTIMATEBUSTER, thank you for your reply, but could you provide an example of what you mean?

That format is used in Show,nothing connection for time show. I only added it to help debugging.

Format string documentation is at
http://docs.python.org/library/stdtypes.html#string-formatting

That format list replace the whole sequence of + and str in your version of Show. I put the format in class variable so that it is easy to change later.

>>> print "%s %s, %i %s, %s" %('It is the morning of', 'Monday', 30, 'December', 514)
It is the morning of Monday, 30 December, 514

Means:
Pick up and print from tuple after % string,
print ' ',
pick up and print second string,
print ', ',
pick up integer from third place in the tupple and print it,
print ' ',
print the next one, which is string,
', ' and
last string (even it is int, does not matter).

I have to respectfully disagree. I still believe that a text advnture will benefit from its own unique time system. You can have a conversion system provided by a module, but you shouldn't use an object with multiple arguments with year, month as an integer can represent all those. You will probably not be confined within the day, month, year thing.

TONYJV, thank you again, the link provided the details I needed in a manner that actually made sense to me :)

ULTIMATEBUSTER, I'm confused, are you respectfully disagreeing with TONYJV's answer to my inquiry or with my implementation of time management in my text adventure? If you have another way of trying to do this, please provide some sample code supporting your position. I welcome any input.

I was hoping to get a response from ULTIMATEBUSTER, but since there has been no reply, I will mark this thread Solved.

Thanks TONYJV

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.