I'm making a dice roller for the game Heroscape (So we can play with offshore friends). The dice for heroscape have 6 sides. 3 sides show skulls, 1 side has a symbol and 2 sides have a shield.
I've made it randomly generate 1 of those sides, but i'd like it to list off the results at the end (i.e. You rolled 6 skulls, 2 symbols and 4 shields).
Heres my current code:
loop = 1
while loop == 1:
diceChoose = raw_input('Pick your dice. (Press 1 for a D20 roll, and 2 for attack /defense dice.) ')
if diceChoose == ('1'):
import random
for x in range(1):
print random.randint(1,21),
print
raw_input("YOUR DICE ROLL(S) HAVE COMPLETED. PRESS ANY KEY TO CONTINUE.")
elif diceChoose == ('2'):
diceNo = int(raw_input('How many dice do you need? '))
testvar = 0
diceRoll = ['skull', 'skull', 'skull', 'symbol', 'shield', 'shield']
from random import choice
while testvar != diceNo:
print choice(diceRoll)
testvar = testvar + 1
if testvar == diceNo:
print ('YOUR DICE ROLLS HAVE COMPLETED')
raw_input("PRESS ANY KEY TO CONTINUE.")
else: loop = raw_input('Type 1 or 2. Nothing else will work. Press 1 to start the program again.')
What i've tried is a bunch of if statements, but i've realised that if I try print ('diceRoll') all I get is the whole array instead of the randomly selected dice roll.
I'm not sure how to save each diceRoll as it happens, so I can print that number later on.
(My thinking is something like
if diceRoll == 'skull' skullNo +1
print('skullNo'))
I think a good data structure for you to use for this problem would be the Counter from the collections module in the standard library. It works a little like a dictionary, mapping objects to an integer count. However, you can add values to it and that will increment their count.
So, I'd do this:
from random import choice
from collections import Counter
diceNo = int(raw_input('How many dice do you need? '))
diceValues = ['skull', 'skull', 'skull', 'symbol', 'shield', 'shield']
counter = Counter()
counter.update(choice(diceValues) for _ in range(diceNo))
print("Rolls:")
for value, count in counter.items():
print("{}: {}".format(value, count))
print ('YOUR DICE ROLLS HAVE COMPLETED')
raw_input("PRESS ANY KEY TO CONTINUE.")
The key line is counter.update(choice(diceValues) for _ in range(diceNo)). This calls counter.update with a "generator expression", which produces diceNo random roll results. If you haven't learned about generator expressions yet, I suggest checking them out, as they can come in really handy.
Welcome to SO. I changed a few parts of your code to make them more similar to my style - feel free to change them back if that helps.
Change your loop code to simply:
while True:
This accomplishes the same thing, except that it is more pythonic.
Then, tab in one and tell set number values for the skull, symbol and shield. In this case, we set it to 0.
skull = 0
symbol = 0
shield = 0
Next, change the code below the diceNo = int(raw_input('How many dice do you need? ')) to this. It should be indented by one.
for x in xrange(diceNo):
import random
choice = random.randint(1,6)
if choice == 1:
skull +=1
elif choice == 2:
skull +=1
elif choice == 3:
skull +=1
elif choice == 4:
symbol =+ 1
elif choice == 5:
shield += 1
elif choice == 6:
shield += 1
This code repeats for the number of dice rolls needed. I then adds 1 to the variable associated with that name.
Directly below that, we display the info to the user.
print "You rolled %d skulls, %d symbols, and %d shields. Congrats." % (skull, symbol, shield)
Since you seemed to be having issues with the code, I decided to post it in its entirety.
while True:
#Here we set the variables
skull = 0
symbol = 0
shield = 0
diceChoose = raw_input('Pick your dice. (Press 1 for a D20 roll, and 2 for attack / defense dice.) ')
if diceChoose == '1':
import random
for x in range(1):
print random.randint(1,21),
print
raw_input("YOUR DICE ROLL(S) HAVE COMPLETED. PRESS ANY KEY TO CONTINUE.")
elif diceChoose == '2':
diceNo = int(raw_input('How many dice do you need? '))
for x in xrange(diceNo):
import random
choice = random.randint(1,6)
if choice == 1:
skull +=1
elif choice == 2:
skull +=1
elif choice == 3:
skull +=1
elif choice == 4:
symbol =+ 1
elif choice == 5:
shield += 1
elif choice == 6:
shield += 1
print "You rolled %d skulls, %d symbols, and %d shields. Congrats." % (skull, symbol, shield)
raw_input("PRESS ANY KEY TO CONTINUE.")
else: loop = raw_input('Type 1 or 2. Nothing else will work. Press 1 to start the program again.')
Related
It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))
P1Roundx=int (0)
P2Roundx=int(0)
P1Scorex=int(0)
P2Scorex=int(0)
P1Total=int(0)
P2Total=int(0)
number=int(0)
P1R1=int(0)
P2R1=int(0)
P1R2=int(0)
P2R2=int(0)
import time
Username=input("what is player 1’s username")
Username=str(Username)
if Username == ("1"):
print ("hello",Username,)
elif Username == ("2"):
print ("welcome",Username,)
else:
print("LEAVE!")
exit()
# This module determines if player 1 is authenticated or if they are not. If they are not they are forced to exit the programme
Username2=input("what is player 2's username")
Username2=str(Username2)
if Username2 == ("2"):
print ("hello,",Username2,)
elif Username2 == ("1"):
print ("welcome",Username2,)
else:
print("LEAVE!")
exit()
# This module determines if player 2 is authenticated or not and exits the programme if they are not
import random
P1R1= random.randint(1,6)
P1R1=("Your first roll is",P1R1)
P1R2=random.randint(1,6)
P1R2=("Your second roll is",P1R2)
print("Your total is",P1R1+P1R2)
P1total=P1R1+P1R2
if P1Total % 2 == 0:
P1Total=(P1Total)+P1R1
else:
P1Total=(P1Total)-5+P1R1+P1R2
print("Player 1's total score is",P1Total)
import random
P2R1= random.randint(1,6)
P2R1=("Your first roll is",P2R1)
P2R2=random.randint(1,6)
P2R2=("Your second roll is",P2R2)
print("Your total is",P2R1+P2R2)
P2total=P2R1+P2R2
if P2Total % 2 == 0:
P2Total=(P2Total)+ P2R1+P2R2
else:
P2Total=(P2Total)-5+P2R1
print("Player 2's total score is",P2Total)
time.sleep(6)
as an error, but I don't understand where the var + int is. I need help.
BTW IM NOT VERY GOOD AT THIS SNAKEY TING
When your code does this
P1R1= random.randint(1,6)
P1R1 is a number between 1 and 6; let's imagine it is 4. But then the code does
P1R1=("Your first roll is",P1R1)
It appears your intent is to print this out as a message. But what it actually does is change the value of P1R1 to the tuple ("Your first roll is",4). Then your code carries on as if P1R1 still had the value 4 because it does addition on it.
If you look at the output of this line:
print("Your total is",P1R1+P1R2)
you will see that it is
Your total is ('Your first roll is', 4, 'Your second roll is', 1)
when it is clear that you are expecting
Your total is 5
It should be easy for you to see why the code goes wrong after that.
hi remove the below lines which are assigning tuple to P1R1 and P2R2
P1R1=("Your first roll is",P1R1)
P2R2=("Your second roll is",P2R2)
There seems to be an error in restarting the program, it does not restart properly. It asks if you want to play again then asks for name of players tells you the goal then restarts by itself.
import random, time
#Variables
die1 = 0
die2 = 0
goal = 0
tries1 = 0
tries2 = 0
sum = 0
sum2 = 0
choice = "y"
while choice == "y":
#Asking for the player's names
player1 = input("What is your name, player1?")
player2 = input("What is your name, player2?")
#The "goal"
goal = random.randrange(5) + 1
print("The goal is:", goal)
#First while loop for the first die rolled by the first player
while die1 != goal:
die1 = random.randrange(5) + 1
time.sleep(1)
print(player1, "Your roll is:", die1)
tries1 = tries1 + 1
sum = sum + die1
time.sleep(1.5)
print("Your sum is:", sum)
#Second while loop for the second die rolled by the second player
while die2 != goal:
die2 = random.randrange(5) + 1
time.sleep(1)
print(player2, "Your roll is:", die2)
tries2 = tries2 + 1
sum2 = sum2 + die2
time.sleep(1.5)
print("Your sum is:", sum2)
time.sleep(2)
#The statement at the end of the game
print("\n\n""Player", "\t\t", "Goal", "\t\t", "# of Rolls","\t\t", "Sum of Rolls", "\n", player1, "\t\t", goal, "\t\t", tries1,"\t\t\t", sum, "\n", player2, "\t\t", goal, "\t\t", tries2, "\t\t\t", sum2)
choice = input("Would you like to play again?: (y) or (n)")
goal = 0
tries1 = 0
tries2 = 0
sum = 0
sum2 = 0
break
It's probably because at the end of the program you are breaking out of the main while loop no matter what. You should surround it with an if statement using the choice variable. Also The Last Statement is inline with the while for when the second player rolls therefore it will be executed in that loop. To fix that you going to need to reduce the indentation so it is executed at the end of the game. Also the tries1 variable is indented out a space so python will probably throw some form of syntax error at that as well.
In place of your break statement, put:
if choice != 'y':
break
This will cause the outer while loop to go back to the beginning if the user has typed 'y'. Otherwise you'll break out of the loop and the script will exit.
Move ALL the variable declarations from die1 through sum2 inside the while loop; otherwise they won't get initialized for the replay.
So far, I've had a few bumps in the road, but I've been able to correct them, though my programming is quite sloppy as I've just started Python. The idea is to create a dice game called "Pig." The idea is that a user can roll or hold each turn and each subsequent roll adds to the players pot, though if you roll a 1 it's a bust and your pot is reset. Here is my program so far:
import random
die = random.randint(1,6)
R = (die)
r = (die)
H = (0)
h = (0)
User_Score = 0
Computer_Score = 0
pot1 = 0
pot2 = 0
User = input('Hello! Enter your name:')
Computer = 'AI'
if roll_again is 1:
return take_turn(User)
elif roll_again is 0:
take_turn(Computer)
print (User,"'s pot: ",pot1)
print (Computer,"'s pot: ",pot2)
if pot1 >= 50:
User_Score += 1
if pot2 >= 50:
Computer_Score += 1
def roll_die(random):
numbers = [0]*6
for n in range (1,6):
die = random.randint (1,6)
numbers = n
return numbers
def take_turn(User):
print ("It is your turn",User, input("Hit Enter to continue.")
if input == True
(roll_die(random))
if die == int(1)
(pot1) is 0 and print("Die: 1 Pot: Bust! 0")
else:
print ("Die:",die, "Pot:",pot1)
(pot1) =+ die
(R,r,H,h) is raw_input ("(R)oll again or (H)old?")
if input is(R,r)
(roll_again) is 1
else input is (H,h)
(roll_again) is 0
print (User,"'s pot: ",pot1)
print (Computer,"'s pot: ",pot2)
else
return take_turn(User)
take_turn(User)
take_turn(Computer)
I seem to have a syntax error around the line 40 (I'm not sure exactly which line). Which is "if die == int(1)". I'm sure there are plenty of errors after that which I can solve on my own time, but getting past this roadblock would really be helpful! Thanks in advance.
There is no closing parenthesis at the end of line 38.
print ("It is your turn",User, input("Hit Enter to continue.")
This might be the error
I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.