Simulate rolling dice in Python? - python

first time writing here.. I am writing a "dice rolling" program in python but I am stuck because can't make it to generate each time a random number
this is what i have so far
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8)
print("Roll or Quit(r or q)")
now each time that I enter r it will generate the same number over and over again. I just want to change it each time.
I would like it to change the number each time please help
I asked my professor but this is what he told me.. "I guess you have to figure out" I mean i wish i could and i have gone through my notes over and over again but i don't have anything on how to do it :-/
by the way this is how it show me the program
COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r
1
r
1
r
1
r
1
I would like to post an image but it won't let me
I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU

Simply use:
import random
dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)

import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8) # this only gets called once, so r is always one value
print("Roll or Quit(r or q)")
Your code has quite a few errors in it. This will only work once, as it is not in a loop.
The improved code:
from random import randint
computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
print('COP 1000') # q and r are initialized to avoid user error, see the bottom description
print("Let's play a game of Chicken!")
player_input = '' # this has to be initialized for the loop
while player_input != 'q':
player_input = raw_input("Roll or quit ('r' or 'q')")
if player_input == 'r':
roll = randint(1, 8)
print('Your roll is ' + str(roll))
# Whatever other code you want
# I'm not sure how you are calculating computer/player score, so you can add that in here
The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q, it would stop the loop, and go to the next part of the program. See: Python Loops --- Tutorials Point
The picky part about Python 3 (assuming that's what you are using) is the lack of raw_input. With input, whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input 'q' or 'r'. However, a way to avoid an user error (if the player inputs simply q or r, without the quotes) is to initialize those variables with such values.

Not sure what type of dice has 8 numbers, I used 6.
One way to do it is to use shuffle.
import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])
Each time and it would randomly shuffle the list and take the first one.

This is a python dice roller
It asks for a d(int) and returns a random number between 1 and (d(int)).
It returns the dice without the d, and then prints the random number. It can do 2d6 etc. It breaks if you type q or quit.
import random
import string
import re
from random import randint
def code_gate_3(str1):
if str1.startswith("d") and three == int:
return True
else:
return False
def code_gate_1(str1):
if str1.startswith(one):
return True
else:
return False
def code_gate_2(str2):
pattern = ("[0-9]*[d][0-9]+")
vvhile_loop = re.compile(pattern)
result = vvhile_loop.match(str1)
if result:
print ("correct_formatting")
else:
print ("incorrect_formattiing")
while True:
str1 = input("What dice would you like to roll? (Enter a d)")
one, partition_two, three = str1.partition("d")
pattern = ("[0-9]*[d][0-9]+")
if str1 == "quit" or str1 == "q":
break
elif str1.startswith("d") and three.isdigit():
print (random.randint(1, int(three)))
print (code_gate_2(str1))
elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
for _ in range(int(one)):
print (random.randint(1, int(three)
print (code_gate_2(str1))
elif (str1.isdigit()) != False:
break
else:
print (code_gate_2(str1))
print ("Would you like to roll another dice?")
print ("If not, type 'q' or 'quit'.")
print ("EXITING>>>___")

This is one of the easiest answer.
import random
def rolling_dice():
min_value = 1
max_value = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
print("Rolling dices...")
print("The values are...")
print(random.randint(min_value, max_value))
print(random.randint(min_value, max_value))
roll_again = input("Roll the dices again? ")
rolling_dice()

Related

How do I get the sum of the user input and a randomly generated number?

I've just started coding a month ago for school and we're currently finishing up our first project. I'm making a calculator of sorts that takes a user input(from 1-999), then generates a random number from 1-999, and then adds both together. Everything goes smoothly until it reaches the last few lines of code. Unfortunately, I can't quite get the final sum to show up in the console. I've tried so many things and I don't know what else to do anymore, just seems impossible.
Here's the code:
def click_circle(event):
if event.key == "e":
input_num = input("Type a number from 1 to 999. ")
print("Your number is " + str(input_num) + ".")
print("I will now choose a number at random from 1 to 999, and add them.")
final_random = random_number()
final_random
print("+")
final = int(input_num)
print(final)
print("Press R to add these two numbers.")
if event.key == "r":
print(sum(final, final_random))
add_key_down_handler(click_circle)
Any help would be appreciated.
thanks
I'm not too sure on what it's asking but I guess you can do this?
import random
def click_circle(event):
if event.key == "e":
input_num = int(input('Type a number from 1 to 999. '))
print(f'Your number is {input_num}.')
print('I will now choose a number at random from 1 to 999, and add them.')
final_random = random.randint(1,999)
print(input_num)
final_process = input('Press R to add these two numbers.')
if event.key == 'r':
print(str(input_num + final_random))
or you can simplify everything and just do
import random
input_num = int(input('Type a number from 1 to 999. '))
random_num = random.randint(1,999)
print(input_num + random_num)
Sum takes an iteratable (list). so either: use sum([final, final_random]) or just use print(final + final_random)

Problem with simple dice game using python

I'm new to python so I decided to make a simple dice game using a while loop just to do a simple test of myself. In the game, I use the module random and the method random.randint(1, 6) to print a random integer of any value from "1 to 6", which is evidently how a dice works in real life. But to make this a game, if the integer that is printed is even (random.randint(1, 6) % 2 ==0) then 'you win' is printed. If the integer is odd, then 'you lose' is printed. After this, the console asks if you want to roll the dice again, and if you say yes (not case sensitive hence .lower()) then it rolls again and the loop continues, but if you say anything else the loop breaks.
I thought this is was how it would work, but every now and then, when an even number is rolled, 'you lose' is printed, and the opposite for odd numbers, which is not what I thought I had coded my loop to do. Obviously I'm doing something wrong. Can anyone help?
This is my code:
import random
min = 1
max = 6
roll_again = True
while roll_again:
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
Those are two separate calls to randint(), likely producing two different numbers.
Instead, call randint() once and save the result, then use that one result in both places:
roll = random.randint(min, max)
print(roll)
if roll % 2 == 0:
print('you win')
You are generating a random number twice, the number printed isn't the same the number as the one you are checking in the if condition.
You can save the number generated in a variable like this to check if your code is working fine :
import random
min = 1
max = 6
roll_again = True
while roll_again:
number = random.randint(min, max)
print(number)
if number % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
You need to assign random number to a variable, right now printed and the other one are different numbers.
import random
min = 1
max = 6
dice = 0
while True:
dice = random.randint(min, max)
print(dice)
if dice % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
random.randint(min,max) returns different value every time it is executed. So, the best thing you can do is store the value at the very first execution and check on that stored value for Win or Loss.
You can try this version of code:
import random
while(True):
value = random.randint(1,6)
print(value)
if(value % 2 == 0):
print("You Win!")
else:
print("You Lose!")
again = input("Want to roll Again? Type 'Yes' or 'No'")
if(again.lower() != 'yes'):
break

What can I do to fix my simple computer-player game code? Syntax Error

I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break

Python Roll dice with 2 parameters: Number of sides of the dice and the number of dice

This is the problem I have: Write a function roll dice that takes in 2 parameters - the number of sides of the die, and the number of dice
to roll - and generates random roll values for each die rolled. Print out each roll and then return the string
“That’s all!” An example output
>>>roll_dice(6,3)
4
1
6
That's all!
This is the code I have so far using a normal roll dice code:
import random
min = 1
max = 6
roll_dice = "yes"
while roll_dice == "yes":
print random.randint(min,max)
print random.randint(min,max)
print "That's all"
import sys
sys.exit(0)
Try this:
def roll_dice(sides, rolls):
for _ in range(rolls):
print random.randint(1, sides)
print 'That\s all'
This uses a for loop to loop rolls amount of times and prints a random number between 1 and sides each loop.
import random
def roll_dice(attempts,number_of_sides):
for i in range(attempts):
print(random.randint(1, number_of_sides))
print("thats all")
In a more advanced, you can have two parameters where you ask the users input to set the values and it will run the functions and give the numbers rolled, the sum and ask if the user wants to try again.
#Import 'random' module
import random
def main():
#Get values from user to determine slides_per_dice and number_of_die.
sides_per_die = get_value(1,50, 'How many sides should the dice to have
(1-50): ', 'That is not a correct response, enter a value between 1 and
50')
number_of_dice = get_value(1,10, 'How many dice should be rolled (1-10):
', 'That is not a correct response, enter a value between 1 and 10')
#Simulate rolling specified number of dice with specified sides on each
dice.
outcome = rolling_dice (sides_per_die, number_of_dice)
#Asking user if they would like to roll again.
roll_again = input("Would you like to play again (y/n): ") .lower()
while roll_again != 'n':
if roll_again =='y':
main()
else:
print('Error: please enter "y" or "n".')
roll_again = input("Would you like to play again (y/n): ")
#Final message if user ends the game.
print('Thanks for playing.')
#Asking user for side_per_dice and number_of_nice input.
def get_value(lower_limit, upper_limit, prompt, error_message):
number = int(input(prompt))
while number < lower_limit or number > upper_limit:
print(error_message)
number = int(input(prompt))
return number
#Determining the outcome of the rolls and summing up total for all rolls.
def rolling_dice (sides_per_die, number_of_die):
roll_sum = 0
print('Rolling dice .....')
for roll in range (number_of_die):
result = random.randint(1, sides_per_die)
roll_sum += result
print(result, end = " ")
print(f'\nThe sum of all dice rolled is {roll_sum}')
main()

Loop never seems to actually loop

print("Welcome to my dice game.")
print("First enter how many sides you would like your dice to have, 4, 6 or 12")
print("Then this program will randomly roll the dice and show a number")
#Introduction explaing what the game will do. Test 1 to see if it worked.
while True:
#starts a while loop so the user can roll the dice as many times as they find necessary
import random
#Imports the random function so the code will be able to randomly select a number
dice = int(input("Enter which dice you would to use,4, 6, or 12? "))
#set a variable for the amount of dice number
if dice == 12:
x = random.randint(1,12)
print("You picked a 12 sided dice. You rolled a " + str(x) + " well done")
#Test 2 see if it does pick a random number for a 12 sided di
elif dice == 6:
x = random.randint(1,6)
print("You picked a 6 sided dice. You rolled a " + str(x) + " well done")
#Test 3 see if it does pick a random number for a 6 sided di
elif dice == 4:
x = random.randint(1,4)
print("You picked a 4 sided dice. You rolled a " + str(x) + " well done")
#Test 4 see if it does pick a random number for a 4 sided di
else:
print("Sorry, pick either 12, 6 or 4")
#Test 5 tells the user that they can only pick 4, 6 or 12 if anything else is entered this error shows
rollAgain = input ("Roll Again? ")
if rollAgain == "no":
rollAgain = False
if rollAgain == "yes":
rollAgain = True
break
print ("Thank you for playing")
#if the user enters anything apart from yes y or Yes. The code ends here.
That is the code i have so far. However the code will never actually go to the beginning of the loop, no matter what i enter the code just displays "Thanks for playing" and ends. Can anyone please tell me where i have went wrong?
First, you should be using raw_input to get the user's selection. (assuming python 2) If you're using python 3 then input is fine and keep reading.
Anyway, it'll still quit when you type yes because you break out of the loop! You should move the break statement into the "no" case so it breaks out when you say you do not want to roll again.
rollAgain = raw_input ("Roll Again? ")
if rollAgain == "no":
break
You don't need to set rollAgain to true or false at all. With the above code, anything other than "no" is assumed to be "yes" but you can add checks for that easily.
The problem is that you break your loop when the user wants to roll the dice again. The loop should break when the player doesn't want to play again so you have to do :
http://pastebin.com/hzC1UwDM

Categories

Resources