How to assign points in a simple game - python

I am making a simple game, at the beginning you can choose the amount of players, which is between 2 and 5 (shown below) I am having problem with assigning the initial amount of points, which is 100 points. Also, not sure where to place the code regarding the points in my woring code below.
When I start working on the game, after each dice moevent the score would increase.
players_list= []
max_players= 5
max_players = int(input(" Please, insert the number of players? : "))
while (max_players <2) or (max_players > 5) :
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
players_list = []
while len(players_list) < max_players:
player1 = input(" Enter your first and last name? : ")
players_list.append(player1)
print("Players in the game : ")
print(players_list)
Should I change the players list into a dictionary?
The code with the score system that does not work
score=100
players_list= []
max_players= 5
max_players = int(input(" Please, insert the number of players? : "))
while (max_players <2) or (max_players > 5) :
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
players_list = []
while len(players_list) < max_players:
player1 = input(" Enter your first and last name? : ")
players_list.append(player1)
print("Players in the game : ")
players_list.appened (players)= { score:100}
print(players_list)
print(score)

I'd recommend to use dictionary where keys are player names (assuming player names will be unique) and values will be player's score:
players_dict = {}
score = 100
max_players = -1
while not (2 <= max_players <= 5):
max_players = int(input("Please, insert the number of players: "))
while len(players_dict) < max_players:
player = input("Enter your first and last name: ")
if player in players_dict:
print(f"Player {player} already exists, choose another name")
else:
players_dict[player] = score
print(players_dict)
Prints (for example):
Please, insert the number of players: 1
Please, insert the number of players: 3
Enter your first and last name: John
Enter your first and last name: Adam
Enter your first and last name: John
Player John already exists, choose another name
Enter your first and last name: Lucy
{'John': 100, 'Adam': 100, 'Lucy': 100}

No you don't need to change the list into a dictionary. Rather you probably want to have a list of dictionaries.
TLDR;
I'm not sure if I understand your problem, cause the description is vague tbh.
There's no need to use the input before the while loop.
The user can input something what cannot be parsed into an int, so I'd wrap it into try...except block.
"player_list" is redefined
in the 2nd loop it's not player1, it's the "next" player I guess
you can also keep name and surname in a single string and then skip the split
one way or another it would make sense to keep your player as a dict
Consider renaming players_list to players, typically you don't add the name of the data structure to the variable name
Code:
score=100
players_list= []
max_players= 0
while (max_players <2) or (max_players > 5) :
try:
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
except Exception as e:
print(f"Invalid input: {e}")
while len(players_list) < max_players:
name, surname = input(" Enter your first and last name? : ").split(" ")
player = {"name": name, "surname": surname, "points": score}
players_list.append(player)
print(f"Players in the game : {players_list}")

Related

How to get an integer value in a list if user inputs the corresponding string value?

I want the user to select a string value from a list and the quantity of that string they want.
Using those two factors, I want to multiply the the amount of the item they chose with the value of that item and add that to their balance.
import random
from math import fsum
item_val = {
"Common": 10,
"Uncommon": 25,
"Rare": 50,
"Epic": 100,
"Legendary": 250,
"Exotic": 500,
}
def item_trading():
balance = []
init_bal = random.randint(10, 500)
balance.append(init_bal)
print(f"Your starting balance is: {balance}. ")
while True:
which_item = input("Which item would you like to purchase?: ")
which_item = str(which_item)
if which_item not in item_val:
print("That item doesn not exist. Please try again. ")
continue
else:
print(f"You want to purchase {which_item} rarity of items. ")
num_of_items = input(f"How many {which_item} items would you like to purchase?: ")
num_of_items = int(num_of_items)
print(f"You have purchased {num_of_items} {which_item} items! ")
for rarity,val in item_val.items():
balance.append(-(num_of_items)*(val))
print(f"You current balance is: {fsum(balance)} ")
break
break
item_trading()
However, "balance.append(-(num_of_items)*(val))" only uses the first value ("Common" value) which is 10, so even if the user selected a "Rare" value (50) it only multiplies by 10.
How would I go about doing this? Thanks in advance!
You don't need to loop over item_vals.items(), just use item_vals[which_item]
init_bal = random.randint(10, 500)
balance = [init_bal]
def item_trading():
print(f"Your starting balance is: {balance}. ")
which_item = input("Which item would you like to purchase?: ")
which_item = str(which_item)
if which_item not in item_val:
print("That item doesn not exist. Please try again. ")
continue
print(f"You want to purchase {which_item} rarity of items. ")
num_of_items = input(f"How many {which_item} items would you like to purchase?: ")
num_of_items = int(num_of_items)
print(f"You have purchased {num_of_items} {which_item} items! ")
balance.append(-num_of_items * item_vals[which_item]
print(f"Your current balance is: {fsum(balance)} "
break
item_trading()
Also, the initialization of the balance list should not be in the function. If it's in the function, you reset the balance every time you call the function, instead of keeping a running balance.

For loop inside while loop in asking user input with conditions

I am writing a python game and it has following features to ask from user.
it can be up to 4 players (minimum 1 player, maximum 4 player)
It will ask players name. If the name is already exists, the program will prompt "name already in the list" and ask to enter the name again
if the player enters empty string in player name input, it will exits.
it will ask how many n number of random digits player want to play with (randint(start, stop) is used). only up to 3 digits are allowed
I know I have to user while loop for indefinitely ask the user input until the condition is satisfied. I also have to use for loop to ask users for a name based on the input at point 1.
Following is my attempt which has errors. Hence, need your help in review -
def attempt1():
playerList = []
numPlayers = input("How Many Players? ")
if int(numPlayers) < 5 and int(numPlayers) > 0:
while True:
if numPlayers != "":
for i in range(int(numPlayers)):
playerName = input("Player name or <Enter> to end ")
if playerName != "":
if playerName not in playerList:
playerList.append(playerName)
break
else:
print("Player Name Cannot be empty")
# numPlayers = input("How Many Players? ")
else:
print("There must be at least one player")
numPlayers = input("How Many Players? ")
else:
print("Invalid number of players. Please enter 1 - 4")
print(playerList)
def attempt2(numPlayers):
playerList = list()
# numPlayers = 1
i = 0
while i < 4:
for x in range(0,numPlayers):
playerName = input("Name ")
if playerName not in playerList:
playerList.append(playerName)
i += 1
else:
print("Name is already in the list")
print(playerList)
return playerList
This solves my issue. Please kindly suggest if you have better solutions. I am sure my code here is messy but it works for now.
def askPlayerName(numPlayers):
playerList = []
x = numPlayers
while True:
if x > 0:
for i in range(x):
print(x)
playerName = input("Enter name: ")
if playerName not in playerList:
x -= 1
playerList.append(playerName)
break
else:
print("ELSE")
x = numPlayers - len(playerList)
print(x)
print("name aldy in the list")
else:
return playerList
return playerList

Can't figure out this For loop in Python

I'm trying to get this For loop to repeat itself for an amount equal to "totalNumStudents"
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
However, the code never gets to this loop and restarts from the beginning.
Here is the first half of the code including the loop.
freshman = 0
sophomore = 0
junior = 0
senior = 0
test_score = 0
totalTestScores = 0
totalNumStudents = freshman + sophomore + junior + senior
# Start a while loop.
while True:
# Display the menu of choices.
print("\nPress '1' to enter a student")
print("Press '2' to quit the program")
print("NOTE: Pressing 2 will calculate your inputs.\n")
# Prompt to enter a choice.
choice = input("Enter your choice: ")
# If the choice is 1.
if choice == '1':
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
# Otherwise, display an error message.
else:
print("Invalid test score! Test score " +
"must be between 0 and 100.")
# Calculate total test scores
totalTestScores = totalTestScores + test_score
What am I missing here?
Since you add up before get those numbers, your totalNumStudents is all always zero. You should put the add up statement after you get the numbers:
...
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
# add up here
totalNumStudents = freshman + sophomore + junior + senior
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
...
BTW since your while True loop only runs once, you don't need the loop. Just remove it.

Fixing invalid syntax errors in try and except

When I use this code, my aim is to try and make sure that any input will not break the code like letters or numbers not between 0-3. But when i use this code the whole list isn't coming up. How would i fix this?
The output should look like this
Hello Megan the four games avaliable are:
0 Mario Cart
1 Minecraft
2 Angry Birds
3 Grabd Theft Auto
What number game do you want? h
Please choose a valid number
What number game do you want? 23
Please choose a number between 0 and 3
What number game do you want? 1
You have chosen Minecraft
Instead, the output is
Hello the four games avaliable are:
0 Mario Cart
What number game do you want? 2
1 Minecraft
What number game do you want? h
Please enter a valid value
The code i am using is:
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
try:
gametype = int(input("What number game do you want? "))
while gametype <0 or gametype >3:
print (" Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a valid value " )
return gametype
game ()
I have also tried another way, using 'while True' before 'try' but the program says that is an invalid syntax.
SECOND TRY
I have used this new code, but again it won't let me run the code as it says I have an invalid syntax when I put While True, with True highlighted in red.
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
while True:
try:
gametype = int(input("What number game do you want? "))
if 0 <= gametype <= 3 :
return game
print ("Please enter a value between 0 and 3 ")
except ValueError:
print ("Please enter whole number from 0 to 3 " )
return game
game ()
I think you want something like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
for gamenum, gamename in enumerate(gamelist):
print(gamenum, ":", gamename)
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
demo output
What's your name? Megan
Hello, Megan, the four available games are:
0 : Mario Cart
1 : Minecraft
2 : Angry Birds
3 : Grand Theft Auto
What number game do you want? 4
Please enter a value between 0 and 3
What number game do you want? Minecraft
Please enter a whole number from 0 to 3
What number game do you want? 2
You chose Angry Birds
The main change I made to your code is to put the try.. except stuff inside a while True block, so we keep asking for input until we get something valid. I also used enumerate to print each game with its number. That's neater than your while gamecount < 4: loop.
If you have to print the list of games using a while loop then you can do it like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
gamenum = 0
while gamenum < len(gamelist):
print(gamenum, ":", gamelist[gamenum])
gamenum += 1
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
I made gamelist a global list so we can access it outside the game function. We don't need to use the global statement in the function because we aren't changing gamelist. In general, you should avoid using the global statement.

My code is breaking out of my for loop

so I've been working on this code for a little bit just to test my abilities and I've run into a brick wall. For some reason my code is breaking out of my for loop. If I say I want to see how much 2 rooms cost it goes through the first one fine but them asks me how many rooms I want to check again. If I input 2 again, it will go through it once and then go on through the rest of the code normally. I have two for loops setup the exact same as each other but for some reason one works and the other doesn't. I'm probably making a stupid mistake but I've been trying to fix it for ages now but no cigar. Appreciate all help!
def start():
print ("Welcome to Caroline's Painting and Decorating cost estimator")
print ("Here you can see an estimate to see how much the job will cost")
print ("First though, you have to enter a few details about the job")
customerNumber = input ("Please enter your customer number ")
dateofEstimate = input ("Please enter the current date ")
def roomCalculator():
surfaceAreaCost = 0
totalPrice = 0
price = 0
count = 0
rooms = int(input("Please enter the number of rooms that require painting "))
for i in range(0, rooms):
roomName = input ("What room needs decorating? ")
wallsNumber = int(input("How many walls are in the room? "))
wallpaper = input ("Is there any wallpaper thats needs to be removed? Enter Y for yes and N for no ")
if wallpaper == "Y".lower():
surfaceAreaCost + 70
for i in range(0, wallsNumber):
count = count + 1
print ("Please enter the dimensions for wall", count)
height = int(input("How high is the wall? "))
width = int(input("How long is the wall? "))
surfaceAreaWall = height*width
wallCost = surfaceAreaWall * 15
price = surfaceAreaCost + wallCost
employeeType = input ("What employee would you like? Enter AP for apprentice or FQ for Fully-Qualified ")
if employeeType == "AP".lower():
price = price + 100
print ("You are having an apprentice do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
elif employeeType == "FQ".lower():
price = price + 250
print ("You are having a Fully-Qualified employee to do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
Your error is a result of nested for loops, because you use variable i in both. This causes an error since you change value of variable i in first for loop with second for loop. Rename variable in second for loop with j for instance.
Thanks all for the help! It was a stupid error on my part. I used 3.4.4 at my school computer and 3.5.1 at home. It all worked anyway.

Categories

Resources