Я запрограммировал игру, которая берет имя песни и исполнителя из внешнего файла. Программа печатает имя исполнителя, но маскирует название песни, и пользователь должен правильно угадать заголовок, чтобы заработать очки. Это работает отлично, но я хочу добавить ограничение по времени, поэтому у них есть только 60 секунд, чтобы получить максимальный результат, который они могут сделать.
Вот часть кода, на который я ссылаюсь:
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("
")
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("
")
score += 3
break
elif guesses == 2:
print ("(+1 point)")
print("
")
score += 1
break
else:
print("That's incorrect, guess again.
")
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 ("
")
pickSong_random()
Я пробовал играть с этой концепцией, но пока не повезло:
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!")
Всего 3 ответа
Оказывается, вы фактически переназначили модуль «время» на целое число 60, перезаписывая библиотеку, поэтому у него не было атрибута «.sleep ()». Также обратный отсчет не имеет значения и немного избыточен. В любом случае, этот отредактированный бит кода работал для меня:
import time
sec=60
while sec != 0:
print(sec)
sec = sec-1
time.sleep(1)
print ("You've ran out of time!")
Надеюсь это поможет!
Просто запишите время начала и перерыв от вашей петли, если время наступает. Спящий, вы делаете свою спящую программу, и пользователь ничего не может сделать. Таким образом, «быстрота» не имеет никакого значения, потому что вы не можете ничего делать, пока программа спит:
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
Хотя у Om Agarwal может быть возможное решение, вы также можете рассмотреть возможность использования неблокирующего подхода в своей игре с использованием встроенного времени pygame .
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
Ура!
Редактировать 1: Добавлена модификация примера.
import pygame
import time
import random
import sys
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("
")
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
start_ticks = pygame.time.get_ticks()
while guesses < 2:
guesses += 1
guess = input("[Guess]: ")
seconds = (pygame.time.get_ticks() - start_ticks) / 1000
if seconds > 60:
print("You've ran out of time!")
break
# 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("
")
score += 3
break
elif guesses == 2:
print("(+1 point)")
print("
")
score += 1
break
else:
print("That's incorrect, guess again.
")
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("
")
pickSong_random()