The issue is that the number of stones the computer takes differs from the number that is displayed on the screen.
I know it's cause the function is being repeated twice. But I can't find a way to store the random number generated and use that number for printing AND subtracting
[Also I know this can be done without using functions but it is required]
Here is the code:
import random
stones = random.randint(15, 30)
turn = 0
while stones > 0:
if turn == 0:
def player_announce():
print('There are', stones, 'stones. How many would you like?', end=' ')
def invalid_entry():
print('Enter a number from 1-3.')
player_announce()
player_stones = int(input(''))
if player_stones > 3 or player_stones < 1:
invalid_entry()
else:
stones = stones - player_stones
turn = 1
else:
def draw_stones():
computer_stones = random.randint(1, 3)
return computer_stones
print('There are', stones, 'stones. The computer takes', draw_stones())
stones -= draw_stones()
turn = 0
if turn == 0:
print('The computer beats the player!')
else:
print('The player beats the computer!')
The simple answer is to call draw_stones once and store the result:
computers_stones = draw_stones()
print('There are', stones, 'stones. The computer takes', computers_stones)
stones -= computers_stones
Once you've got it working, I advise you get someone to read over the whole thing for you there are a lot of things you could do better!
Related
I am a beginner to coding in general and am trying to learn python and so I have been learning how to make a few basic games to figure things out and practice my basics... I have made a game to guess the number that is generate at a random interval of 0-100 and give feedback on if you guessed higher or lower to narrow it into your results. I managed to make the game work and I started trying to add a replayability framework so when you guess correct the game restarts automatically and a new number is generated to guess, however I am not able to make a new number generate. Originally I made the number generate outside the loop and made a loop that seemed effective but the number stayed the same, added it into the loop and it changed with every guess. so I tried adding a secondary def and pointing to it and making the number regenerate there but it doesnt seem to be making a new number still, and if I remove the generation outside of def replay def game no longer sees num as a valid variable. I am unsure how to accomplish this, any advise would be helpful....
import random
num = random.randint(0,100)
def Game():
print("Guess the Number: ")
guess = input()
guess = int(guess)
if guess==num:
print ("CORRECT!!!!!")
Replay()
elif guess>num:
print ("Sorry to high... Try again")
Game()
elif guess<num:
print ("Sorry to low... Try Again")
Game()
def Replay():
num = random.randint(0,100)
Game()
Replay()
This is a example of your code written more correctly according to me:
from random import *
def Game():
replay = 0
while replay == 0:
num = randint(0, 100) # if you want the number to revert every time you make a mistake, leave the line as it is otherwise put this assignment before the loop.
guess = int(input("Choose a integer number from 0 to 100: "))
if guess == num:
print(f"{guess} is mysterious number")
replay = 1
elif guess > num:
print(f"Sorry but {guess} is high, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
elif guess < num:
print (f"Sorry but {guess} is low, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
Game()
I have a guessing game where one player sets the number for the other person to guess, and then the other player tries to guess what the number is, and the game says if the number is higher, or lower than their current guess. My code is pretty messy, and overcomplicated since I am new to Python. But it just recently broke, not letting the player wins. When the player should win, it says that the number is higher. Here's my code:
from random import randint
import getpass
# Allows the user to select the range
guessamount = input("How large do you want the range of numbers to pick be?(Limit is 420): ")
if int(guessamount) >= int(420):
guessamount = 420
# Allows player 1 to select the answer for player 2 to guess
answer = getpass.getpass("Player 1 select the answer (The answer will not show up while typing):")
if int(answer) >= int(guessamount):
answer = guessamount
attempts = 5
while attempts != 0:
guess = input("Guess a number between 1-" + str(guessamount) + ": ")
if answer == int(guess):
attempts = 0
else:
attempts -= 1
if int(guess) > int(answer):
print ("You suck at this game. The answer is lower than " + str(guess))
else:
print ("You suck at this game. The answer is higher than " + str(guess))
if answer == int(guess):
print("You won the game! The answer was " + str(answer))
else:
print("You ran out of attempts. The number was " + str(answer))
I fixed it! I changed it so the player inserts the answer instead of it being random. And I forgot to change the numbers to int.
Thanks #jarmod for helping.
I'm a beginner in python trying to create a RPS game where human is playing against a computer. The game is created such that it would be played over a number of determined rounds (best of 3 rounds). A draw is considered a point for each side.
My problem is setting the while condition. Initially I did this:
while (player_count + computer_count) != winning_score : where the game ends when all round are played. However there will be instances where not all rounds needs to be played and the winner can already be determined (because of draws, each player will get a point).
How do I change the while condition such that when either players get winning_score/2 + 1, the game ends?
hi you can probably do it like this
winning_count = winning_score/2+1
while(player_count < winning_count) and (computer_count < winning_count):
...
Once either the player win or the computer win is more than the winning count, it goes to False and the loop breaks
Just in case you want to have another perspective on how to implement the game (and how to determine the winner), I exhort you to play with the following version:
import random
options = {1: 'Rock', 2: 'Scissors', 3: 'Paper'}
def play():
score = [0, 0]
while not any(wins == 3 for wins in score):
print(f'SCORE\tUser: {score[0]} - PC: {score[1]}')
user_selection = int(input('Enter your selection:{}> '.format(
''.join([f'\n{n}: {option}\n' for n, option in options.items()]))))
pc_selection = random.randint(1, 3)
print(f'{options[user_selection]} vs. {options[pc_selection]}')
if user_selection in (pc_selection - 1, pc_selection + 2):
print('User wins')
score[0] += 1
elif user_selection == pc_selection:
print('Draw')
else:
print('PC Wins')
score[1] += 1
input('\n_____ ENTER TO PROCEED _____')
winner = 'User' if score[0] == 3 else 'PC'
print(f'\n{winner} won the match!')
play()
Hopefully you will find here something useful and new for your learning process.
I'm trying to make a code for a multiplayer dice rolling game where the user can input how many players.
I want the code to repeat until a player reaches 100 points and go on a cycle between all the players.
I've tried all sorts of functions/modules for this and asked peers and some teachers, searched online for this and all over stack overflow but couldn't find an answer.
playerPoints = {}
toRoll = ""
minPlayers = 2
maxPlayers = 4
winner = 100
double1 = 25
def players(numberOfPlayers):
numberOfPlayers = 0
while numberOfPlayers not in (str(i) for i in range (minPlayers,maxPlayers)):
numberOfPlayers = int(numberOfPlayers)
for i in range(numberOfPlayers):
playerPoints["score{}".format(i+1)] = 0
return numberOfPlayers
def diceroll():
die1 = randint(1,6)
die2 = randint(1,6)
return die1, die2
roll = 0
while roll not in (str(i) for i in toRoll):
roll = input("Press enter to roll both dice")
if roll == toRoll:
print(str(die1) + " and " + str(die2))
break
I want the code to continue however I am stuck at this point where the code only asks how many players are there and then breaks.
I called the function by doing:
numberOfPlayers = input("How many players are there? (2-4)")
players(numberOfPlayers)
diceroll(die1, die2)
roll()
Possible fix for your problem
There are all kinds of return statements in your code which makes it impossible for some code to be executed. Like in the diceroll function where you return die1 and die2 in:
return die1, die2
The code after that line is never exectuted because the function returns some values.
You say that you execute the function like so:
numberOfPlayers = input("How many players are there? (2-4)")
players(numberOfPlayers)
diceroll(die1, die2)
roll()
However, the diceroll function takes zero parameters, while you give it two (die1 and die2), this won't work. Also I don't see a roll function in your code, so that will give you an error as well.
How I would have done it
So, I know StackOverflow is not the place where we write code for you. But since there were all kinds of things in your code that I found weird. I have rewritten the code as how I would have done it:
import random
playerPoints = []
minPlayers = 2
players = 0
maxscore = 100
amountOfDice = 2
gameRound = 0
def setPlayers():
while True:
players = input("How many players are playing?\n")
if players.isdigit():
players = int(players)
if minPlayers <= players:
for i in range(players):
playerPoints.append(0)
return players
def diceroll(player, amountOfDice):
throw = 0
print("\tPlayer {0}s turn:".format(player + 1))
for i in range(amountOfDice):
die = random.randint(1, 6)
print("\t\tPlayer {0} has thrown die {1} which landed on {2}".format(player + 1, i + 1, die))
throw += die
playerPoints[player] += throw
print("\tPlayer {0}s score is now: {1}".format(player + 1, playerPoints[player]))
return throw
def checkWin(maxscore):
for player in range(players):
if (playerPoints[player] >= maxscore):
print("Player {0} wins!".format(player + 1))
return True
return False
if __name__ == "__main__":
players = setPlayers()
while True:
gameRound += 1
print("Round: {0}".format(gameRound))
for i in range(players):
diceroll(i, amountOfDice)
if (checkWin(maxscore)):
break
Now, first off, I removed some restrictions in the players function (and changed the name to setPlayers). Your code didn't have a check if the input was a number, which could result in an error. I also removed the restriction of 4 players, because the code works with every amount (if 2 or higher ofcourse).
The diceroll function now takes the player that will roll as an argument as well as the amount of dice that will be rolled.
I also added the checkWin function which checks if a player has won. It takes the maximum score as an argument.
Now this probably isn't the fastest code, however I think its understandable. If you have any questions about it, feel free to ask.
I'm updating a crack the code game I made in Python so that you can play a single-player game against the computer. For some reason, the interpreter either doesn't use the data stripped from the input used to determine player count or skips the if statement that uses the stripped data from the input. Either way, after you input the player number it goes straight to the guessing code with an empty list of correct code characters.
My code for the player count determining and code creation is:
plyrs = 0
correctanswer = []
print('Welcome!')
plyrs = str(input('How many players are there? (minimum 1, maximum 2) '))
if plyrs == 2:
print("I'm gonna ask you for some alphanumerical (number or letter characters to make a code for the other player to guess.")
input('Press enter when you are ready to enter in the code!') #Like all of my games, it has a wait.
i = 0
while i < 4:
correctanswer.append(input('What would you like digit ' + str(i + 1) + " to be? "))
i = i + 1
print("Ok, you've got your code!")
i = 0
while i < 19: #Generates seperator to prevent cheating
print('')
i = i + 0.1
print("Now, it's the other player's turn to guess!")
elif plyrs == 1:
import random
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
i = 0
while i < 4:
correctanswer.append(characters[randint(0,36)])
i = i + 1
print('Time for you to guess!')
print('')
No other skipping if statement questions apply to this so please help.
plyrs is a string, and you're comparing it to an int. "2" == 2 will always be false. Same with plyrs == 1, this will be false throughout.