python dice rolling restart script - python

i want to restart my script automatically i have a dice rolling script and i don't want to have to reset my script manually between each roll this is my script.
import random
from random import randrange
from random import randint
r = randint
min = 1
max = 6
rolls = int(float(input('how menny times do you want to roll:')))
for x in range(rolls):
print ('Rolling the dices...')
print ('The value is....')
print (r(min, max))
i have tried a few ways to do it but none of them worked

I'm not 100% sure what you were actually trying to do, but here is a program that I wrote that will roll 2 die at a time, and will generate however many rolls you would like to roll. -not the best practice to use recursive (main calls main from within itself), but it's not really an issue with something this basic.
*replace raw_input with input if you are using Python 3+. I use 2.7 so I use raw_input
import time
import random
def roll_multiple():
#honestly this is all you need to do what you want to do, the rest just turns it into a game and allows multiple runs
roll_number = int(raw_input("How Many Times Would You Like to Roll?\n"))
for i in range(roll_number):
print"You Rolled A ", random.randrange(1,6,1), " and a ", random.randrange(1,6,1)
#that's it! if you do these 3 lines, it will ask for how many times, and for each item in range of roll_number (whatever you input) it will run the print below and generate new numbers for each roll.
def main():
print("Welcome to Craps 2.0")
playing = raw_input("Press Enter to Roll or Q to quit")
if playing == 'q':
print("Thanks for Playing")
time.sleep(2)
quit()
elif playing != 'q':
roll_multiple()
main()
main()

Related

How do I write a program that will interact with an app on my computer? (I.e feed it input)

I'm very new to python, and I'm trying write a program (i'll call it p1) that will generate random 16-digit numbers and enter them into another program (lets say p2) I have on my computer. The goal is to for p1 to keep entering a new number into p2 until it the correct number is entered.
I understand how to generate numbers and what not but I don't know how to make it so p1 enters the numbers automatically instead of having to do it manually. Basically I don't know hoe to get the two programs to interact?
If you want to get two scripts to interact, you can use subprocess.Popen, more info here: https://docs.python.org/3/library/subprocess.html. I'm not sure what you mean by programs, but an example of how you could get two scripts to interact would be:
p1:
import subprocess
import random as r
random_num = int((r.random())*99) # 2 digit number
s = subprocess.Popen(["python", "C:/Users/Jhanz/PycharmProjects/test/p2.py", str(random_num)], stdout=subprocess.PIPE)
while s.stdout.read() != b"Congratulations! You guessed the number!\r\n":
random_num = int((r.random()) * 99)
s = subprocess.Popen(["python", "C:/Users/Jhanz/PycharmProjects/test/p2.py", str(random_num)],
stdout=subprocess.PIPE)
print("You guessed the number!", random_num)
p2:
import sys
number_to_guess = 10
if int(sys.argv[1]) == number_to_guess:
print("Congratulations! You guessed the number!")
else:
print("You didn't guess the number!")

Can I make a print statement run before a module I imported?

I am a beginner to python and coding in general and I was wondering how I can make a print statement run before a module I imported. I am making a number guessing game and in my main file where I combine all the modules, I have a general function for running all the code together. It would be best if I show my code so you guys will have a better understanding of what I am dealing with:
import random
import lvl1
import time
level1 = lvl1.Level_1_activated()
# This is the main file combining everything together to make this game playable
introduction = """
Hello and welcome to NumGuess by Sava. Here is a little bit about the game:
The game works by having 3 levels, each where you must pick a number between a range of
1-10 (level 1), 1-20 (level 2), and 1-50 (level 3).
You are given 5 attempts in the first level, 10 in the second level, and 20 in the final one.
You can also access a hint by typing ‘hint’. You win the game by picking the right number in each level.
You lose the game when you run out of tries. You can get a free bonus with 5 extra tries if you type ‘hlp’.
"""
def start_game(time, lvl1):
print(introduction)
level1
start_game(time, lvl1)
This is just the code for the main module, I have the code for lvl1 (which is the first level of my 'game'), and I have a class which has all the functions which then take part in the while loop. I will also show that file:
import random
import time
# I will fist make variables for the time breaks. S is for short, M is for medium and L is for long
S = 0.2
M = 0.7
L = 1.1
class Level_1_activated():
def get_name(self):
# This function simply asks the name of the player
name = input("Before we start, what is your name? ")
time.sleep(S)
print("You said your name was: " + name)
def try_again(self):
# This asks the player if they want to try again, and shows the progress of the level
answer = (input("Do you want to try again? "))
time.sleep(M)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(M)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
# Return statement for if the player wants to play again
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
# This is the return statement that stops the while loop
return False
def find_rand_num(self, random):
# This is the core of the level, where the player just chooses numbers between 1 and 10
time.sleep(S)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(L)
# The list of numbers for the level that the player is on at the moment
num_list = [1,10]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(S)
print("Congratulations! You got the number correct!")
# Yet another return statement for the while loop
return "Found"
elif input != number:
time.sleep(M)
print("Oops, you got the number wrong")
# This variable is fairly self-explanatory; it is what controls how many itterations there are in the while loop
tries = 1
while tries < 6:
if tries < 2:
Level_1_activated().get_name()
res = Level_1_activated().find_rand_num(random)
if res == "Found":
break
checker = Level_1_activated().try_again()
if checker is False:
break
tries += 1
If you go back to this function in the main file:
def start_game(time, lvl1):
print(introduction)
level1
I intentionally put the print statement before the module to make it run first, and I have tried different approaches to this and still can't seem to get a grasp on what I'm doing wrong here. Thank you for taking the time to read the code and I would be very grateful if any of you have a possible solution to this.
there are number of thing you can do, one is encapsulate your code into functions that only run when you ask for it
lvl1
... #all the previous code
def run_game():
tries = 1
while tries < 6:
...
tries += 1
you can also make a distinction between being executed directly vs being imported, to do that is simple, you include the following check (usually at the end of the file)
if __name__ == "__main__":
#if true it mean that you're executing this module directly, otherwise it was imported
#and you include here whatever you want that happens when you execute the module directly but not when is imported, like for example running a game
run_game()
__name__ is a special variable and python will assigned the value "__main__" if executed directly, otherwise it will be the name of the file, like "lvl1" for example
And in your main you can import it and do stuff like
import lvl1
...
def start_game():
print(introduction)
lvl1.run_game()

Variable not define newbie in Python

I made a menu to play a game in python. (Please See Below). However, I can t use my lists when I call setup_game or init_trigger. I tried to put them into the while and to also add a variable play so I can avoid the user to press 2 if he never played before. my issues are the following:
Why setup_game(possible_answers, female_charactere, male_charactere) or init_trigger(possible_answers, charactere_attributes) does not work if I put the list out of the while?
why is play not defined?
Please also give me feedback on the code itself, I am a newbie and I want to improve. Thank you!
### create the menu
def menu():
print (30 * "-" , "MENU" , 30 * "-")
print ("1. Replay")
print ("2. Back to my first choice")
print ("3. Exit")
print (67 * "-")
## setup number of time player try the game
play=0
## lists needed to run setup_game and init_trigger
possible_answers= ["female","Female","F","girl","answer","Answer","a","yes","y","Yes","Y","kitchen","Kitchen","K","k","1","Leave","leave"]
female_charactere= ["boy","girl","he","his","him","prince"]
male_charactere= ["girl","boy","she","her","her","princess"]
loop=True
while loop: ## While loop which will keep going until loop = False
menu() ## Displays menu
choice = int(input("Enter your choice [1-3]: "))
if choice==1:
print ("Your story is about to start")
play=play+1 ##count number of time user play
setup_game(possible_answers, female_charactere, male_charactere) ## launch game
elif (choice==2 and play>=1):
print ("Your are back to your first choice")
play=play+1 ##count number of time user play
init_trigger(possible_answers, charactere_attributes) ##lauch game at first choice
elif (choice==2 and play==0):
print ("You have not played yet, you are starting a new story")
setup_game()
elif choice==3:
print("Thank you for playing!")
loop=False # This will make the while loop to end as not value of loop is set to False
else:
print("Thank you for playing!")
break
Why setup_game(possible_answers, female_charactere, male_charactere)
or init_trigger(possible_answers, charactere_attributes) does not work
if I put the list out of the while?
Here you're calling 2 functions you've yet to create. Unless you have more code that you did not share. Your app has no idea what to do with start_game() or init_trigger().
why is play not defined?
Python requires proper indentation, when you step into something like a function, loop, if statement, etc, you have to indent the code that belongs to it.
In your case, you've indented play = 0 under the menu() function. Because of this, play only exists in the scope of menu (). If you align play = 0 left, that warning will disappear.

Count # of times a certain outcome appears when randomly selecting from a list of possible outcomes

My code generates random outcomes of the list "outcomes". I am running batches of 10,000+, and I need a way to count the batches and total them at the bottom. How would I do this?
Here is my code:
import random
import time
from time import sleep
outcomes = ['TT','Tt','Tt','tt']
for x in range (0, 5):
b = "LOADING OUTCOMES" + "." * x
print (b, end="\r")
time.sleep(0.5)
print("4 Possible Genetic Outcomes Will Be Shown. . . ") ; sleep(1)
for x in range (0, 10000):
print(random.choice(outcomes))
time.sleep(0.001)
x=input("Done determining outcomes!! Press enter to close")
from collections import Counter
from random import choice
outcomes = ["TT", "Tt", "Tt", "tt"]
totals = Counter(choice(outcomes) for _ in range(10000))
which gives something like
Counter({'TT': 2528, 'Tt': 4914, 'tt': 2558})
This is using the code you provided in the screen shot. Here is how I would go about it. Check if this solution works for you. Next time please put the code inside the question itself and not as an image. It will attract more people to help you since they can just copy paste your code and help you out quicker instead of typing out your code themselves.
How I solved it:
have a dictionary already predefined with the possible choices from the list. Each time a choice appears, just increment the counter by 1. At the end print all the possibilities. You can use a loop to do this, but since there are only 3 elements I decided to just print them out.
import random
import time
from time import sleep
outcomes = ["TT", "Tt", "Tt", "tt"]
outcomesCount = {"TT":0, "Tt":0, "tt":0}
for x in range(0,5):
b = "LOADING OUTCOMES" + "." * x
print(b, end="\r")
time.sleep(0.5)
print("4 Possible Genetic Outcomes Will Be Shown. . . ")
sleep(1)
for x in range(0,10000):
choice = (random.choice(outcomes))
time.sleep(0.001)
outcomesCount[choice] += 1
print(choice) #This is something you were doing in original code. I would not do this because there are too many print statements, and will cause the program to run for a while.
print("The number of times each outcome appeared was: ")
print("TT : %s" %(outcomesCount["TT"]))
print("Tt : %s" %(outcomesCount["Tt"]))
print("tt : %s" %(outcomesCount["tt"]))
x = input("Done determining outcomes!! Press enter to close")
The output of running the above program was note this is only the last print statements:
The number of times each outcome appeared was:
TT : 2484
Tt : 4946
tt : 2570
Done determining outcomes!! Press enter to close
improvements:
1. get rid of the sleep because you are just delaying the program execution. You don't need it there. If you want the user to see the loading message for a second of two, you can just add 1 pause at the end.
The sleep in the second for loop is not needed at all. This is a computer and is capable of doing amazing things. This is nothing compared to what it can handle.
dont print all the outcomes, as it is going to be printing 10000 different rows.
Good luck and hope this helped.

How do you make python read a random value it printed and insert it into an array?

I have written a small coin flipping program for Home work Python, it will choose one of two values; Heads or Tails at random and print them, the loop iterates 10 times then stops. As I understand it the only way to count the number of repetitions of some words is to place the words in an array or a split variable string and then run a pre-written cnt. Click Here to see that discussion.
I need to know how you get Python to take the random value it produced and then save it into an array according to the number of iterations of the for loop(in this case x number of iterations).
Here is the variable name and the two options:
coin = ["Heads", "Tails"]
Here is the code for the coin flipper core:
#Flipping core :)
def flipit(random, flip, time, comment, repeat):
time.sleep(1)
print("It begins...")
print("\n")
for x in range(0, 10):
print("Flip number", x + 1)
print(random.choice(comment))
time.sleep(1)
print(random.choice(coin),"\n")
time.sleep(2)
print("\n")
from collections import Counter
counting = []
cnt = Counter(counting)
cnt
print("Type startup(time) to begin flipping coins again")
If you do feel like refining the code please do if you have the time, but all I need is a method that I can put into the overall program that will make it run properly.
Please don't worry about the random comment, that was for a bit of fun.
I have pasted the whole program on PasteBin, Click Here for that.
Thank you for reading this and my gratitude to those who respond or even fix it.
Edit:
Just for reference I am a bit of a newbie to Python, I know some things but not even half of what the people who answer this will know.
Solution:
I have managed to make Python "read" the random value using a per-iteration if statement in my for loop, using if statements I have added 1 to the respective variable according to the random.choice.
Here is the flip core code:
def flipit(random, time, comment, headcount, tailcount, side):
time.sleep(1)
print("It begins...")
print("\n")
for x in range(0, 10):
print("Flip number", x + 1)
side = random.choice(coin) # get the random choice
print(random.choice(comment))
time.sleep(1)
print(side) # print it
if side == "Heads":
headcount += 1
else:
tailcount += 1
time.sleep(2)
print("\n")
print("You got", headcount, "heads and", tailcount, "tails!")
print("Type start() to begin flipping coins again")
resetheadtail()
resetheadtail() is the new function I have added to reset the variables at the end of the program running.
For the full code click Here!
Thanks all who helped, and those who persevered with my newbieness :)
#comment necessary for edit, please ignore
I think what you want to do is:
flip = random.choice(coin) # get the random choice
print(flip) # print it
counting.append(flip) # add it to the list to keep track
Note that you will need to move counting = [] to before your for loop.

Categories

Resources