中途重开的一次对话
(每道题开头都有同一段游戏核心:new_round 开一局、parse 校验输入、judge 比大小、step 记一次猜测、score 算分。秘密固定是 73。)
session 管一整次运行:处理 q、r、非法、结束后再猜。秘密依次 73、18。看这串输入的回应和记录:
LIMIT = 7
def new_round(secret):
return {"secret": secret, "tries": 0, "low": 1, "high": 100, "over": False, "won": False}
def parse(line):
s = line.strip()
if s in ("q", "r"):
return s
if not s.isdigit():
return None
n = int(s)
if n < 1 or n > 100:
return None
return n
def judge(secret, n):
if n > secret:
return "大了"
if n < secret:
return "小了"
return "对了"
def step(st, n):
st["tries"] += 1
r = judge(st["secret"], n)
if r == "大了" and n - 1 < st["high"]:
st["high"] = n - 1
if r == "小了" and n + 1 > st["low"]:
st["low"] = n + 1
if r == "对了":
st["won"] = True
if st["won"] or st["tries"] >= LIMIT:
st["over"] = True
return r
def score(st):
return LIMIT + 1 - st["tries"] if st["won"] else 0
def play(secret, lines):
st = new_round(secret)
out = []
for line in lines:
if st["over"]:
break
n = parse(line)
if n is None:
out.append("无效")
continue
if n == "q":
out.append("退出")
break
out.append(step(st, n))
return st, out
def record(rec, st):
rec["rounds"] += 1
if st["won"]:
rec["wins"] += 1
s = score(st)
rec["total"] += s
if s > rec["best"]:
rec["best"] = s
return s
def session(secrets, lines):
rec = {"rounds": 0, "wins": 0, "total": 0, "best": 0}
k = 0
st = new_round(secrets[0])
out = []
for line in lines:
n = parse(line)
if n is None:
out.append("无效")
continue
if n == "q":
out.append("退出")
break
if n == "r":
k = (k + 1) % len(secrets)
st = new_round(secrets[k])
out.append("重开")
continue
if st["over"]:
out.append("本局已结束")
continue
out.append(step(st, n))
if st["over"]:
record(rec, st)
return rec, out
SECRETS = [73, 18]
LINES = ["50", "r", "50", "25", "12", "18", "q"]
rec, out = session(SECRETS, LINES)
print(",".join(out) + "/" + str(rec["rounds"]) + "/" + str(rec["total"]))
全部评论