How to create a loop for multiple players turn? - python

Im trying to get this loop to work, but it just refuses to work. Any help would be very much appreciated.
while player1_score < 100 and player2_score < 100 and player3_score < 100 and player4_score < 100:
while player_turn != playerholder:
dice_rolling()
scoring()
score_awarding()
player_turn = player_turn + 1
if player_turn == playerholder:
player_turn == 1
What im trying to do is get the number of players present (playerholder) and then keep player turn within the bounds of it i.e repeating till someone gains a score of 100 or more.
Just ask if you need any more code :)
Thanks in advance.
EDIT: Everyone seems to be confused as to what I'm asking so I'm going to try explain it more elaborately.
So the game has from 2 to 4 players, and what they are trying to do is get a score of 100 or more. Since there are multiple players, I want to try and have a repeating structure to efficiently use the functions I have created over and over. With the current code, it will score Players like it should up until the last player, where the code stops completely and nothing is presented. What I would like to do is get the code to repeat infinitely until the required score is gained, as in it will keep cycling through the players with no errors. I have tried multiple times with different loops but I cannot get it to work. Hopefully this is a little bit clearer to everyone. Sorry about the unorganized/unclear question, relatively new to StackOverflow.
EDIT: Problem has been solved

As an aside, you should be keeping your players in some sort of list and iterating through them, allowing them each to take a turn in their iteration. Something like:
players = [player1,player2,player3,player4]
for player in players:
if player.score >= 100: win(player)
dice_rolling()
player.score += scoring()
But of course this only works if you have some sort of class Player in your code (which you should).
class Player(object):
def __init__(self,name):
self.name = name
self.score = 0
# what else does a Player do?
In fact you can probably make a Game class as well!
class Game(object):
def __init__(self,players):
self.players = players # a list of players
self.running = False
def dice_rolling(self):
diceroll = sum(random.randint(1,6) for _ in range(2))
def scoring(self):
return score # I don't know how you're doing this so...
def win(self,player):
print("{} wins!".format(player.name))
def run(self):
self.running = True
while self.running:
for player in self.players:
roll = dice_rolling()
player.score += scoring()
if player.score >= 100:
self.running = False
win(player)
Game().run()

Your code probably doesn't work as intended because instead
of assigning 1 to the player_turn you do this:
player_turn == 1
when it should be this:
player_turn = 1

You could try something using a list structure.
It would look like this if there were 4 players:
turns = [0,1,2,3,4,0,1,2,3,4]
#this would add another turn for player 0, to remove you just use del
turns.append(0)
#This would remove a winner from your turn stack while preserving the order
for i in turns:
if i ==4:
del i
#You could also use a dictionary if you don't like list indicies or numbers:
Players = {"blue":3, red":4, "green":2, "orange":1}
turn = [4,2,1,3,4,2,1,3]
#If there is also a maximum number of turns, you can have that hard coded also:
for i in range(max):
turn.append(1)
turn.append(2)
turn.append(3)
turn.append(4)
Truthfully, I don't really understand what your question but hopefully this may have answered it wholly or in part.

Related

I want to know why my program is not stopping in my while loop

Hy guys i have the following problem - Write a program to play the following simple game. The player starts with $100. On each
turn a coin is flipped and the player has to guess heads or tails. The player wins $9 for each
correct guess and loses $10 for each incorrect guess. The game ends either when the player
runs out of money or gets to $200.
My program is actually running. However when players points go bellow zero my program still runs and that is not what i expected. I need to know if there is something that i can do in my if sentences or if there is an easier way to make statements when i have to much conditions.
import random
list=['heads','tails']
def game():
p1=100
p2=100
while (p1>0 or p2>0)and(p1<200 or p2<200):
x=random.choice(list)
x1=input('digit your guess player1 - ')
x2=input('digit your guess player2 - ')
if x1==x:
p1+=30
else:
p1=p1-40
if x2==x:
p2+=30
else:
p2=p2-40
return p1,p2
print(game())
I expect the program to return the scores and end if any player points goes above 200 or bellow 0
If I consider your original problem, the problem is that you are returning whatever current value the player has, instead you should remember the last score and if the condition you want the game to stop on happens, return the last score. This will ensure only valid scores are returned
import random
list=['heads','tails']
def game():
player=100
last_score = 0
#Conditions to break while loop
while player > 0 and player < 200:
#Keep track of last score
last_score = player
#Get choice from player, and increase/decrease score
x=random.choice(list)
x1=input('digit your guess player1 - ')
if x1 == x:
player += 9
else:
player -= 10
#Return last score
return last_score
print(game())
Extending this idea to the 2 player game will solve your issue as well!
import random
list=['heads','tails']
def game():
p1=100
p2=100
last_scores = 0,0
# Conditions to break while loop
while (0<p1<200) and(0<p2<200):
# Keep track of last score
last_scores = p1,p2
# Get choice from player, and increase/decrease score
x=random.choice(list)
x1=input('digit your guess player1 - ')
x2=input('digit your guess player2 - ')
if x1==x:
p1+=30
else:
p1=p1-40
if x2==x:
p2+=30
else:
p2=p2-40
return last_scores
print(game())
Change the while condition to:
while p1>0 and p2>0 and p1<200 and p2<200
but it is more readable if:
while 0<p1<200 and 0<p2<200

Trying to add my first score counter (Python) (Beginner)

This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.

Correct approach to solve turn based puzzles

I am simulating a game in python. It involves two players, each has a set of turns. Based on a hit or a miss, we decide if that player will get another turn.
I not able to craft this logic programmatically, here is what I have so far:
Let's simulate each player separately for the sake of simplicity
for coordinate in list_of_player1_moves:
result = fire(coordinate[0], coordinate[1])
#result is either a 'Hit' or a 'Miss'
for coordinate in list_of_player2_moves:
result = fire(coordinate[0], coordinate[1])
#result is either a 'Hit' or a 'Miss'
Now, in order to have individual turns for each player, I did:
turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)
for turn in range(0, turns):
r = move_player1(turn) #move player inturn calls fire()
if(r == 'Hit'):
break #start over, giving them another turn
r = move_player2(turn)
if r == 'Hit':
#how do give player 2 another turn?
I am out of ideas on how to approach this further. Please suggest. Also please advice on alternative/better approaches.
Thanks!
Edit:
Sample Output for better understanding,
Player1 fires got miss
Player2 fires which got hit
Player2 fires which got miss
Player1 fires which got hit
Player1 fires which got hit
Player1 fires which got miss
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 no more missiles left to launch
Player2 fires which got hit
Player2 won the battle
Your problem description is a bit ambiguous, so I am assuming that
Every time a player hits another player, he gets 1 more move
The game doesn't terminate until both of the players run out of moves
Thus I rewrote the function
counter = 0
no_of_player1_moves = len(list_of_player1_moves)
no_of_player2_moves = len(list_of_player2_moves)
while counter < no_of_player1_moves or counter < no_of_player2_moves:
# won't terminate until both players run out of turns
r = move_player1(turn)
if(r == 'Hit'):
no_of_player1_moves += 1 #if player1 hits, player1 gets 1 more turn
r = move_player2(turn)
if(r == 'Hit'):
no_of_player2_moves += 1 #if player2 hits, player2 gets 1 more turn
counter += 1
P.S:
Instead of your long statement
turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)
You can simply use
turns = max(len(list_of_player2_moves),len(list_of_player1_moves))
Edit:
no_of_player1_moves = len(list_of_player1_moves)
no_of_player2_moves = len(list_of_player2_moves)
while no_of_player1_moves>0 or no_of_player2_moves>0:
# won't terminate until both players run out of turns
while move_player1(turn)=="Hit" and no_of_player1_moves!=0:
no_of_player1_moves -= 1
while move_player2(turn)=="Hit" and no_of_player2_moves!=0:
no_of_player2_moves -= 1
This would probably solve your problem, but the design doesn't scale well (imagine if you have 10 players, you wouldn't want to write it 10 times).
For that, I would suggest creating a Player object, and placing them in a list, then keep cycling through the list (nested while loop) until all players run out of moves. There is probably a better solution out there too (even compared to this), but that would at least be scalable.

blackjack game: for loops 'not in' vs 'in'

I have run into some trouble using for loops while making a blackjack game simulation. The function new_game simulates four cards being dealt, while new_card ensures no card is repeated in a game. I created two variations of the function new game and was wondering how they differ.
In Version 1, there were situations where the function only returned 3 cards, while Version 2 seems to work as expected.
Version 1:
def new_game():
game=[];
for x in range(4):
n=new_card();
if n not in game:
game+=[n];
else:
new_game();
print(game);
return game
Version 2:
def new_game():
game=[];
for x in range(4):
n=new_card();
if n in game:
new_game();
print(game);
else:
game+=[n];
return game
Calling new_game is not the best way to solve this project. You can try multiple ways , one of which I am showing. Rather than a constant for loop try to check the length of list until it is of desired length.
def new_game():
game=[];
while len(game)!=4:
n = new_card()
while(n in game):
n = new_card()
else:
game.append(n)
return game
print new_game()
I am not sure if this is a good design but still it works and you may modify it.
EDIT
Thanks to Blckknght for suggesting this.
def new_game():
game=[]
while len(game)!=4:
n = new_card()
if n not in game:
game.append(n)
return game
print new_game()

Creating a multiplayer blackjack game

I'm very new to python and have been trying to make a multiplayer blackjack game on python for a while now. I've been running into lots and lots of problems and was wondering if you guys could help me with them.
import random
def total(hand):
aces = hand.count(11)
t = sum(hand)
if t > 21 and aces > 0:
while aces > 0 and t > 21:
t -= 10
aces -= 1
return t
Cards = ["2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "AH", "JH", "QH", "KH", "AC", "JC", "QC", "KC", "AS", "JS", "QS", "KS", "AD", "JD", "QD", "KD"]
Cards[35] = 11
Cards[36] = 10
Cards[37] = 10
Cards[38] = 10
Cards[39] = 11
Cards[40] = 10
Cards[41] = 10
Cards[42] = 10
Cards[43] = 11
Cards[44] = 10
Cards[45] = 10
Cards[46] = 10
Cards[47] = 11
Cards[48] = 10
Cards[49] = 10
Cards[50] = 10
Players = raw_input("How many players are there?")
for i in range Players:
Player i = []
Player i.append(choice(Cards))
Player i.append(choice(Cards))
tp = total(player)
print "Player" + i + "Cards: " + Player i + "," + "total: " + tp
hitorstand = raw_input("hit (h) or stand (s)?")
if hitorstand == "h":
Player i.append(choice(cards))
print ("hit (h) or stand (s)?")
elif hitorstand == "s":
break
else print "Please enter h or s"
dealer = []
While True:
dealer.append(choice(cards))
dealer.append(choice(cards))
td = total(dealer)
while td > 17:
dealer.append(choice(cards))
else:
break
if td < tp < 21:
"Player i wins"
else print "dealer wins"
This is what I have so far. I understand there are lots of gibberish and code that won't work. I was wondering if you guys can let me know what is wrong with the code and maybe suggest some options on how to fix it.
My main concerns right now:
I am making a "multiplayer" blackjack game.
I have no idea how I'm supposed to make a loop for a multiplayer blackjack game.
In my code, I asked how many people are playing. How do I make a loop for the game without knowing
what the number will be?
Also, how do I create a function to find out the winner without knowing how many players are playing?
After I type in
Players = raw_input("How many players are there?")
for i in range Players:
The Players in the for loop gives me a syntax error. What is wrong?
As an update, I've thought about what you said about making a list
and I still do not really understand how I should go about
making a code to find out the winner.
for example
even if I make a list, if i do not know how many players are actually playing, I wouldn't be able to compare the elements in the list. If I knew how many people were playing,
playerlist = [1,2,3]
I can say
if playerlist[0] > playerlist[1], playerlist[2] and playerlist[0] < 21:
then print "player 1 wins!"
But since I won't know how many people are playing until the user actually types in the input, I am lost as to how I am supposed to write the code for the winner.
I do not know if there is a way of saying "if this is bigger than the rest". I only know how to say "if this is bigger than that".
Is there a way of saying "if this is bigger than the rest" in python?
If not, can you give me some suggestions to making the code to find out the winner?
You're on the right track with your "Players" variable. If you store an int representing the number of players there, then any time you want to do something that should require knowing the number of players, just use the Players variable instead. For instance, you can write a for loop that iterates that number of times (like you've already almost got). In order to iterate over the players, you'll need to place them in some sort of data structure (probably a list).
Once you know the number of players, you can set up the list like this:
playerList = []
for i in range(Players):
playerList[i] = [whateverDataYouWantToStoreAboutEachPlayer]
After that, you can access each player in a for loop by referring to playerList[i]. That way, you can do things for each player without knowing the number of players ahead of time.
When you use raw_input, the input is stored as a string. To use it as an int (which is the way you want to use it), you need to convert it first. You can do this with
Players = int(Players)
although it would be safer to first make sure that the number the user entered is actually a number, as in
while not Players.isdigit():
Players = raw_input("Please enter an integer: ")
Players = int(Players)
Also, as minitech said (and as shown above), you need to iterate over range(Players), rather than just Players, as that will create a list of numbers from 0 to Players-1, and you can only iterate over data that is in some sort of a sequence format.
EDIT (to answer follow-up question): You can find the largest value in the list by iterating over the whole thing and keeping track of the largest value you see:
highestIndex = 0
for i in range(Players):
if PlayerList[i] > playerList[highestIndex]:
highestIndex = i
At the end, highestIndex will hold the index in the list of the player with the highest score.
Python also has a built-in function, max(), which will give you the maximum value in a list. It won't give you the location of that value, though, so it would be more cumbersome to use in this case.

Categories