как отметить время? - PullRequest
0 голосов
/ 09 мая 2018

Я работаю над своим первым оригинальным проектом, это виртуальный питомец. Код в основном готов, но я не могу понять, как отметить время. Я хочу сделать это, чтобы домашнее животное становилось голодным и скучающим со временем. Я пытался создать такую ​​функцию def manageHunger(): while True: myPet.hungerLevel -= 1 time.sleep(60) и многие другие функции, но ничего не видно для работы. это весь код:

import random
import time
import winsound
import sys
import os
import textwrap
import random


class pet:
    def __init__(self):
        self.petName = ''
        self.hungerLevel = 10
        self.happinesLevel = 10
        self.sleepy = False
        self.sadnessLevel = 0
        self.dead = False
        self.entratainiment_level = 15

myPet = pet()

global playedTimes
playedTimes = 0

def titleScreenOptions():
    playerOptions = input("> ")

    if playerOptions.lower() == "play":
        setupGame()

    elif playerOptions.lower() == "help":
        helpMenu()

    elif playerOptions.lower() == "quit":
        sys.exit()

    while playerOptions.lower() not in ["play", "help", "quit"]:
        print('sorry, your command was not recognized by my system, check for any speeling mistakes and try again.')
        print('You can type "help" at any give moment to see a list of basic commands')
        playerOptions = input("> ")

    if playerOptions.lower() == "play":
        setupGame()

    elif playerOptions.lower() == "help":
        helpMenu()

    elif playerOptions.lower() == "quit" or playerOptions.lower() == "exit":
        sys.exit()


def titleScreen():
    os.system('cls')
    print("#=====================================================================#")
    print("# Welcome to pymagochi, the game where you raise your own virtual pet #")
    print("#=====================================================================#")
    print("#                              |>PLAY<|                               #")
    print("#                              |>HELP<|                               #")
    print("#                              |>EXIT<|                               #")
    print("#=====================================================================#")
    print("#            |created by: julio|      |2018, Brazil|                  #")
    print("")
    titleScreenOptions()

def helpMenu():
    os.system('cls')
    print("#=============================================#")
    print("# type the commands in order to execute then, #")
    print("# here are some of the basic commands for you #")
    print("#                 >check<                     #")
    print("#                 >feed<                      #")
    print("#               >go to bed<                   #")
    print("#              >play a game<                  #")
    print("#=============================================#")
    print("# the rest you can figure it out by your self #")
    print("# I mean, you are not that stupid, are you?   #")
    print("#=============================================#")
    print("")
    titleScreenOptions()


def promptUser():
    print("#############################")
    print("what would you like to do?")
    userCommands = input(">> ")
    validCommands = ['feed', 'play a game', 'walk', 'eat', 'drink', 'go to bed', 'help me', 'quit', 'exit', 'clear', 'play', 'fun', 'check', 'status', 'help', 'sleep', 'rest']
    while userCommands.lower() not in validCommands:
        print('sorry, your command was not recognized by my system, check for any speeling mistakes and try again.')
        print('You can type "help" at any give moment to see a list of basic commands')
        userCommands = input(">> ")

    if userCommands.lower() == 'quit' or userCommands.lower() == 'exit':
        sys.exit()

    if userCommands.lower() == 'clear':
        clearScreen()

    elif userCommands.lower() in ['eat', 'feed', 'drink']:  
        feedPet()

    elif userCommands.lower() in ['play a game', 'play', 'fun']:
        playWithPet()

    elif userCommands.lower() in ['check', 'status']:
        checkStatus()

    elif userCommands.lower() in ['go to bed', 'sleep', 'rest']:
        sleepPet()

    elif userCommands.lower() in ['help me', 'help']:
        print("===========================================")
        print("type the commands in order to execute then,")
        print("here are some of the basic commands for you")
        print("                >check<                    ")
        print("                >feed<                     ")
        print("              >go to bed<                  ")
        print("             >play a game<                 ")
        print("===========================================")
        print("the rest you can figure it out by your self")
        print("I mean, you are not that stupid, are you?  ")
        print("===========================================")
        userCommands = input(">> ")


def feedPet():
    myPet.hungerLevel += 1
    if myPet.hungerLevel > 20:
        myPet.hungerLevel = 20
        print("thanks, but I am full already")

    print("thanks for feeding me!!!")
    promptUser()

def playWithPet():
    if myPet.sleepy == False:   
        print("yeah!!! let's play a game")
        myPet.hungerLevel -= 1
        myPet.entratainiment_level += 2
        gameChoice()
        if myPet.entratainiment_level >= 20:
            myPet.entratainiment_level = 20
    elif myPet.sleepy == True:
        print("I don't want to play now, I am tired :(")

    promptUser()



def gameChoice():
    print("what game do you want to play? A math game or blank")
    game_choice = input(">> ") 
    if game_choice == 'math game':
        for i in range(8):
            number1 = random.randint(1, 30)
            number2 = random.randint(1, 30)
            answer = (number1 + number2)    
            print("%d + %d = ?" %(number1, number2))
            player_answer = int(input(">> "))
            if player_answer == answer:
                print("congrats, you got it right")

            elif answer != player_answer:
                print("sorry, thats the wrong answer")
                break


def manageSleep():
    global playedTimes
    playedTimes += 1
    if playedTimes >= 5:
        playedTimes = 5
        print("I am tired, put me in bed please")

        myPet.sleepy = True


def checkStatus():
    print("name: %s " %myPet.petName)
    print("hunger: %d " %myPet.hungerLevel)
    print("happines: %d " %myPet.happinesLevel)
    print("sadnes: %d " %myPet.sadnessLevel)
    print("entratainiment level: %d " %myPet.entratainiment_level)
    print("is he tired: %s " %myPet.sleepy)
    print("is he dead: %s " %myPet.dead)
    promptUser()

def sleepPet():
    print("z")
    time.sleep(0.3)
    print("zZ")
    time.sleep(0.3)
    print("zZz")
    time.sleep(0.3)
    print("zZzZ")
    time.sleep(0.3)
    print("zZzZz")
    time.sleep(0.3)
    print("zZzZzZ")
    time.sleep(0.3)
    print("zZzZzZz")
    myPet.sleepy = False
    print("Good morning, I feel better already")
    promptUser()



def clearScreen():
    os.system("cls")
    promptUser()

def setupGame():
    print("hello, welcome to pymagochi, where you are going to raise your own virtual pet")
    print("what would you like to name it?")
    name = input(">>")
    myPet.petName = name
    print("%s is a great name for a pet" %myPet.petName)
    time.sleep(3)
    os.system("cls")
    promptUser()


titleScreen()
titleScreenOptions() 

Ответы [ 2 ]

0 голосов
/ 09 мая 2018

Чтобы отслеживать прошедшее время, вы можете сохранить значение time.time() для начального времени запуска. Если вы хотите получить количество прошедшего времени (в секундах), просто вычтите время начала из текущего времени следующим образом:

import time

start_time = time.time()
while True:
    input("Press enter to get the time elapsed.")
    elapsed_time = time.time() - start_time
    print(elapsed_time)
0 голосов
/ 09 мая 2018

Вы можете создать простой класс «Время», который будет поддерживать время для вас. Вот простой макет для вас:

class Time:
   def __init__(self):
       self.current_time=0

   def getTime(self):
       return self.current_time

   def Tick(self):
       self.current_time +=1


time= Time()
print(time.getTime())

# Increment time by 2
time.Tick()
time.Tick()
print(time.getTime())

РЕДАКТИРОВАТЬ: Это будет возможным решением, если вы хотите управлять временем самостоятельно, а не полагаться на системное время.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...