So I'm creating a very basic python game and I need some help with this step I'm stuck at. The concept of the game is for the program to roll two die and add the sums. With that number they can choose a number available from the number list (1-10) to "peg". They keep going until all numbers are pegged or are out of options. Earlier in the program I created two functions that I'm using in this step. Those two are ask_number and valid_moves. Basically the ask number just asks them which number they want to peg but it doesn't actually peg the number yet. The valid_moves function just checks which numbers are still available for the player to select.
The game pretty much just looks like this halfway through:
------------------------------
(1)(2)(3)(4)(X)(6)(7)(X)(9)(X)
------------------------------
The X are the numbers that were already pegged. In this part of the game I need to figure out how to replace the number with "X". I have this so far but I know I am way off and I am having trouble with figuring out what to do. (pegholes is the name of the list and move is the number they picked in the ask_number function). Thanks so much!
PEGGED = "X"
def enter_peg(pegholes, roll, total):
ask_number()
if ask_number == valid_moves():
pegholes.append(ask_number(PEGGED))
return pegholes, move
I am really not sure how your game is supposed to work, but this may help you out:
#!/usr/bin/env python
import random
import sys
pegs = range(2, 11)
def roll_dice():
return random.randint(1, 5) + random.randint(1, 5)
while True:
roll = roll_dice()
print "You rolled %s" %roll
available_choices = set(p for p in pegs if p != 'X') - set(range(roll+1, 11))
if len(available_choices) == 0:
print "FAIL SAUCE"
sys.exit()
while True:
choice = raw_input("Choose a number %s: " % (", ".join(str(x) for x in sorted(list(available_choices)))))
if choice == 'q':
sys.exit()
choice = int(choice)
if choice in available_choices:
break
print "Nice try buddy... pick a number in range, that hasn't been picked"
pegs[choice - 2] = 'X'
print "".join("(%s)" % p for p in pegs)
if len([x for x in pegs if x == 'X']) == 9:
print "WINNER!"
sys.exit()
I'm not clear on what you're trying to do...
When you say "add the sum" you mean add them together to get a sum, right?
Standard dice add up to 12 and two dice can't total 1 so for a fair game you want to go from 2 - 12
You could try something like this:
import random
#set up list of numbers from 2 to 10
numlist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#create a roll dice function, producing the sum of two random integers 1-6
def rolldice():
return (random.randint(1,6) + random.randint(1,6))
#run the rolldice function
roll = rolldice()
#set up a loop for while the sum of the roll appears in the list
while roll in numlist:
print "Your rolled %s" %roll
print "Your list was", numlist
print "Replacing %s with X" %roll
numlist[numlist.index(roll)]="X"
print "Your new list is", numlist
raw_input("Press enter to roll again")
roll = rolldice()
#once a roll not in the list show up:
print "Your roll was %s" %roll
print "This is not in your list"
You could also add another if statement to ask the user if they want to try again if the roll is not on the list... and then go back through the while loop.
Keep trying -- I was new to all of this last summer and am still learning. Just keep trying different things... you will learn from your mistakes.
Related
Why does my while loop repeat infinitely in Python 3? I'm trying to create a revamped riddle program and have run into 2 issues. My first is the while loop is running infinitely, and whatever the selected riddle is it's infinitely repeating. My program is supposed to create an empty list, and put 5 random numbers in it, then take that list and check if the length of it is less than 5. If it is the main program runs. I've already tried to take the integer version of the length of the list. (I'm new to programming and 12 so the answer is probably simple.) Here's my code :
import sys, random
print('Welcome to Random Riddles!')
print('This is a list of hard randomized riddles!')
print('Please type either (q)uit, or (s)tart to start this quiz or after each riddle')
Choices = input()
randRiddle_list = []
randomRiddle = random.randint(1,5)
for i in range(5) :
randomRiddle = random.randint(1,5)
randRiddle_list.append(randomRiddle)
while int(len(randRiddle_list)) <= 5 :
if randomRiddle == 1 :
if Choices == 's' :
print('Okay then, what is so fragile that saying its name breaks it?')
print('A: Silence, B: Light, C: Clothes, D: The Dark One')
elif Choices == 'q' :
sys.exit()
When you reach the following statement:
int(len(randRiddle_list)) <= 5
int(len(randRiddle_list)) is to the length of randRiddle_list. Each time the while loop re-evaluates this, the length is the same. So you need to edit the length of randRiddle_list with some command (del or pop) in order for the length to be <=5.
I think your main mistake is thinking that the while loop with your riddles is executing before the riddle list is full. What's happening is:
# After the user has entered a value, choices equals that value, and won't change
Choices = input()
randRiddle_list = []
# randomRiddle will equal one random number [1,5]
randomRiddle = random.randint(1,5)
for i in range(5) :
# You are adding that same random number to randRiddle_list 5 times
randRiddle_list.append(randomRiddle)
The code you provided doesn't ever change the length of randRiddle_list, because it's never edited after this point. Python doesn't go back here for the rest of the script.
Perhaps you would like to go over each riddle?
import sys
import random
print('Welcome to Random Riddles!')
print('This is a list of hard randomized riddles!')
print('Please type either (q)uit, or (s)tart to start this quiz or after each riddle')
Choices = input(">")
randRiddle_list = []
# This here is important, you add 5 random numbers.
# As random.randint(1, 5) gives a new random number each iteration of the loop
for i in range(5):
# Adds a random number 5 times
randRiddle_list.append(random.randint(1, 5))
for riddle in randRiddle_list:
if riddle == 1:
if Choices == 's':
print('Okay then, what is so fragile that saying its name breaks it?')
print('A: Silence, B: Light, C: Clothes, D: The Dark One')
# Ask the user for their input once again
Choice_riddle = input(">")
if Choice_riddle == "A":
print("Correct!")
else:
print("Wrong :(")
elif Choices == 'q':
sys.exit()
else:
# The random numbers in randRiddle_list are not 1, so if riddle == 1: didn't execute
print("You did not get riddle 1")
I'm programming a yahtzee like game where a player rolls 5 dice and gets to pick which dice to re-roll.
I can't get my function to properly iterate over the user input verify that they are valid.
Here's some code:
def diceroll():
raw_input("Press enter to roll dice: ")
a = random.randint(1, 6)
b = random.randint(1, 6)
c = random.randint(1, 6)
d = random.randint(1, 6)
e = random.randint(1, 6)
myroll.append(a)
myroll.append(b)
myroll.append(c)
myroll.append(d)
myroll.append(e)
print "Your roll:"
print myroll
diceSelect()
def diceSelect():
s = raw_input("Enter the numbers of the dice you'd like to roll again, separated by spaces, then press ENTER: ")
rollAgain = map(int, s.split())
updateMyRoll(rollAgain)
def updateMyRoll(a):
reroll = []
for n in a:
if n in myroll:
reroll.append(n)
removeCommonElements(myroll, a)
print "deleting elements..."
elif n not in myroll:
print "I don't think you rolled", n, "."
diceSelect()
else:
print "I don't understand..."
diceSelect()
print "Your remaining dice: ", myroll
def removeCommonElements(a,b,):
for e in a[:]:
if e in b:
a.remove(e)
b.remove(e)
The problem is likely in the diceSelect function, such that I can enter only true values and it works fine, I can enter only false values and get the desired effect for ONLY the first false value (which I understand based on the code... but would like to change), or I can enter true AND false values but it ONLY acts on the true values but ignores the false values.
How can I iterate over these values and re-prompt the user to enter all true values?
You've got a couple of problems here in your code. I've re-written your code a bit:
def diceroll(dice_count=6):
raw_input("Press enter to roll dice: ")
# No need to create a variable for each roll.
# Also modifying global variables is a bad idea
rolls = []
for _ in range(dice_count-1):
rolls.append(random.randint(1,6))
# or **instead** of the above three lines, a list
# comprehension
rolls = [random.randint(1,6) for _ in range(dice_count-1)]
return rolls
def roll_select():
# one letter variable names are hard to follow
choices = raw_input("Enter the numbers of the dice you'd like to roll again, separated by spaces, then press ENTER: ")
# again, modifying global variables is a bad idea
# so return the selection
return map(int, choices.split())
def roll_new_dice(myroll):
# no need to create a new list, we have everything
# we need right here
for val in roll_select():
try:
print('deleting {}'.format(val))
# we can just remove the values directly. We'll get
# an exception if they're not in the list.
myroll.remove(val)
except ValueError:
print("That wasn't one of your rolls")
# Then we can re-use our function - this time
# extending our list.
myroll.extend(diceroll(6-len(myroll)))
rolls = diceroll()
print('You rolled {}'.format(rolls))
changes = roll_select()
if changes:
roll_new_dice(rolls)
print('Your new rolls: {}'.format(rolls))
Hopefully this should be a bit clearer than what you had before.
"You will need to call the function once per possible die value."
I'm a programming noob and have spent about seven hours trying to figure this out.
My code is just a conglomeration of ideas and hopes that I'm headed in the right direction. I desperately need help and want to understand this stuff. I've scoured the message boards for my specific issue in vain. Please assist...
I realize my code is spitting out the result for every possible roll. When I need a program that I.E. when someone chooses to roll 50 times and designates 2 as the die value they desire to single out. The histogram would display how many times 2 was randomly rolled out of 50 rolls as asterisks on a single line of histogram.
My code thus far:
import random
def dice_sum(rolls):
results = 0
dice_sum = 0
for i in range(0, rolls):
results = random.randint(1, 6)
print("Die %d rolled %d." % (i+1, results))
dice_sum += results
print("Total of %d dice rolls is: %d" % (rolls, dice_sum))
return dice_sum
def hist_gram():
hist_gram='*'
dievalue= int(input('Which specific value between 1 and 6 are you requesting? [enter a #]'))
# get user input
rolls = int(input('How many times would you like to roll the 6 sided die? [enter a #]'))
dievalue= int(input('Which specific value between 1 and 6 are you requesting? [enter a #]'))
# pass input values to function and print result
result = dice_sum(rolls=rolls)
print(result)
You're making a mountain out of a molehill. Slow down and think about the problem. They want you to do an action a bunch of times. Then based on what each result is, do something with that information.
We can use a for loop to do the actions many times, as you've used. Then we can check the result using a simple if statement. You're trying to do the processing after the fact and it's making your life more difficult than it needs to be.
Our solution becomes very simple:
import random
def dice_count(rolls, reqValue):
count = 0
for i in range(0, rolls):
if roll_the_dice() == reqValue:
count = count + 1
#Every time we encounter the value, we count up by one
#That's it! return count.
#Apparently we want a 'single line of a histogram',
# which is kind of a pointless histogram, don't you think?
#Turns out you can multiply against strings.
return count*'*'
def roll_the_dice():
#Apparently we need to call the function more than once? Confusing instruction.
return random.randint(1,6)
And now for the input:
You can use a try..catch block to deal with bad input. If someone inputs something that's not a number, the int conversion will create a ValueError. Instead of crashing, we can decide what happens when a ValueError is raised. If an error occurs, just start over - and keep trying until the user gets it right.
def main():
doInput()
def doInput():
rolls = 0
side = 0
#set up the variables, so we can access them outside the try..catch block
try:
rolls = int(raw_input("How many times should the die be rolled? "))
except ValueError:
print "That's not a valid number. Try again!"
doInput()
try:
side = int(raw_input("Which side?"))
if side < 1 or side > 6:
print "That's not a valid side of a die! Try again!"
do_input()
except ValueError:
print "That's not a valid number. Try again!"
do_input()
dice_count(rolls, side)
You'll want to store the result of each die role somehow, rather than just adding up the sum of your roles. This will also extend your function to be able to look at the results of all 50 results if you want, or just one roll at a time.
There are a few data structures you could use, but I'd recommend a dictionary because it's the most intuitive when dealing with storing values associated with events. For example:
from collections import defaultdict
import random
def dice_sum(rolls):
results = defaultdict(int)
for i in xrange(rolls):
this_roll = random.randint(1,6)
results[this_roll] += 1
return results
Running dice_sum(50):
>>> results = dice_sum(5)
>>> results[1]
11
>>> results[2]
5
>>> results[3]
6
>>> results[4]
13
>>> results[5]
8
>>> results[6]
7
Getting a histogram for a single line has been explained, so if you want the whole thing:
def histogram(results):
hist = ""
for i in xrange(1,7):
bar = '#' * results[i]
hist += '{}: {}\n'.format(i,bar)
return hist
Running it:
>>> print histogram(results)
1: ###########
2: #####
3: ######
4: #############
5: ########
6: #######
I have been set some homework to make a word guessing game, I have got it to work for the most part but at this point I am using random.choice and that command allows the same string to repeat more than once. I need to know how to use random.randint in this instance.
""" This is a guessing game which allows the person operating the program to
guess what i want for christmas"""
import random
sw = ("Trainers")
print ("In this game you will have 10 chances to guess what I want for christmas, you start with 10 points, each time you guess incorrectly you will be deducted one point. Each time you guess incorrectly you will be given another clue.")
clue_list = ["They are an item of clothing", "The item comes in pairs", "The Item is worn whilst playing sport", "The item is an inanimate object", "The item can be made of leather","They come in differant sizes", "They have laces", "can be all differant colours", "the item has soles", "Im getting it for christmas ;)"]
def guessing_game(sw, clue_list):
x = 10
while x<=10 and x > 0:
answer = input("What do I want for christmas?")
if sw.lower() == answer and answer.isalpha():
print ("Good Guess thats what I want for christmas")
print ("You scored %s points" % (x))
break
else:
print ("incorrect, " + random.choice(clue_list))
x -=1
if x == 0:
print ("You lost, try again")
guessing_game(sw, clue_list)
for your implementation I think you want:
clueint = random.randint(0, len(clue_list))
print("incorrect, " + clue_list[clueint])
to ensure the same clues are not displayed twice declare an empty list to store guess in OUTSIDE the function definition:
clues_shown = []
and then add each int to the list:
def showClue():
clueint = random.randint(0, len(clue_list))
if clueint in clues_shown:
showClue()
else:
clues_shown.append(clueint)
print("incorrect, " + clue_list[clueint])
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()