I've been trying to figure out how to add a score to this for ages. I'm still not sure ;( sorry I'm new to coding.
this is the code for the main part
while roundsPlayed > 0:
chips_left = MAX_CHIPS
n = 1
rounds = 1
while chips_left > 0:
while True:
print("Number of chips left {}".format(chips_left))
if n%2 == 0:
print("{} How many chips would you like to take (1 - 3): ".format(playerTwo))
else:
print("{} How many chips would you like to take (1 - 3): ".format(playerOne))
try:
chipsTaken = int(input())
if chipsTaken < 1 or chipsTaken > 3:
print("Please enter a valid number from 1 to 3!")
else:
break
except:
print("Thats not even a number brotherman")
n += 1
chips_left = chips_left - chipsTaken
roundsPlayed = roundsPlayed - 1
rounds += 1
Related
Playing a 2 person game where player A and B take turns drawing stones out of a bag.
10 stones, 9 white, 1 black
You lose if you draw the black stone.
Assuming you alternate drawing stones, is going first an advantage, disadvantage, or neutral?
I'm aware that this can be solved using conditional probability, but I'd like to also prove it by using significant sample size data
import random
import os
import sys
stones = 4
player1Wins = 0
player2Wins = 0
no_games = 100000
gameCount = 0
fatal_stone = random.randint(1, int(stones))
picked_stone = random.randint(1, int(stones))
def pick_stone(self, stones):
for x in range(1, int(stones) + 1):
if picked_stone == fatal_stone:
if (picked_stone % 2) == 0:
player2Wins += 1 print("Player 2 won")
break
if (picked_stone % 2) == 1:
player1Wins += 1
print("Player 1 won")
break
else:
stones -= 1 picked_stone = random.randint(1, int(stones))
self.pick_stone()
pick_stone()
# def run_games(self, no_games): #for i in range(1, int(no_games) + 1): #gameCount = i #self.pick_stone()
print(fatal_stone)
print(picked_stone)
print(int(fatal_stone % 2))
print(int(picked_stone % 2))
print(gameCount)
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
The following code works. And it suggests that both players' chances of winning are equal, regardless of who plays first.
import random
import os
import sys
num_stones = 4
no_games = 100000
player1Wins = 0
player2Wins = 0
def pick_stone(player: int, stones: list, fatal_stone: int):
global player1Wins, player2Wins
picked_stone = random.choice(stones)
stones.remove(picked_stone)
if (picked_stone == fatal_stone):
if player == 1:
player2Wins += 1
else:
player1Wins += 1
return False
return True
def run_games(no_games: int):
for _ in range(no_games):
stones = [i for i in range(num_stones)]
fatal_stone = random.choice(stones)
# player 1 and 2 pick stones in turn
player = 1
playing = True
while playing:
playing = pick_stone(player, stones, fatal_stone)
player = player % 2 + 1
print(f"Total rounds: {no_games}")
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
run_games(no_games)
I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')
I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review
I am trying to run a quick game where the user first inputs an integer from 2-10 then inputs an integer of 1 or 2. The first choice allows for calculations to be performed on it by the second input. The second input has two games, countdown and factorial. I have the first choice running, and the code for the second choice mainly down, but I'm trying to figure out to have them run as functions where after you run either choice and completes, it prompts you to choose again.
I've tried searching the forums and looking up videos on functions but keep running into errors. Tried placing the def main(): and return in different sections of code and getting errors.
# user instructions for section 1
def opening ():
print('Please enter a number from 2 to 10 in the first prompt.')
print('In the second prompt, please choose 1 or 2 to play a number game')
opening ()
num_choice = int(input('Enter a number from 2 to 10 to begin: '))
num_choice2 = int(input('Now pick 1 for countdown or 2 for factorial: '))
if num_choice <= 1 : # error message because user can't follow directions
print('please choose from the number range provided')
# user choice branches
if num_choice2 == 1 :
print('Countdown from %d\n:' % num_choice)
elif num_choice2 == 2:
print('factorial for %d\n:' % num_choice)
# countdown loop function
while num_choice >= 2 :
print(num_choice)
num_choice -= 1
#factorial game instructions
if num_choice == 0:
print("\n The factorial of 0 is 1");
elif num_choice < 0:
print("\n Negative numbers get this done..!!");
else:
factor = 1;
for i in range(1, num_choice+1):
factor = factor*i;
print("\nFactorial of", num_choice, "is", factor);
So far, the first function, and countdown game are working as intended, the rest is as stated above.
as per my understanding of your question, i have restructured your code for better readability and provided with the solution you wanted. Hope this helps
def opening ():
print('Please enter a number from 2 to 10 in the first prompt.')
print('In the second prompt, please choose 1 or 2 to play a number game')
def countdown(num_choice):
while num_choice >= 2 :
print(num_choice)
num_choice -= 1
def factorial(num_choice):
if num_choice == 0:
print("\n The factorial of 0 is 1");
elif num_choice < 0:
print("\n Negative numbers get this done..!!");
else:
factor = 1;
for i in range(1, num_choice+1):
factor = factor*i;
print("\nFactorial of", num_choice, "is", factor);
while(True):
opening ()
num_choice = int(input('Enter a number from 2 to 10 to begin: '))
num_choice2 = int(input('Now pick 1 for countdown or 2 for factorial: '))
if num_choice <= 1 : # error message because user can't follow directions
print('please choose from the number range provided')
continue
# user choice branches
if num_choice2 == 1 :
print('Countdown from %d:\n' % num_choice)
countdown(num_choice)
elif num_choice2 == 2:
print('factorial for %d:\n' % num_choice)
factorial(num_choice)
if(input("do you want to replay?(y/n): ")=='y'):
continue
else:
break
tweak = int(input("Input an integer"))
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print(number)
collatz(tweak)
If you are trying to implement a Collatz conjecture script, then your first if is wrong - you should divide the number by 2. Also, your return causes the function to end, so you get only one while loop, doesn't matter what happens inside - so you basically return the number you inputed or that number * 3 + 1.
Here is the correct code with slight modifications:
tweak = int(input("Input an integer"))
def collatz(number):
steps = 0
num = number
while number != 1:
if number % 2 == 0:
number = number / 2
else:
number = int(3 * number + 1)
steps +=1
print("Reached 1 in {} iterations for number {}.".format(steps, num))
collatz(tweak)
You also don't need the elif, because number can only be dividable by 2 or not.
Example outputs:
collatz(22)
collatz(55)
collatz(234)
Reached 1 in 15 iterations for number 22.
Reached 1 in 112 iterations for number 55.
Reached 1 in 21 iterations for number 234.
Your question has only code, but I think this is what you might be looking for:
def collatz(tweak):
while tweak != 1:
if tweak % 2 == 0:
return int(tweak)
elif tweak % 2 != 0:
return int((3 * tweak) + 1)
print(tweak)
tweak = int(input("Input an integer:"))
result = collatz(tweak)
print(result)
Your returning values in if and else so it wont print beyond..
instead assign it in variable and do print..
tweak = input("Input an integer")
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print number # this wont work.. your returned already
print "output:%s"%collatz(tweak)
output:
me#dev-007:~/Desktop$ python test.py
Input an integer10
number 10
output:10