我想在我的代碼上添加一個評分系統。玩家每答對一次,總分會加5分。這是我下面的代碼:
def easyLevel():
n = 2
while n <= 7:
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern " " random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
easyAns = str(input("What was the pattern?: "))
if easyAns == pattern:
n = n 1
print("That's correct!")
else:
print("Sorry, that's incorrect.")
break
如何將分數保存在檔案中?以及玩家正確回答的最后一個模式。
另外,有沒有辦法可以在這個函式之外列印模式和得分?如果是這樣,我該怎么做?
感謝您的幫助。謝謝!
uj5u.com熱心網友回復:
如果你使用一個全域變數來存盤分數呢?
import random
import string
score = 0 # set the global variable score to 0
def easyLevel():
global score #this tells python that when we assign to score in this function, we want to change the global one, not the local one
n = 2
while n <= 7:
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern " " random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
easyAns = str(input("What was the pattern?: "))
if easyAns == pattern:
n = n 1
print("That's correct!")
score = score 5 # so when we change score in here, it changes the global variable score
else:
print("Sorry, that's incorrect.")
break
另一種方法是將分數用作區域變數,并在完成后回傳。然而,這不會否定在某些能力上對全域分數變數的需要。
以下是來自 Stack 的更多資訊: 在函式中使用全域變數
快樂編碼!
uj5u.com熱心網友回復:
添加一個變數來存盤分數,然后在回圈之后,將最后一個模式和分數保存到csv檔案中
import random
import string
import csv
def easyLevel():
n = 2
score = 0
last_pattern = None
# start game
while n <= 7:
# make new pattern
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern " " random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
# get input
easyAns = input("What was the pattern?: ")
if easyAns == pattern:
n = 1
score = 5
print("That's correct!")
# update last pattern
last_pattern = pattern
else:
print("Sorry, that's incorrect.")
break
return last_pattern, score
game = easyLevel() # returns last_pattern and score
last_pattern, score = game
# show result
print("Last pattern :", last_pattern, ", Score :", score)
# save score and last pattern in file
with open('data.csv', 'a') as file:
csv_wrtier = csv.writer(file)
csv_wrtier.writerow([last_pattern, score])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490626.html
