How to detect certain numbers from a dice roller? - python

I have made a text-based RPG that uses dice rolling for the combat system. If you get a 1, your attack is forfeited. You can keep rolling until you get a one, or type 'attack'. I made a dice roller, and I just want to know, how to make it detect if the roll is 2 through 6. Here is the code:
print ("Type roll to roll the dice")
rollKeeper = ("1")
while rollKeeper == ("1"):
rollOn = input ( )
if rollOn == ("roll"):
import random
def rollDice():
damage = random.randint(1,6)
damage = random.randint (1,6)
print (damage)
So I want to get it do detect numbers 2 through 6, and that's it. I know about
if damage == ("1"):
but that is already part of my game. I just need to be able to detect if it is any of the others (up to 6).

Roll it into a function, since it's reusable.
import random
def roll_die():
return random.randint(1,6)
then just test.
result = roll_die()
if result == 1:
# forfeit attack however you're doing that
else: # roll between 2-6
# do whatever your game logic has you doing.

Try adding:
if 2 <= damage <= 6:
#insert code here

Related

How do I make this dice game run in a simulation 10,000 times using python?

I'm doing a homework assignment. I can't seem to find a solution on how to make the dice roll 10,000 times plus create a variable that updates everytime you win some money when you roll the dice correctly. I have some instructions on the homework below can anyone shed some light on me?
The game is played as follows: roll a six sided die.
If you roll a 1, 2 or a 3, the game is over.
If you roll a 4, 5, or 6, you win that many dollars ($4, $5, or $6), and then roll again.
With each additional roll, you have the chance to win more money, or you might roll a game-ending 1, 2, or 3, at which time the game is over and you keep whatever winnings you have accumulated.
Use the randint function from Python's Random module to get a die roll result
(see functions for integers).
Run 10,000 simulations of the game (Monte Carlo method).
Print the average amount won and the largest amount won.
Just as a thought experiment, would you pay $3 for a chance to play this game?
Example Output:
Average amount won = x.xx
Max amount won = xx
import random
class diceGame:
def __init__(self,dice):
self.dice = dice
def gameOutCome(self):
askUser = str(input("Roll to play the game? Y/N: "))
while True:
if askUser == 'y':
print(self.dice)
if self.dice == 1:
print("Sorry, Try Again!")
elif self.dice == 2:
print("Sorry, Try Again!")
elif self.dice == 3:
print("Sorry, Try Again!")
elif self.dice == 4:
print("You win $4")
elif self.dice == 5:
print("You win $5")
elif self.dice == 6:
print("You win $6")
askUser = str(input("Roll to play the game? Y/N: "))
x = random.randint(1,6)
dd = diceGame(x)
dd.gameOutCome()
Welcome to stackoverflow. Since this is your homework, I don't think it is appropriate to post an entire solution here.
However I do think some pointers in the right direction might be helpful:
1) You are running the simulation 10000 times. Each roll requires 2 user inputs. So in order to finish the simulation you need at least 20000 user inputs... Yeah that will be tiresome ;) .... So lets cut the user input - just write a function that executes the game until the game is finished. Once you have a function that executes one game, how can you execute it multiple times?
2) Think of each roll having two possible outcomes - continue the game or not. What des it mean to continue? What condition has to be fullfilled for the game to end?
3) Once the game has ended, what do you need to do with the money?
4) You can use the sum and max functions to calculate the average and the maximum win.
import random
def play_game():
#The function that executes the game - you have to write that on your own
pass
wins = [play_game() for i in range(0,10000)]
win_average = sum(wins)/10000.0
max_win = max(wins)

How to assign a score to a player and accordingly add/remove points from their score during a player's turn

In this game I've been tasked to do, one part of it is where all players in the game start off with 0 points, and must work their way to achieve 100 points, which is earned through dice rolls. After player decides to stop rolling, each player's score is displayed. My problem is that I don't know how to individually assign each player a "Score" variable, in relation to how many players are playing initially, so for e.g.
Player 1: Rolls a 2 and a 5
Player 1 score = +25
and etc. for every other player
Essentially, I need help on how to check if for example user at the start inputs that 3 players are playing, 3 different variables will be assigned to each player that contains their scores, which will change as the game progresses.
I have no idea what the proper code should actually contain, hence why I'm looking for help
import random
playerList = []
count = 0
def rollTurn():
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print("Your first dice rolled a: {}".format(dice1))
print("Your second dice rolled a: {}".format(dice2))
print("-------------------------MAIN MENU-------------------------")
print("1. Play a game \n2. See the Rules \n3. Exit")
print("-------------------------MAIN MENU-------------------------")
userAsk = int(input("Enter number of choice"))
if userAsk == 1:
userNun=int(input("Number of players?\n> "))
while len(playerList) != userNun:
userNames=input("Please input name of player number {}/{}\n> ".format(len(playerList)+1, userNun))
playerList.append(userNames)
random.shuffle(playerList)
print("Randomizing list..:",playerList)
print("It's your turn:" , random.choice(playerList))
rollTurn()
while count < 900000:
rollAgain=input("Would you like to roll again?")
if rollAgain == "Yes":
count = count + 1
rollTurn()
elif rollAgain == "No":
print("You decided to skip")
break
I would like that during a player's turn, after rolling their dices, the value of those two rolled dices are added to that individual's score, and from there, a scoreboard will display showcasing all the players' in the lobby current scores, and will continue on to the next player, where the same thing happens.
instead of using a list for playerList, you should use a dict:
playerList = {}
playerList['my_name'] = {
"score": 0
}
You can iterate on the keys in the dict if you need to get data. For example in Python3:
for player, obj in playerList.items():
print(player, obj['score'])
And for adding data its a similar process:
playerList['my_name']['score'] = playerList['my_name']['score'] + 10

using function and random numbers

I have a question:
When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it.
This is what I have done so far:
import random
x = random.randint(1,6)
print("You roll a die ", x)
new_try = input("\n\n Do you want to roll a die again?")
if str(new_try) == 'yes':
print("You roll a die ", x)
else:
print("Cool game!")
I am still getting same numbers :(
You aren't changing x the second time, and merely printing it out again, giving the same result. Here is the code for a fixed version:
import random
x = random.randint(1, 6)
print("You roll a die", x)
new_try = input("\n\n Do you want to roll again? ")
if new_try == 'yes':
x = random.randint(1, 6)
print("You roll a die", x)
else:
print("Cool game!")
If you want to use a function for it, you can do it over multiple times:
import random
def roll_dice():
x = random.randint(1, 6)
print("Dice was rolled: " + str(x))
try_again = input("Do you want to try again? ")
if try_again == 'yes':
roll_dice()
roll_dice()
I reckon what you can do is set a different seed each time you run a new try.
x is not the diceroll, that is random.randint(1,6). So after x = random.randint(1,6), x stores the result of a single diceroll which happened earlier, and available to provide that single result any time in the future. So x stores a number, not the fact that it should be generated randomly.
If you want a function for rolling a dice, that would be def for first attempts:
def diceroll():
return random.randint(1,6)
having this function, any subsequent print(diceroll()) (note that it is a function call, diceroll()) would print the result of a different roll (and results could be equal only by coincidence). Or, you could again store the result of a single diceroll as x=diceroll(), so it could be re-used multiple times in the future (let's say you want to compare it to the user's guess and also print it)
Side note: technically you can store functions in variables too, x=diceroll would store the function, so x would not be a number, but the act of rolling the dice, and would have to be called as a function, like print(x()).
If you want to produce different numbers at different times, you have to use a seed value. Here is an example to explain:
import random
random.seed( 3 )
print "Random number with seed 3 :", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()
I will not make the program for you. I have explained you the concept. Now just implement it.

Game of Pig - can't figure out how to loop through all the players

I have figured out most of the problem but can't seem to figure out how to loop through each of the players to let them play the game. This is the code I have so far. I think that my while loop in the main() function is wrong but I don't know what to do to fix it. Let me know if you can point me in the right direction. I also need to figure out how to end the turn if you roll a 1.
import random
def instructions():
print ("==================================================")
print ("\nWelcome to the Game of Pig. To win, be the")
print ("player with the most points at the end of the")
print ("game. The game ends at the end of a round where")
print ("at least one player has 100 or more points.\n")
print ("On each turn, you may roll the die as many times")
print ("as you like to obtain more points. However, if")
print ("you roll a 1, your turn is over, and you do not")
print ("obtain any points that turn.\n")
def num_players():
while True:
players = raw_input("How many players will be playing? ")
if players.isdigit():
return int(players)
else:
print "\nPlease enter a valid number of players.\n"
def name_players(players):
count = 1
list_of_players = []
for i in range(players):
name = raw_input("Enter the name for Player {}: ".format(count))
list_of_players.append(name)
count += 1
print ""
return list_of_players
def start_game(list_of_players):
points = 0
for player in list_of_players:
print "{0} has {1} points.".format(player, points)
print ("==================================================\n")
s = input("How many sides of the dice do you want? ")
for player in list_of_players:
print ("\n{0}'s turn:").format(player)
answer = raw_input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s)
if roll > 1:
points += roll
print "{0} has {1} points.".format(player, points)
answer = raw_input("Press y to roll the dice?")
def main():
instructions()
players = num_players()
list_of_players = name_players(players)
start_game(list_of_players)
if __name__ == "__main__":
main()
The problem you encountered is due to the local variable, points, in function start_game. All your players are sharing the same variable to keep tracking their score. Therefore, once, your first player reaches/passes 100 points, the game logic will move to the second player. However, the points variable is still keeping the score from the previous player (which is more than or equal to 100). Because of that, the following players will never get chance to get into while loop.
You should declare points vriable for each players OR reset points variable every time when points variable holds value is greater than or equal to 100.
def start_game(list_of_players):
points = 0 #<----------------- points is local variable to the function
for player in list_of_players:
print("{0} has {1} points.".format(player, points))
print ("==================================================\n")
s = int(input("How many sides of the dice do you want? ")) ###
# validate value of s?
for player in list_of_players:
### the variables declared in for loop is unique to each player
print ("\n{0}'s turn:".format(player))
answer = input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s + 1, 1) ### randrange
if roll > 1:
points += roll
print("{0} has {1} points.".format(player, points))
answer = input("Press y to roll the dice?")
PS. I'm running your code with Python 3.6.1.
Furthermore, one more thing you need to take care of is that for random.randrange(start, stop, step). The output will not include the value of stop. e.g. random.randrange(0, 10, 1) will generate integers from 0 to 9 inclusive. Therefore, if a player chose 6 sides of dice, that means the random number range should be from 1 to 6. In this way, you need to increment whatever number player entered.
e.g. 6 sides of dice
either random.randrange(0, 6+1, 1) or random.randrange(6+1) should work.

python: if statement, not responding properly to value from dice roll

so i have been working on a input based dungeon game in python that is fairly rudimentary. I wanted to put a dice roll condition in the game and decide if a player will die or live on a path. However my if statement will not properly respond to the roll in the number generator i have in the program, it will print the number and then carry on whether or not the condition was met. How can i fix this, and why is this happening?
if direction == 1:
import random
from random import *
num = 6
def d6(num):
rolls = []
for x in range(num):
rolls.append(randint(1,6))
return rolls
rolls = d6(1)
print rolls
if rolls is 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
elif rolls is not 3:
print "you are back at the start which way will you go?\n"
path3 =float(input("forward, or right?"))
is and is not are reserved for special comparisons in python. You need == and !=. Also you can change it to a simple if/else instead of if/elif with no else. Also, it looks like your d6 function returns a list instead of a single number. Try adjusting that to return a single number instead:
from random import randint
def d6():
return randint(1,6)
rolls = d6()
if rolls == 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
else:
print "you are back at the start which way will you go?\n"

Categories