יש לי קוד פייתון תקול: 1. למה לאחר שאני עושה הרשמה או כניסה- מוחזרת לי שגיאה 500? 2. למה קובץ ה-JSON לא נוצר ולא שומר את המשתמש הנוכחי? ואם הוא כן שומר- שומר לי כל פעם רק על השחקן הנוכחי ודורס את כל השחקנים? 3. למה כשנשמרים שחקנים חדשים בקובץ ה-JSON הם נשמרים ללא הפרמטר של COUNT_WIN, וכתוצאה מכך נוצר לי אובייקט לא שלם? (אני חושבת שזה גורם להרבה שגיאות) 4. למה כשאני רוצה שחק לאחר הרשמה או כניסה עדיין מופיעה לי ההודעה שאני צריכה לעשות log_in? 5. מיד כשאני מריצה את הלקוח מופיעה לי השגיאה הבאה: הקובץ לא נמצא או שהוא ריק  — ניסיתי להכניס את הקובץ שלי מספר פעמים לבינה מלאכותית בשביל שתפתור לי את הבעיות, אך זה לא עזר. — אני מאד אשמח אם תוכלו לעזור לי. תודה מראש!  להלן הקוד שלי: class User:
    def __init__(self, userName, id, password, countWin=0, countTimes=0, words=None):
        self.userName = userName
        self.id = id
        self.password = password
        self.countTimes = countTimes
        self.words = words if words else set()
        self.countWin = countWin
    def __str__(self):
        return (f"userName: {self.userName}; id: {self.id}; password: {self.password};"
                f"countTimes: {self.countTimes}; words: {self.words}; countWin: {self.countWin};")   from flask import Flask, request, jsonify, abort, make_response, session
from flask_cors import CORS
from User import User
import json
import random
import os
import time
# תיעוד קוד
app = Flask(__name__)
CORS(app, supports_credentials=True)
usersFile = 'Users.json'
#  טעינת משתמשים מקובץ ה- JSON
def load_users():
    """Load users from the JSON file."""
    try:
        if not os.path.exists(usersFile) or os.path.getsize(usersFile) == 0:
            print("The file users.json is missing or empty.")
            return []
        with open(usersFile, 'r') as file:
            data = json.load(file)
            # !!! וידוא שמבנה הקובץ תקין !!!
            if not isinstance(data, list):
                print("Error: Invalid JSON structure in users.json.")
                return []
            print(data)
            return [User(**user) for user in data]  # קריאת ה-JSON והמרה לאובייקטים של משתמשים
    except FileNotFoundError:
        print("File not found. Initializing with an empty list.")
        return []
        # return {}
    except json.JSONDecodeError as e:  # כאן מודיעים על שגיאה עם קובץ JSON
        print(f"Error decoding JSON: {e}")
        return []
        # return {}
#  רשימת המשתמשים
users = load_users()
#  משתמש נוכחי
# currentUser: User = None
# global currentUser
currentUser = None
#  שמירת משתמשים לקובץ ה- JSON
@app.route('/save_users', methods=['POST'])
def save_users():
    """Save users to the JSON file."""
    try:
        with open(usersFile, 'w') as file:
            # json.dump([user.__dict__ for user in users], file)  # , ensure_ascii=False)
            # print(currentUser.__dict__)
            # print(currentUser.__dict__, file)
            print(users.__str__())
            json.dump([user.__dict__ for user in users], file, ensure_ascii=False,
                      indent=4)  # שמירת כל המשתמשים בקובץ בפורמט יפה
            print("Users saved successfully!")
            print(file.readlines())
    except Exception as e:
        print(f"Error saving users: {e}")
        abort(500)  # !!!!! שגיאה 500 עם הדפסת הסיבה
#  הרשמה
@app.route('/register', methods=['POST'])
def register():
    # data = request.json
    global currentUser
    currentUser = None
    # !!!! הוספת טיפול בשגיאות בעת גישה ל-JSON או session
    try:
        data = request.json
        # !!! בדיקה אם קלט לא תקין !!!
        if not data or 'userName' not in data or 'password' not in data:
            return jsonify({"message": "Invalid input data"}), 400
    except Exception as e:
        print(f"Error processing request: {e}")
        abort(500)
    users = load_users()
    # !!! בדיקה אם המשתמש כבר קיים !!!
    if any(user.userName == data['userName'] for user in users):
        return jsonify({"message": "User already exists."})
    _id = len(users) + 1
    new_user = User(data['userName'], _id, data['password'])
    print(new_user.__str__())
    response = make_response(jsonify({"message": "sign in successfully."}))
    response.set_cookie("userId", str(new_user.id), max_age=600, httponly=True, secure=False, samesite='None')
    session['userName'] = new_user.userName
    print(f"Hello {new_user.userName}")
    users.append(new_user)
    currentUser = new_user
    save_users()  # שמירת המשתמשים לאחר הוספת המשתמש החדש
    # global currentUser
    # print(f"Hello {data['userName']}")
    # return jsonify({"message": "User registered successfully."})
    return response
#  התחברות
@app.route('/logIn', methods=['POST'])
def logIn():
    # data = request.json
    # # userName = data['userName']
    # # password = data['password']
    # if not data.get('userName') or not data.get('password'):
    #     return jsonify({"message": "Invalid input data."})
    # !!!! ודא שהמשתנה 'currentUser' מאותחל בעת ההרשמה או הכניסה
    global currentUser
    currentUser = None
    # !!!! הוספת טיפול בשגיאות בעת גישה ל-JSON או session
    try:
        data = request.get_json()
        # !!! בדיקה אם קלט לא תקין !!!
        if not data or 'userName' not in data or 'password' not in data:
            return jsonify({"message": "Invalid input data"}), 400
    except Exception as e:
        print(f"Error processing request: {e}")
        abort(500)
    # userName = data.get('userName')
    # password = data.get('password')
    # for i in users:
    #     if i.userName == userName and i.password == password:
    #         response = make_response(jsonify({"message": "logIn successfully."}))
    #         response.set_cookie("userId", str(i.id), max_age=600, httponly=True, secure=False, samesite='None')
    #         session['userName'] = userName
    #         print(f"Hello {userName}")
    #         # global currentUser
    #         currentUser = i
    #         return response
    # return jsonify({"message": "You need to signIn."})
    # !!! בדיקת פרטי כניסה !!!
    for user in users:
        if user.userName == data['userName'] and user.password == data['password']:
            currentUser = user
            response = make_response(jsonify({"message": "logged in successfully."}))
            response.set_cookie("userId", str(user.id), max_age=600, httponly=True, secure=False, samesite='None')
            session['userName'] = user.userName
            print(f"Hello {user.userName}")
            return response
    return jsonify({"message": "Invalid username or password."})
# דקורטור לוודא שהמשתמש מחובר
def login_required(f):
    def decorated_function(*args, **kwargs):
        userId = request.cookies.get('userId')
        if not userId or not session.get('userName'):  # בדיקה אם המשתמש מחובר
            return jsonify({"message": "You didn't logIn or your playing time is over.\n You need to log in first."})
            # register()
        return f(*args, **kwargs)
    decorated_function.__name__ = f.__name__  # תיקון שם הפונקציה
    return decorated_function
#  רשימת המילים עבור המשחק
def load_words():
    try:
        with open('allWords.txt', 'r') as file:
            print(file.read().strip().split(','))
            return file.read().strip().split(',')
    except FileNotFoundError:
        return []
#  מהלך המשחק
@app.route('/play/<int:num>', methods=['POST'])
@login_required
def play(num):
    try:
        words = load_words()
        if not words:
            return jsonify({"message": "No words available."})
        random.shuffle(words)  # ערבוב המילים
        word = words[num % len(words)]
        return jsonify({"word": word, "length": len(word)})
    except Exception as e:
        # !!! טיפול בשגיאות במשחק !!!
        print(f"Error during game: {e}")
        abort(500)
# הסטורית משחקים
@app.route('/history', methods=['GET'])
@login_required
def history():
    userId = request.cookies.get('userId')
    user = next((u for u in users if str(u.id) == userId), None)
    if user:
        return jsonify({"message": f"You have played: {user.countTimes} games with words: {user.words.__str__()}, and "
                                   f"you won: {user.countWin} times"})
    return jsonify({"message": "User not found."})
# יציאה מהמשחק
@app.route('/logOut', methods=['POST'])
@login_required
def logOut():
    # session.pop('userName', None)
    # !!! ניקוי session בעת התנתקות !!!
    session.clear()
    return jsonify({"message": "Logged out successfully."})
if __name__ == '__main__':
    app.run(debug=True)  import json
from requests import session
import time
import Server
import User
basic_url = "http://127.0.0.1:5000"
# יצירת אובייקט session
sess = session()
usersFile= 'Users.json'
#  תפריט למשתמש
def menu():
    print("1. sign_in")
    print("2. log_in")
    print("3. game")
    print("4. history")
    print("5. exit")
# הרשמה
def register():
    global currentUser
    userName = input("Enter your name: ")
    password = input("Enter a password: ")
    response = sess.post(f"{basic_url}/register", json={'userName': userName, 'password': password})
    if response.status_code == 200:
        print(Server.users.__str__())
        print(response.text)
    elif response.status_code == 400:
        print(response.json()["message"])
    else:
        print(response.status_code)
# כניסה
def logIn():
    global currentUser
    userName = input("Enter your name: ")
    password = input("Enter a password: ")
    response = sess.post(f"{basic_url}/logIn", json={'userName': userName, 'password': password})
    if response.status_code == 200:
        print(Server.users.__str__())
        print(response.text)
    elif response.status_code == 401:
        print(response.json()["message"])
    else:
        print(response.status_code)
# שלבי ה'המן תלוי'
def draw_hangman(stage):
    stages = [
        "x-------x",
        "x-------x\n|\n|\n|\n|\n|",
        "x-------x\n|       |\n|\n|\n|",
        "x-------x\n|       |\n|       0\n|\n|",
        "x-------x\n|       |\n|       0\n|       |\n|",
        "x-------x\n|       |\n|       0\n|      \\|/\n|",
        "x-------x\n|       |\n|       0\n|      \\|/\n|      \\",
        "x-------x\n|       |\n|       0\n|      \\|/\n|      \\ /\n|"
    ]
    return stages[stage]
#  עדכון המשתמש בקובץ ה-JSON
def update_user(user):
    with open(usersFile, 'r') as file:
        # while True:
        #     u = file.readline()
        #     if u.userName == user.userName and u.password == user.password:
        #         u.replace('')
        #     file.__next__()
        users = json.load(file)
        for u in users:
            if u['userName'] == user.userName and u['password'] == user.password:
                u.update(user.__dict__)
            with open(usersFile, 'w') as f:  # שמירת כל המשתמשים בקובץ
                json.dump(users, f, ensure_ascii=False, indent=4)
#  מהלך המשחק
def play():
    num = int(input("Enter a number to start the game: "))
    response = sess.post(f"{basic_url}/play/{num}")
    if response.status_code != 200:
        print(response.json()["message"])  # הודעת שגיאה
        return
    data = response.json()
    if 'word' not in data:   # בדיקה אם המפתח 'word' לא קיים
        print("Error: " + data["message"])
        return
    word = data['word']
    length = data['length']
    print(word, length)
    # w=''
    # for i in len(word):
    #     w+='_'
    w = ['_' for _ in range(length)]
    # # w = '_' * response.json()['length']  # יצירת רשימה של _ לפי אורך המילה
    print(f"You need to guess this word: {w}")
    # print(f"You need to guess this word: {''.join(w)}")
    wrongGuesses = 0
    guessedLetters = []
    while wrongGuesses < 6 and '_' in w:
        guess = input("Enter a letter: ")
        if guess in guessedLetters:
            print("You've already guessed that letter.")
            continue
        guessedLetters.append(guess)
        if guess in word:
            print("Good guess!")
            # for i in len(w):
            #     if word[i] == guess:
            #         w['guess'] = guess
            for i in range(len(word)):
                if word[i] == guess:
                    w[i] = guess  # עדכון ה-guess במיקום הנכון
            print(w)
            # print(''.join(w))
        else:
            wrongGuesses += 1
            print(draw_hangman(wrongGuesses))
            print(f"There are only {6 - wrongGuesses} wrong times left")
    # for user in Server.users:
    #     if user.userName == Server.currentUser.userName and user.password == Server.currentUser.password:
    #         user.countTimes += 1
    #         if wrongGuesses != 6:
    #             user.countWin += 1
    # update_user(Server.currentUser)
    # sess.post(f"{basic_url}/save_users")
    if wrongGuesses != 6:
        Server.currentUser.countTimes+=1
        Server.currentUser.countWin+=1
    #     return {f"message": f"You won!. The word is: {word}"}
    # return {f"message": f"You lost! The word was: {word}"}
        print(f"You won! The word is: {word}")
    else:
        Server.currentUser.countTimes+=1
        print(f"You lost! The word was: {word}")
    update_user(Server.currentUser)
    sess.post(f"{basic_url}/save_users")
# הסטורית משתמש
def history():
    response = sess.get(f"{basic_url}/history")
    if response.status_code == 200:
        #     return response.json()["message"]
        # return response.json()["message"]
        print(response.json()["message"])
    else:
        print(response.json()["message"])
# יציאה מהמשחק
def logOut():
    response = sess.post(f"{basic_url}/logOut")
    print(response.text)
def main():
    while True:
        menu()
        choice = input("Choose an option: ")
        if choice == '1':
            register()
        elif choice == '2':
            logIn()
        elif choice == '3':
            play()
        elif choice == '4':
            history()
        elif choice == '5':
            logOut()
            break
        else:
            print("wrong choice")
            return
if __name__ == '__main__':
    main()  קובץ allWords.txt: apple, banana, tangerine, plum, orange,
cucumber, tomato, caret, date, grape,
melon, watermelon, squash, pepper,
eggplant, avocado, lemon, nectarine