I am new to python, My first project that I am still working on is a kind of a game in which you throw a dice and stuff like that, so it's pretty much a dice simulator.
Before the user actually starts the game I have made the program ask them questions like; "Type 'start' on keyboard to begin the game, and this I am doing with raw_input.
Here's the problem:- I want to make only the input 'start' possible to write, if something else is written, the game doesn't start. I hope you understand me
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name);
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
You just need if_else
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
if start=='start':
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name)
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
else:
print("XYZ message")
Related
I'm trying to code a game of craps in which the player has a virtual 'wallet' to gamble with. I've gotten to the user input part and it's not going as planned.
Here is what I have so far:
import random
import sys
money = "500"
# start the game
a = input("Hello travler, to start the game, please type 'yes'. If you are not ready to begin your journey, type 'no' ")
if a.lower() == "no":
sys.exit()
else:
print("Welcome")
print("Hold on... I'm missing something,")
name = input("What is your name, traveler?: ")
print("Welcome,", (name))
# those who need instructions can ask for it,
# others can start the game directly.
a = input("Welcome to a game that'll determine the rest of your life. Do you need instructions? (yes) or (no)? \n")
if a.lower() == "yes":
print('''1. the player will roll two six sided dice. the sum of the two dice is the player's number for the round.
2. rolling a 7 or an 11 as your first roll win you the game, but be weary, a 2, 3, or 12 automatically causes the player to lose. no more game for you. If a 4, 5, 6, 8, 9, or 10 are rolled on this first roll, that number becomes the 'point.'
3. the fated player continues to roll the two dice again until one of two things occur: either they roll the 'point' again, causing them to win the game; or they roll a 7, causing them to be doomed to the eternals.''')
elif a.lower() == "no":
print("may luck be with you on this fateful day,", name)
print("You will start off with 500 pieces of luck, if you leave this game with over 1000 pieces of luck, you will be fated for sucsess. On the other hand, should you drop below 0 peices of luck, you will find yourself in debt to the universe, a misfortune that few recover from.")
print("You currently have", money, "luck to spare")
# betting time
while True:
bet = input("How much luck do you wish to bet? ")
if bet.isdigit() is True:
if money > bet:
print("Bet accepted")
if bet.isdigit() is True:
if bet > money:
print("How unfortunate, you do not have the luck to make this bet.")
elif bet.isdigit() is False:
print ("Sorry, luck can only be quantitated in number values.")
# if you bet higher than your money, it wont allow you to bet within after that.
The code below the line # betting time is where I am hitting my head over.
I need the code to do the following:
check if the user input is in fact a number, if it's not a number, make them enter a new input
if the user input is a number, determine if it is within the amount they have in their 'wallet' (if not, make them input a new number)
if the number is within the amount in their 'wallet' and is a digit, give the user the option to "roll dice" triggering the game to start.
If they win, they need to be granted double what they bet, if they lose, they need to lose the amount they bet. The wallet will need to update after each play, giving the user the option to play again with their updated wallet (so if they bet 50 and win, their new balance will be 550. The process continues until the user either reaches 1000 or 0, causing the game to end either way.)
For checking if the user's bet is a number use the .isnumeric() function on your bet like:
bet.isnumeric()
to do the second thing you needed help with you could do:
if bet < wallet: blah blah blah elif
bet > wallet: print("You do not enough money")
around like that it with actual good syntax
to do dice you could use the random.randint() function like this:
random.randint(1,6)
I hope that helps!
What I want to do is have Python generate a number between 1 and 6, then add 6 to that number which I have got it to do and provide me with a result, however what I can't seem to figure out is how to make that value able to be called so it can go up and down during the game, here is what I have so far:
import random
import time
Name = input("Before we get started lets get your character created, tell me what is your name?")
print()
print ("Welcome ",Name," to the adventure of a lifetime. The next thing you will need to do is sort out your character stats. This will require dice rolls which we will do within the game.")
print()
def skillroll():
skillroll=""
while skillroll !="Y" and skillroll != "N":
skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")
if skillroll=="Y":
print("Rolling the dice..")
skill=random.randint(1,6)
time.sleep(2)
print("I rolled a", skill, " I will now add 6 to this so your skill is", skill+6)
skill=skill+6
print()
return skillroll
skillroll()
I just cant see how to get that final answer out so I can use it during the game-play.
A friend of mine sent me this to help
https://github.com/protocol7/python-koans/blob/master/python%202/koans/about_classes.py
But I just cant see how this relates and every answer I found on Stackoverflow is for different languages.
Simply use:
import random
random.randrange(1, 7)
to get any number between 1 and 6.
Your code becomes:
import random
import time
def skillroll():
skillroll=""
while skillroll !="Y" and skillroll != "N":
skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")
if skillroll=="Y":
print("Rolling the dice..")
skill = random.randrange(1, 7)
time.sleep(2)
print("I rolled a ", skill, ". I will now add 6 to this so your skill is", skill+6, "\n")
skill=skill+6
return skillroll # What if N??
Name = input("Before we get started lets get your character created, tell me
what is your name?")
print ("\nWelcome ",Name," to the adventure of a lifetime. The next thing you
will need to do is sort out your character stats. This will require dice
rolls which we will do within the game.\n")
skillroll()
I'm totally new to Python and programming in general, and just starting to learn how to crawl, basically. I decided to learn programming by doing, and so I tried to develop a little dice game.
The main intention (i did not manage to succeed in making the code like i wanted it to) was to make a game with the following rules:
The game is played by two or more players
There is only one dice involved in the game
Object of the game is to be the first to get at least 100 points
A player is chosen by random to go first: The player can roll the dice as many times as s/he likes, and the points are accumulated. However, if the dice returns 1, the player loses the accumulated points. At any time, the player can choose to stop rolling the dice and secure the points. By doing this, the player loses its turn, and the next player can start rolling. Points that are secured, can never be lost.
When first trying to make this code, I wanted to make it with classes and functions, but I just couldn't make that work. Also I couldn't figure out how to design the game for multiple players. I tried working with lists and dictionaries, but I just kept pulling my hair. So I just tried to make the game for 1 player, where the objective is to reach a 100 points in fewest rounds (a new round starts everytime you secure points). Not very fun, but at least I got it to work (well, sort of).
I would highly appreciate any comments to my little program. Please note it's my first code, and I know it is really badly written. I want to hear how you guys think the code could be improved, and how I should go about in organizing the code for multiple players. I'm interested in learning to program for mobile devices at a later stage, and want to eventually turn this little game into an app so I can play with friends (for fun and as a way to learn the how-to's).
Hope the indents are adjusted properly.
from random import choice # Importing the random element to create the dice
score = 0
rounds = 1
secured = 0
unsecured = 0
ask = "N/A"
while secured+unsecured < 100: # Check if the total score is below 100
a = int(choice([1,2,3,4,5,6])) # Choose a dice number
if a == 1: # Check if the dice is one
if ask == "s": # Check if the player secured the last score
print ("Good thing you just secured your score, because you now rolled a 1.")
print ("Because of this, you only lost your round, not any points! :)")
if ask =="N/A": # Check if the player rolled a one on the first throw
print ("************* Round 1 ***********")
print ("Tough luck, you rolled a ONE on your first roll. You lost one round.")
rounds +=1
if ask == "r": # Check if the player lost points that was unsecured
print ("")
print ("***** UH UH UH UH UH - YO ROLLED A ONE ******")
print ("You lost the", unsecured,"points you didn't secure")
unsecured = 0 # Player loses the unsecured points
rounds +=1 # Increase round number
else:
unsecured = unsecured + a # If the dice returned something else than one, the player wins the points
print ("")
print ("")
print ("************ Round ", rounds, "**************")
print ("")
if a > 1: # Only display the dice if the dice is higher than one (if it's one it has already been printed)
print ("You rolled a ", a)
print ("")
print ("Unsecured points: ", unsecured)
print ("Secured points:" , secured)
print ("The sum of secured and unsecured pointsare:",secured+unsecured, "points")
print ("")
ask = input ("Roll the dice or secure? (r/s) ")
if ask == "s":
secured = secured+unsecured # If player chooses to secure the points, the points are added
score = 0
rounds +=1 # Increase round
if unsecured == 0: # Check if player was an idiot and chose to secure 0 points
print ("You chose to secure zero points, not very clever! You wouldn't risk anything by rolling the dice, and you lost the round!")
else:
print ("You chose to secure your", unsecured, "points, and you have secured", secured, "points in total")
print ("")
unsecured = 0 # Reset unsecured points, since it is added to secure points
input ("Press Enter to roll the dice:")
else:
if ask == "r":
score = unsecured+a
else:
print ("Congrats! You made ",secured+unsecured, "points in", rounds , "rounds")
Basically I want to record high scores in my program. I'm new to coding so need a bit of help. I will create this basic program to demonstrate what I want.
import time
name = input("Please enter your name: ")
mylist=["Man utd are the best team","I am going to be a pro typer.","Coding is really fun when you can do it."]
x=random.choice (mylist)
print ("The sentence I would like you to type is: ")
print (x)
wait = input ("Please press enter to continue, The timer will start upon hitting enter!")
start = time.time()
sentence = input("Start typing: ")
end = time.time()
overall = end - start
if sentence == (x):
print ("It took you this many seconds to complete the sentence: %s" % overall)
if overall <= 9:
print ("Nice job %s" % name)
print ("You have made it to level 2!")
How would I be able to save the time it took and if someone beats the time make that the new high score?
You're looking for a way to persist data across program executions. There are many ways to do it, but the simplest is just writing to a file.
In addition, if you want to use a database, look into SQLite3 for Python.
So we have a school project to make a program that asks the user whether to pick a random card from a 52 deck or simulate a coin toss - heads or tails. I've got a beta version working but I'm looking into how to make the program more efficient. Basically, the program sets the tuples 'card' and 'coin' to all the possible types, so for coin, heads and tails, and card, the 52 different cards.
The following part of the program sets the variable 'choice' to either card or coin
while choice!='card' and choice!='coin':
choice=input("Pick a card or toss a coin (card/coin)?: ")
if choice!="card" and choice!="coin":
print("Please enter either 'card' or 'coin'...")
time.sleep(2)
Next I want to be able to return a value from either tuple depending on the value of 'choice' without using and if statement, something along the following:
print("The ",choice," picked at random is... ",random.choice("Either card, or coin"),"!")
How would I do this? Thanks, Brandon.
Full program:
#importing modules used in program
import time
import random
#creating duples for possible cards and coins
cards=["Ace of spades","King of spades","Queen of spades","Jack of spades","10 of spades","9 of spades","8 of spades","7 of spades","6 of spades","5 of spades","4 of spades","3 of spades","2 of spades","Ace of diamonds","King of diamonds","Queen of diamonds","Jack of diamonds","10 of diamonds","9 of diamonds","8 of diamonds","7 of diamonds","6 of diamonds","5 of diamonds","4 of diamonds","3 of diamonds","2 of diamonds","Ace of clubs","King of clubs","Queen of clubs","Jack of clubs","10 of clubs","9 of clubs","8 of clubs","7 of clubs","6 of clubs","5 of clubs","4 of clubs","3 of clubs","2 of clubs","Ace of hearts","King of hearts","Queen of hearts","Jack of hearts","10 of hearts","9 of hearts","8 of hearts","7 of hearts","6 of hearts","5 of hearts","4 of hearts","3 of hearts","2 of hearts"]
coin=["Heads","Tails"]
#setting variable 'repeat' to 'y' to start the mainloop of the program
repeat="y"
while repeat=="y":
#blanking the repeat and choice variables so they can be reset later
repeat=""
choice=""
#won't allow the user to continue until either 'card' or 'coin' is entered
while choice!='card' and choice!='coin':
choice=input("Pick a card or toss a coin (card/coin)?: ")
if choice!="card" and choice!="coin":
print("Please enter either 'card' or 'coin'...")
time.sleep(2)
print("The ",choice," picked at random is... ",random.choice(card),"!")
#won't allow the user to continue until either 'y' or 'n' is entered
while repeat!="y" and repeat!="n":
repeat=input("Go again..? (y/n): ")
if repeat!="y" and repeat!="n":
print("Please enter either 'y' for yes or 'n' for no...")
time.sleep(2)
#ending of the program
print("Goodbye!")
time.sleep(2)
The easiest way to accomplish this is to have a dictionary of tuples:
items = { 'coin': coin,
'card': cards }
Then, after choice has been set properly by your while loop, use the word provided by the user as the key to select from the dictionary the correct list, which can then be passed to random.choice:
print("The ", choice, " picked at random is ...", random.choice(items[choice]))
I'm for sure if this is what you're asking, but if the tuple you're talking about is this ('coin', 'card'), then you can do the following:
import random
test = ('coin', 'card')
test[random.randint(0, 1)]
That will randomly select one of the two choices.