gpt4 book ai didi

python - 如何设定游戏时间限制?

转载 作者:太空宇宙 更新时间:2023-11-03 21:32:22 24 4
gpt4 key购买 nike

我编写了一个游戏,它从外部文件中获取歌曲和艺术家姓名。该程序打印艺术家姓名,但掩盖歌曲的标题,用户必须正确猜出标题才能获得积分。这很好用,但我想添加一个时间限制,这样他们只有 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("\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()

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

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!")

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

#Casey_Neale
import sys
import random
import time
import math
import csv
import time, sys
newaccounts=True
loggedIn=False
yn=True

def tutorial(): #Games introduction
slow_print("Your aim is to get as many points as possible...")
print("\n")
time.sleep(1.5)
slow_print("You need to guess the name of each song to gain points...")
print("\n")
time.sleep(1.5)
slow_print("You have two guesses for each song...")
print("\n")
time.sleep(1.5)
slow_print ("The artist name is provided for you...")
time.sleep(0.5)
print("\n")

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

def leaderboard():
print ("\n")
print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
f = open('H_Highscore.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
for i in leaderboard:
print(i)
f.close()
time.sleep(10)
sys.exit()

def loginsys():
doublecheck=True
while doublecheck == True:
verifyRegister = input ("➡Welcome | Are you a registered user?\n[Y/N]: ")
print (" ")
if verifyRegister == "n" or verifyRegister == "N": #If the user is not already registered
if newaccounts == True:
loop=True
while loop == True:
username = input ("Please enter a username\n[User]: ")#Prompts the user to provide a desired username
print (" ")#Prompts for username
checkusername = input ("Please retype your username\n[Verify]: ")#Verifys username
print (" ")#Prompts to verify username
if checkusername != username:
print ("Invalid, please try again")
loop=True
else:
loop=False
time.sleep(0.5)
passloop=True
while passloop == True:
password = input ("Please enter a password\n[Password]: ") #Prompts the user to provide a desired password
print (" ")#Prompts for password
checkpassword = input ("Please retype your password\n[Verify]: ") #Verifys password
print (" ")#Prompts to verify password
if checkpassword != password:
print ("Invalid, please try again")
print (" ")
passloop=True
else:
passloop=False
file = open("C_AccountData.txt","a") #Opens the file C_AccountData.txt in write mode/opens connection
file.write("USRN:") #Prefix Username to make the file easier to read
file.write(username) #Writes the username
file.write("|") #Partition for visual ease to make the file easier to read
file.write("PSWD:") #Prefix Password to make the file easier to read
file.write(password)#Writes the password
file.write("\n") #New line to make the file easier to read
file.close() #Closes file/ends connection
print ("✓Your account has been created") #Verifies that the account has been made to the user
time.sleep(2)
print ("\n")
doublecheck=True #Loop

if verifyRegister == "Y" or verifyRegister == "y":
loop=True
if loop == True:
user = input("[User]: ")
passw = input("[Password]: ")
f = open("C_AccountData.txt", "r")
for line in f.readlines():
uspwd = line.split("|")
us = uspwd[0]
pw = uspwd[1]
if (user in us) and (passw in pw):
loop=False
print("Login successful, welcome",user)
doublecheck=False
else:
if loop == True:
print ("\n")
print ("Sorry, your account details were not recognised. ")

else:
if verifyRegister != "Y" or verifyRegister != "y" or verifyRegister != "N" or verifyRegister != "n" or verifyRegister !="backup":
print("\n")
doublecheck=True

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("[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 = str(input("Enter a name to save your highscore: ")) #user variable is not saved from the login system as it is defined as a function separately
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()
loginsys() #LOGIN PROTOCOL
time.sleep(3)
print("\n")
tutorial() #TUTORIAL PROTOCOL
slow_print ("Prepare yourself! The game will begin in...\n")
time.sleep(0.5)
print("\n")
slow_print("5...")
time.sleep(0.5)
print("\n")
slow_print("4...")
time.sleep(0.5)
print("\n")
slow_print ("3...")
time.sleep(0.5)
print("\n")
slow_print ("2...")
time.sleep(0.5)
print("\n")
slow_print ("1...")
time.sleep(0.5)
print("\n")

pickSong_random() #GAME PROTOCOL
sys.exit() #EXIT PROTOCOL

最佳答案

以下是如何使用 threading.Timer() 执行此操作我在评论中建议的类(class)。这些可以配置为延迟指定的时间和您选择的函数的调用。

在下面的代码中,我定义了一个名为 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()

关于python - 如何设定游戏时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53453887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com