Python 3.6.0开发游戏登录注册系统 反复提示凭证错误陷入循环的问题
登录系统问题定位与修复
核心报错原因
- 遍历匹配逻辑完全错误:原代码逐行读取账号列表时,只要当前行的凭证和输入不匹配,就立刻触发错误提示、执行break终止循环。如果有效账号不是存储在users.txt的第一行,程序读完第一行不匹配就直接退出遍历,根本不会检查后面的账号行,自然永远提示"Incorrect credentials"。
- 变量赋值笔误:Player2的登录校验分支中,else块里错误地将状态变量写为
logged_in1 = False,没有对应修改为logged_in2,会造成登录状态判断紊乱。 - 隐性匹配失败隐患:原代码没有对用户输入、文件内读取的行做前后空格清理,只要用户输入时不小心带了前后空格、或者文件行末尾有多余空格,即使凭证完全正确也会匹配失败。
- 文件操作不规范:直接调用
open()方法没有手动关闭文件,Python 3.6环境下容易出现文件句柄泄漏、读取内容缓存不完整的问题。
修复后的可运行代码
abc = input("Enter 'n' if a player needs to make a new account, otherwise enter anything to login") new_users = False if abc == "n": while new_users == False: username = input("Please input a username ").strip() password = input("Please input a password ").strip() # 用上下文管理器操作文件,自动处理关闭逻辑 with open("users.txt","a") as file: file.write(f"{username} {password}\n") repeat = input("Enter 'n' to make another account, or type anything else to continue").strip() new_users = (repeat != "n") logged_in1 = False logged_in2 = False # 修复Player1登录逻辑 while not logged_in1: username = input("Please enter your username player 1").strip() password = input("Please enter your password player 1").strip() match_success = False # 一次性读取所有账号行,遍历全量做匹配 with open("users.txt","r") as f: all_lines = f.readlines() for line in all_lines: # 清理行的前后空白,跳过空行 clean_line = line.strip() if not clean_line: continue login_info = clean_line.split() if len(login_info) < 2: continue if username == login_info[0] and password == login_info[1]: print("Correct credentials!") logged_in1 = True match_success = True break # 全量遍历完仍未匹配,再提示错误 if not match_success: print("Incorrect credentials.") # 修复Player2登录逻辑 while not logged_in2: username = input("Please enter your username player 2").strip() password = input("Please enter your password player 2").strip() match_success = False with open("users.txt","r") as f: all_lines = f.readlines() for line in all_lines: clean_line = line.strip() if not clean_line: continue login_info = clean_line.split() if len(login_info) < 2: continue if username == login_info[0] and password == login_info[1]: print("Correct credentials!") logged_in2 = True match_success = True break if not match_success: print("Incorrect credentials.")
逻辑优化建议
- 注册环节增加重名校验:写入新账号前先遍历现有users.txt内容,如果目标用户名已存在,直接提示用户更换,避免重复账号造成登录混乱。
- 统一封装登录逻辑:Player1和Player2的登录校验逻辑完全重复,可以抽成一个接收“玩家编号”参数的独立函数,减少冗余代码,后续调整校验规则时只需要修改一处。
- 提升密码存储安全性:当前明文存储账号密码的方式非常容易泄露敏感信息,可以用Python内置的
hashlib模块对密码做散列处理后再存入文件,避免明文存储风险。 - 增加账号格式校验:用户名和密码不允许包含空格,否则会因为split()拆分逻辑破坏文件存储结构,可以在注册时增加输入规则校验,避免出现脏数据。
内容的提问来源于stack exchange,提问作者EXEO
相关产品推荐
相关产品推荐

