Как создать плавающую переменную в Python? - PullRequest
0 голосов
/ 31 октября 2019

Привет, я пытаюсь выполнить мой курс по информатике, который предназначен для проверки моих способностей (одна из них, которую я выбрал, была игра в кости. Нам разрешено использовать ресурсы, поэтому я пришел сюда, и мне нужна помощь, когда яЯ должен создать систему подсчета очков, но мне нужно, чтобы она менялась с круглыми числами, чтобы в нее можно было добавлять переменные для получения окончательного результата. Любая помощь будет отличной! Я приложил свой код ниже:

import time
import random
def totalScore(n,s):

 file = open("total.txt", "a")
 file.write("name: " + n + ", total: " + str(s) + "\n")
 file.close()
 return

def login():
    while True:
        print("")
        username = input('What is your username? ')
        password = input('What is your password? ')
        if username not in ('User1', 'User2'):
            print("")
            print('Incorrect username, try again')
        if password != 'password':
            print("")
            print('Incorrect password, try again')
            continue
        print("")
        print(f'Welcome, {username} you have been successfully logged in.')
        break
user1 = login()
user2 = login()
print("")
print("")
time.sleep(0.5)
print("               Rules")
print("               -----")
time.sleep(1)
print("• The points rolled on each player’s dice are added to their score.")
time.sleep(2)
print("• If the final total is an even number, an additional 10 points are added to their score.")
time.sleep(2)
print("• If the final total is an odd number, 5 points are subtracted from their score.")
time.sleep(2)
print("• If they roll a double, they get to roll one extra die and get the number of points rolled added to their score.")
time.sleep(2)
print("• The score of a player cannot go below 0 at any point.")
time.sleep(2)
print("• The person with the highest score at the end of the 5 rounds wins.")
time.sleep(2)
print("• If both players have the same score at the end of the 5 rounds, they each roll 1 die and whoever gets the highest score wins (this repeats until someone wins).")
time.sleep(2)
print("")
print("")

round_number = 0
msg = "Press Enter to Start The Round:\n\n"
while True:
    if input(msg).lower() != '':
        continue

    round_number += 1
    print(f"Round Number {round_number}\n")

    print("User1 goes first : ")
    roll_number = 0
    dice3 = 0
    print("")
    msg = "Press Enter to Roll The Dice: \n\n"
    while True:
        if input(msg).lower() != '':
           continue

        roll_number = 1
        dice1 = random.randint(1, 6)
        print(f"1> You got a {dice1}\n")
        input ("Press Enter to Roll Again!")
        roll_number = 2
        dice2 = random.randint(1, 6)
        print(f"2> You got a {dice2}\n")
        if roll_number == 2:
            break
    print("You have used both of your rolls")
    total = dice1 + dice2
    print("your total for this round is " + str(total) + ".")

    if dice1 == dice2:
        input ("Lucky!, you get an additional roll : ")
        roll_number = 3
        dice3 = random.randint(1, 6)
        print(f"Bonus Role> You got a {dice3}\n")
        total = total + dice3
        print("your final total for this round is " + str(total) + ".")

    print("User2 its your turn now : ")
    roll_number = 0
    dice3 = 0
    print("")
    msg = "Press Enter to Roll The Dice: \n\n"
    while True:
        if input(msg).lower() != '':
           continue

        roll_number = 1
        dice1 = random.randint(1, 6)
        print(f"1> You got a {dice1}\n")
        input ("Press Enter to Roll Again!")
        roll_number = 2
        dice2 = random.randint(1, 6)
        print(f"2> You got a {dice2}\n")
        if roll_number == 2:
            break
    print("You have used both of your rolls")
    total = dice1 + dice2
    print("your total for this round is " + str(total) + ".")

    if dice1 == dice2:
        input ("Lucky!, you get an additional roll : ")
        roll_number = 3
        dice3 = random.randint(1, 6)
        print(f"Bonus Role> You got a {dice3}\n")
        total = total + dice3
        print("your final total for this round is " + str(total) + ".")

    msg = "Press Enter to Start a new round! \n"
    round_number
    if round_number == 5:
        break
print("All the rounds are complete")

1 Ответ

0 голосов
/ 31 октября 2019

Вы должны написать читаемый код с некоторыми функциями, комментариями и т. Д. ... для вашей оценки, я сделал комментарии в этом коде ниже, чтобы помочь вам завершить эту игру, но прежде чем добавлять оценку, не торопитесь, чтобы прочитать этот код.

import random

def calculate_score(score, total):
    """ this function return updated score """
    # add total to score
    # if total is even add 10 points to score
    # if total is odd substract 5 points to score
    # if score is positive return score
    # else return 0
    return 0

def read_enter(msg="Press Enter"):
    """ this function block user and force him to press enter"""
    while input(msg).lower() != '':
       continue

def roll_dice(msg=""):
    """ this function return a random number dice"""
    dice = random.randint(1, 6)
    print(msg, end="")
    print(f"> You got a {dice}\n")
    return dice

def player_turn(message="It's your turn : ", score=0):
    """ this function is a player turn, that return the updated score """
    print(message,"\n")
    msg = "Press Enter to Roll The Dice: \n\n"

    read_enter(msg)
    dice1 = roll_dice("1")
    read_enter("Press Enter to Roll Again!")
    dice2 = roll_dice("2")

    print("You have used both of your rolls")
    total = dice1 + dice2
    print("your total for this round is " + str(total) + ".")
    # to update score
    updated_score = calculate_score(score, total)
    dice3 = 0
    if dice1 == dice2:
        input("Lucky!, you get an additional roll : ")
        dice3 = roll_dice("Bonus Role")
        total = total + dice3
        print("your final total for this round is " + str(total) + ".")
    # return the updated score added with dice3
    return updated_score + dice3

def dice_game():
    """ the main function game """
    msg = "Press Enter to Start The Round:\n\n"
    score_user1 = score_user2 = 0
    for round_number in range(5):
        read_enter(msg)
        print("Round Number ", (round_number+1), "\n")
        # you can print scores to keep players updated with theirs scores
        score_user1 = player_turn("User1 goes first : ", score_user1)
        score_user2 = player_turn("User2 its your turn now : ", score_user2)

        msg = "Press Enter to Start a new round! \n"
    print("All the rounds are complete")
    # while both players have the same score
        # roll 1 die for player 1 and update score
        # roll 1 die for player 2 and update score
        # if they have same die number
            # continue
        # else break
    # annonce the winner
    pass

def main():
    dice_game()

if __name__ == '__main__':
    main()
...