如何为游戏设置时间限制?

时间:2018-11-23 23:33:03

标签: python timer

我编写了一款游戏,该游戏从外部文件中提取歌曲和歌手的名字。该程序会打印歌手姓名,但会掩盖歌曲的标题,用户必须正确猜测标题才能获得积分。效果很好,但我想添加一个时间限制,因此他们只有60秒的时间来获得可能的最高分。

这是我引用的代码的一部分:

import numpy as np
np.set_printoptions(threshold=np.nan)

我尝试过尝试这个概念,但到目前为止还没有运气:

def pickSong_random():
  score=0
  lives=5
  songFile = open("F_Songs.txt","r")
  songList = songFile.readlines() #Reads from the bridged file
  songFile.close()
  while True:
    chosenSong = random.choice(songList)

    chosenSong = chosenSong.strip("\n")
    artistAndSong = chosenSong.split(":") #Defines song split

    toDisplay = ""
    toDisplay += artistAndSong[0] + ": "
    songTitleWords = artistAndSong[1].split(" ")

    for word in songTitleWords:
      #loop through
      toDisplay += word[0] + " "
    print(toDisplay)
    #print("2" +toDisplay)
    toDisplay = toDisplay.strip("None")
    guesses = 0
    while guesses <2:
        guesses += 1
        guess = input("[Guess]: ")

        #Guess checking
        if guess.lower() == artistAndSong[1].lower():
            print("Correct! The song was " + artistAndSong[1] + " by " + artistAndSong[0])
            print("It took you", guesses, "guess(es)!")
            if guesses == 1:
                print ("(+3 points)")
                print("\n")
                score += 3
                break
            elif guesses == 2:
                print ("(+1 point)")
                print("\n")
                score += 1
                break
        else:
            print("That's incorrect, guess again.\n")
            lives = lives-1
        if lives == 0:
          print ("You have no more lives to continue! Your score was:",score)
          time.sleep(3)
          slow_print ("Would you like to play again?")
          playAgain = input("[Y/N]: ")
          if playAgain == ("n") or playAgain == ("N"):
            sys.exit()
          if playAgain == ("Y") or playAgain == ("y"):
            print ("Your last score was",score,", lets see if you can beat it this time...")
            time.sleep(1)
            print ("\n")
            pickSong_random()

更新1 我的项目代码现在已经发生了很大变化

import time
countdown=True
time=60
while countdown == True:
    time = time-1
    time.sleep(1.0)
    print (time)
    countdown=True
    if time == 0:
        print ("You've ran out of time!")

4 个答案:

答案 0 :(得分:0)

事实证明,您实际上是在将“时间”模块重新分配为60的整数,从而覆盖了库,这就是为什么它没有属性“ .sleep()”的原因。倒数计时部分也无关紧要并且有点多余。无论如何,这段经过修改的代码对我有用:

import time
sec=60
while sec != 0:            
    print(sec)
    sec = sec-1
    time.sleep(1)
print ("You've ran out of time!")

希望这会有所帮助!

答案 1 :(得分:0)

仅记录开始时间,如果时间到了,则从循环中中断。通过睡眠,您可以使程序进入休眠状态,并且用户无法执行任何操作。因此,“牢度”没有任何区别,因为程序休眠时您什么也不能做:

import random 
import datetime
correct = 0
start = datetime.datetime.now()
while True:
    print("Math test. Add , dont screw up, you got {}s left".
          format(20-(datetime.datetime.now()-start).seconds)) 
    a,b = random.choices(range(1,20),k=2)
    c = input("  {:>2} + {:>2} = ".format(a,b))

    if (datetime.datetime.now()-start).seconds > 20:
        print("Times up. Score: {}".format(correct))
        break
    try: 
        if a+b == int(c): 
            correct += 1
            print("Correct")
        else:
            print("Wrong")
    except:
        print("Wrong")

输出:

Math test. Add , dont screw up, you got 20s left
  17 +  8 = 23
Wrong
Math test. Add , dont screw up, you got 18s left
  10 +  2 = 12
Correct
Math test. Add , dont screw up, you got 14s left
   1 +  7 = 8
Correct
Math test. Add , dont screw up, you got 12s left
   5 + 19 = 24
Correct
Math test. Add , dont screw up, you got 8s left
   4 +  3 = 7
Correct
Math test. Add , dont screw up, you got 5s left
   3 + 18 = 21
Correct
Math test. Add , dont screw up, you got 3s left
  15 + 12 = 27
Correct
Math test. Add , dont screw up, you got 1s left
   7 +  8 = 15
Times up. Score: 6 

答案 2 :(得分:0)

尽管Om Agarwal可能有解决方案,但您可能还想考虑在游戏中使用built-in pygame time使用非阻塞方法。

loadUserByOAuthUserResponse

干杯!

编辑1:添加了示例修改。

start_ticks = pygame.time.get_ticks()
while guesses < 2:
    # OTHER GAME CODE HERE
    seconds = (pygame.time.get_ticks() - start_ticks) / 1000
    if seconds > 60:
        print ("You've ran out of time!")
        break

答案 3 :(得分:0)

这是我在评论中建议的threading.Timer()类的解决方法。可以将它们配置为延迟指定的时间,并根据您的选择选择呼叫。

在下面的代码中,我定义了一个名为timeout()的回调函数和一个名为time_ran_out的全局变量,当计时器到期时,它将设置为True。添加的代码中有注释,说明正在做什么。回调函数所做的全部工作就是设置变量的值。 pickSong_random()函数中的其他代码检查此变量的值,以确定是否调用了回调函数。

Timer实例(以及它们回调的函数)的好处是,它们的执行与运行游戏本身的主线程并行在后台进行,因此使用它们不会影响游戏的运行。执行或代码。

请注意,我还对您的代码进行了重新格式化,使其遵循PEP 8 - Style Guide for Python Code指南,因此我认为它更具可读性(并且更容易处理)。

import random
import sys
import time
from threading import Timer

TIMELIMIT = 10.0  # Seconds (set low for testing).


def slow_print(s):
    for c in s:
        sys.stdout.write('%s' % c)
        sys.stdout.flush()
        time.sleep(0.03)


def pickSong_random():
    # Local Timer callback function.
    def timeout():
        nonlocal time_ran_out  # Reference variable defined in enclosing scope
                               # (so a local one isn't created automatically).
        time_ran_out = True

    score = 0
    lives = 5
    songFile = open("F_Songs.txt", "r")
    songList = songFile.readlines() # Reads from the bridged file
    songFile.close()

    while True:
        chosenSong = random.choice(songList)
        chosenSong = chosenSong.strip("\n")
        artistAndSong = chosenSong.split(":") # Defines song split

        toDisplay = ""
        toDisplay += artistAndSong[0] + ": "
        songTitleWords = artistAndSong[1].split(" ")

        for word in songTitleWords:
            # loop through
            toDisplay += word[0] + " "
        print(toDisplay)
        # print("2" +toDisplay)
        toDisplay = toDisplay.strip("None")

        guesses = 0
        timer = Timer(TIMELIMIT, timeout)  # Create a timer thread object.
        time_ran_out = False  # Define local variable the callback function modifies.

        timer.start()  # Start the background timer.
        while guesses < 2:
            if time_ran_out:
                print('Times up!')
                break

            guesses += 1
            guess = input("[Enter your guess]: ")

            # Guess checking
            if guess.lower() == artistAndSong[1].lower():
                print("✓Correct! The song was " + artistAndSong[1]
                        + " by " + artistAndSong[0])
                print("It took you", guesses, "guess(es)!")
                if guesses == 1:
                    print("\n")
                    print("↑(+3 points)↑")
                    print("\n")
                    score += 3
                    break
                elif guesses == 2:
                    print("\n")
                    print("↑(+1 point)↑")
                    print("\n")
                    score += 1
                    break
            else:
                print("╳The song name isn't", guess, "\n")
                lives = lives-1
                if guesses == 2:
                    print("Sorry, you couldn't guess the song.")
                    print("\n")
            if lives == 0:
                print("You have no more lives to continue! Your score was:", score)
                time.sleep(3)
                print("\n")
                slow_print("Would you like to play again?")
                playAgain = input("\n[Y/N]: ")
                if playAgain == ("n") or playAgain == ("N"):
                    print("\n")
                    # user variable is not saved from the login system as it is
                    # defined as a function separately
                    user = str(input("Enter a name to save your highscore: "))
                    file = open ("H_Highscore.txt", "a")
                    file.write(user)
                    file.write(",")
                    file.write(str(score)) # (int(x)) can not be written
                    file.write("pts")
                    file.write("\n")
                    file.close()
                    time.sleep(0.5)
                    leaderboard()
                    sys.exit()
                if playAgain == ("Y") or playAgain == ("y"):
                    print("Your last score was", score,", lets see if you can beat it this time...")
                    time.sleep(1)
                    print("\n")
                    pickSong_random()

if __name__ == '__main__':
    pickSong_random()