how to make an if statement based on a list - python

so I have to make a rock paper scissors game in my class today and was wondering how to make an if statement based on a list's order than setup a loop for that
here is the code
def RockPaperScissorsFunction4(roundnumberforcurrentpairing, mychoices[], opponentchoices[]):
import random
first_random = random.randint(1, 3)
# 1 = rock 2 = paper 3 = scissors
if (roundnumberforcurrentpairing == 1 ):
mynextmove = 1
# mynextmove = opponentchoices[roundnumberforcurrentpairing - 2]
if roundnumberforcurrentpairing < 3:
mynextmove = 1
if opponentchoices[1, 3, 3, 3,]:
if opponentchoices[2, 3, 3, 3,]:
if opponentchoices[3, 3, 3, 3,]:

Is that you want to For loop with Array child ?
If you want opporentchoice [1,3,3,3] to came out as
1
3
3
3
then compare with first_random
here example :
opponentchoices = [1,3,3,3]
for x in opponentchoices:
first_random = random.randint(1, 3)
if(first_random > x):
print("You win")
else:
print("Opporent win")
Anyway you need to us more detail in this question
update
import random
def RockPaperScissorsFunction4(totalround, MyChoices, opponentchoices):
RoundCount = 2
MaxRound = len(opponentchoices) # We do this because we Don't need Max round more than opponent's choice
if(totalround > MaxRound): # if total round is more than choice Set total round = length of opponent's Array
totalround = MaxRound
print("Set totalround = ",totalround)
for opponent_answer in opponentchoices:
if RoundCount >= totalround:
break
if opponent_answer > opponent_answer:
print("opponent win!")
else :
print("Player win!")
RoundCount = RoundCount + 1
player_answer = random.randint(1, 3)
opponent_array = [1, 3, 3, 3]
RockPaperScissorsFunction4(5,player_answer,opponent_array)
player_answer = random.randint(1, 3)
opponent_array = [2, 3, 3, 3]
RockPaperScissorsFunction4(5,player_answer,opponent_array)
player_answer = random.randint(1, 3)
opponent_array = [3, 3, 3, 3]
RockPaperScissorsFunction4(5,player_answer,opponent_array)

Related

minimax algorithm not working in a two-player turn-based game

I am trying to use minimax algo to find a best move for a game.
The game is 2 players take turns to pick a number from a pile [0,1,2,,,8]
Winning Condition: player wins the game if the player contains three numbers and their sum is 14.
The initial game state is given by the argument like:
4 1 2 3 4
The first number indicate the total length and the following numbers are the numbers taken by player each turn. In this example the player A has [1,3] and player B has [2,4]
My problem is the algo can't give the correct answer:
Like when the input is 4 4 1 7 8 my program cannot gives the correct move: it takes 0 not 3 for next move.
import sys
import math
totalMoves = int(sys.argv[1])
pile = [0, 1, 2, 3, 4, 5, 6, 7, 8]
# who are u
you = []
opponent = []
# cards in hand
playerA = []
playerB = []
# get all the cards into hand
for i in range(totalMoves):
# save card into playerB
if i % 2 != 0:
playerB.append(int(sys.argv[i+2]))
# save card into playerA
if i % 2 == 0:
playerA.append(int(sys.argv[i+2]))
# remove sent card in list
pile.remove(int(sys.argv[i+2]))
# identify which player you are
if totalMoves % 2 == 0:
you = playerA
opponent = playerB
else:
you = playerB
opponent = playerA
def find3Numbers(player): # calcluate the card in hand is equal to 14
arr_size = len(player)
if (len(player) >= 3):
for i in range(0, arr_size-2):
for j in range(i + 1, arr_size-1):
for k in range(j + 1, arr_size):
if (player[i] + player[j] + player[k] == 14):
return True
else:
return False
def isNumberLeft(board):
if (len(board) == 0):
return False
else:
return True
def evaluate(player, oppo):
if (find3Numbers(player) == True):
return 10
elif (find3Numbers(oppo) == True):
return -10
else:
return 0
def minimax(board, player, oppo, depth, isMax):
score = evaluate(player, oppo)
if (score == 10):
return score
if (score == -10):
return score
if (isNumberLeft(board) == False):
return 0
if (isMax):
best = -math.inf
for card in board:
player.append(card)
board.remove(card)
best = max(best, minimax(board, player, oppo, depth+1, not isMax))
board.append(card)
player.remove(card)
return best
else:
best = +math.inf
for card in board:
oppo.append(card)
board.remove(card)
best = min(best, minimax(board, player, oppo, depth+1, not isMax))
board.append(card)
oppo.remove(card)
return best
def bestMove():
bestScore = -math. inf
bestNum = -math.inf
for card in pile:
you.append(card)
pile.remove(card)
score = minimax(pile, you, opponent, 0, False)
pile.append(card)
you.remove(card)
if (bestScore < score):
bestNum = card
bestScore = score
return bestNum
you.append(bestMove())

How can i add the output of my craps code to an array?

How can i add the output of my craps code to the array my_list?
I would like the final output to look like:
1's: {No. Of One's}
2's: {No. Of Two's}
3's: {No. Of Three's}
4's: {No. Of Four's}
Obviously after it prints the games output
i tried adding the append to array line to the bottom and then the print my_list to do it so it runs after however that didnt work
My code looks like this:
my_list = []
for i in range(1,2):
def RollDice():
import random
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
return int(d1 + d2)
def ComeOutRoll():
print('Come-Out Roll')
roll = RollDice()
if roll in [7, 11]:
print('You win!')
elif roll in [2,3,12]:
# craps lose
print('Craps! You lose!')
elif roll in [4,5,6,8,9,10]:
# the point
print('Point %d' % roll)
Finished = False
while not Finished: Finished = ReRoll(roll)
def ReRoll(point):
roll = RollDice()
print(' Roll: %d' % (roll))
if not roll in [7, point]:
# lose
print('Roll again!')
elif roll in [point]:
# point match
print('Point-Match')
elif roll in [7]:
# seven-out lose
# game over
print('Seven-Out!\nYou lose!\nGame Over!')
return True
return False
ComeOutRoll()
my_list.append(RollDice)
print(my_list)
Output:
Come-Out Roll
You win!
[<function RollDice at 0x000000CAEFAAFAE8>]
Try this
my_list = []
my_num = []
for i in range(1,2):
def RollDice():
import random
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
UpdArray(d1)
UpdArray(d2)
return int(d1+d2)
def UpdArray(x):
my_num.append(x)
def ComeOutRoll():
print('Come-Out Roll')
roll = RollDice()
if roll in [7, 11]:
print('You win!')
elif roll in [2,3,12]:
# craps lose
print('Craps! You lose!')
elif roll in [4,5,6,8,9,10]:
# the point
print('Point %d' % roll)
Finished = False
while not Finished: Finished = ReRoll(roll)
def ReRoll(point):
roll = RollDice()
print(' Roll: %d' % (roll))
if not roll in [7, point]:
# lose
print('Roll again!')
elif roll in [point]:
# point match
print('Point-Match')
elif roll in [7]:
# seven-out lose
# game over
print('Seven-Out!\nYou lose!\nGame Over!')
return True
return False
ComeOutRoll()
my_list.append(RollDice())
print(my_list)
print("req. ", my_num)
for x in set(my_num):
print(x,"'s", my_num.count(x), "\n" )
Sample output:
Come-Out Roll
Point 10
Roll: 7
Seven-Out!
You lose!
Game Over!
[9]
req. [4, 6, 6, 1, 3, 6]
1 's 1
3 's 1
4 's 1
6 's 3

Monty Hall simulator has a wrong outcome

I wanted to do something seemingly simple and at the same time prove Monty Hall by code, and sadly what I got was not a proof of the problem, but the complete opposite. No matter if I switch or not, I get ~33% odds of winning across 10000 simulations. Could you check the code and see what's wrong with it? Keep in mind that I'm a web-dev so my Python skills are not great and the code might not look fantastic (for example, I made a removable_doors list where just a variable would've worked fine). Cheers!
import random
av_doors = [1, 2, 3]
door_v = [1, 2, 3]
removable_doors = [1, 2, 3]
score = 0
loses = 0
door = int(input("Choose your door (1-3)"))
pick = int(door)-1
dec = input("Stay or switch? (0/1)")
n = 0
while n < 10000:
removable_doors = [1, 2, 3]
av_doors = [1, 2, 3]
val = random.randint(1,3)
if val == 1:
door_v[0] = 1
door_v[1] = 0
door_v[2] = 0
removable_doors.remove(1)
elif val == 2:
door_v[0] = 0
door_v[1] = 1
door_v[2] = 0
removable_doors.remove(2)
elif val == 3:
door_v[0] = 0
door_v[1] = 0
door_v[2] = 1
removable_doors.remove(3)
try:
removable_doors.remove(int(door))
except:
pass
av_doors.remove(door)
if len(removable_doors) == 2:
rand_door = random.randint(0,1)
if rand_door == 0:
del av_doors[0]
elif rand_door ==1:
del av_doors[1]
else:
del av_doors[0]
if dec == "1":
door = av_doors[0]
else:
pass
pick = door-1
if door_v[pick] == 1:
score+=1
else:
loses+=1
n+=1
print(score)
print(loses)
Your host sometimes removes a door with the car behind it... Here is a solution that works, and (I think) a bit better written, while keeping your structures (in python3 but that should not raise troubles):
import random
win = 0
lose = 0
switch = int(input("Stay or switch? (0-stay/1-switch):")) == 1
n = 0
while n < 10000:
# Init
door_values = [0, 0, 0]
removable_doors = [0, 1, 2]
available_doors = [0, 1, 2]
# Placing the reward somewhere
car_place = random.randint(0, 2)
door_values[car_place] = 1
removable_doors.remove(car_place)
# Choose a door
door_chosen = random.randint(0, 2)
available_doors.remove(door_chosen)
if door_chosen != car_place:
removable_doors.remove(door_chosen)
# Host removes a door that does not have the car and has not been chosen by the player
door_removed_by_host = removable_doors[random.randint(0, len(removable_doors)-1)]
available_doors.remove(door_removed_by_host)
# Switch if specified
if switch:
assert(len(available_doors) == 1)
door_chosen = available_doors[0]
# Check the result
if car_place == door_chosen:
win += 1
else:
lose += 1
n+=1
print('win=%s'%str(win))
print('lose=%s'%str(lose))
print('ratio=%s'%str(win/(win+lose)))
It gives me 0.3332 when switch=False, 0.6738 for switch=True, I guess this rather confirms Monty Hall's solution :)

Dice Poker Scoring System (Function producing NoneType)

So in my coding class we are required to make a "Dice Poker" game. We need to implement a scoring system, however, mine keeps returning a "None", therefore causing issues when I want to add the accumulated score to the base score of 100, since NoneTypes and integers can not be added. I'm aware that I need to fix whatever is causing the None, but I'm not sure how. I believe the problem could be in the "scoring" function, but perhaps it is more lurking in the later parts (After the #Choosing Last Roll or #Scoring output comments) of the function "diceGame". I'm very new to coding, and after hours of looking at this thing I'm not really sure what I'm looking at anymore. Thank you so much for your help!
Text-based dice game
from random import randint
def rollFiveDie():
allDie = []
for x in range(5):
allDie.append(randint(1,6))
return allDie
def outputUpdate(P, F):
print(P)
print(F)
def rollSelect():
rollSelected = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
selectList = rollSelected.split()
return selectList
def rollPicked(toRollList, diceList):
for i in toRollList:
diceList[int(i) - 1] = randint(1,6)
def scoring(dList):
counts = [0] * 7
for value in dList:
counts[value] = counts[value] + 1
if 5 in counts:
score = "Five of a Kind", 30
elif 4 in counts:
score = "Four of a Kind", 25
elif (3 in counts) and (2 in counts):
score = "Full House", 15
elif 3 in counts:
score = "Three of a Kind", 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
score = "Straight", 20
elif counts.count(2) == 2:
score = "Two Pair", 5
else:
score = "Lose", 0
return score
def numScore(diList):
counts = [0] * 7
for v in diList:
counts[v] = counts[v] + 1
if 5 in counts:
finScore = 30
elif 4 in counts:
finScore = 25
elif (3 in counts) and (2 in counts):
finScore = 15
elif 3 in counts:
finScore = 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
finScore = 20
elif counts.count(2) == 2:
finScore = 5
else:
finScore = 0
return finScore
def printScore(fscore):
print(fscore)
print(" ")
def diceGame():
contPlaying = True
while contPlaying:
playPoints = 30
if playPoints > 9:
playPoints -= 10
else:
print("No more points to spend. Game Over.")
contPlaying = False
playing = input("Would you like to play the Dice Game? (Answer 'y' or 'n'): ")
print(' ')
if playing == 'y':
#First Roll
fiveDie = rollFiveDie()
outputUpdate("Your roll is...", fiveDie)
#Choosing Second Roll/Second Roll execution
pickDie = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
pickDie = pickDie.split()
rollPicked(pickDie, fiveDie)
outputUpdate("Your next roll is...", fiveDie)
#Choosing Last Roll
pickDie = rollSelect()
rollPicked(pickDie, fiveDie)
outputUpdate("Your final roll is...", fiveDie)
#Scoring output
scoring(fiveDie)
finalScore = numScore(fiveDie)
playPoints += finalScore
print(playPoints)
else:
contPlaying = False
def main():
diceGame()
main()

My display module doesn't display (Python 2.7)

This is for homework. This particular school offers 0 assistance and the professor is less than helpful. I am just looking for guidance as to why this code isn't working. I have to use Python 2.7. When I run the program it asks me to enter the appropriate amount of pints but then does nothing.
# This program finds the average number of pints collected, the highest amount, and the lowest amount
# Lab 9-4 Blood drive
#the main function
def main():
endProgram = 'no'
print
while endProgram == 'no':
print
# declare variables
pints = [0] * 7
totalPints = 0
averagePints = 0
highPints = 0
lowPints = 0
# function calls
pints = getPints(pints)
totalPints = getTotal(pints, totalPints)
averagePints = getAverage(totalPints, averagePints)
highPints = getHigh(pints, highPints)
lowPints = getLow(pints, lowPints)
displayInfo(averagePints, highPints, lowPints)
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
while not (endProgram == 'yes' or endProgram == 'no'):
print 'Please enter a yes or no'
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
#the getPints function
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = input('Enter pints collected: ')
counter = counter + 1
return pints
#the getTotal function
def getTotal(pints, totalPints):
counter = 0
while counter < 7:
totalPints = totalPints + pints[counter]
counter = counter + 1
return totalPints
#the getAverage function
def getAverage(totalPints, averagePints):
averagePints = totalPints / 7
return averagePints
#the getHigh function
def getHigh(pints, highPints):
highPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] > highPints:
highPints = pints[counter]
counter = counter + 1
return highPints
#the getLow function
def getLow(pints, lowPints):
lowPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] < lowPints:
lowPints = pints[counter]
counter = counter + 1
return lowPints
#the displayInfo function
def displayInfo(averagePints, highPints, lowPints):
print "The average number of pints donated is ", averagePints
print "The highest pints donated is ", highPints
print "The lowest pints donated is ", lowPints
# calls main
main()
There is an infinite loop in function getLow() because counter is incremented only when the current value is less than the previous value. e.g. entering values 1, 2, 3, 4, 5, 6, 7 will result in an infinite loop, however, the loop will terminate if you entered 7, 6, 5, 4, 3, 2, 1.
Function getHigh() has a similar problem, but the values must be ascending if the infinite loop is to be avoided. Note that one of getLow() or getHigh() will always produce a loop in your code.
Hint: look at using Python's min() and max() functions.

Categories

Resources