My code is designed to simulate a basketball game, which simulates a 30-second game with 3 points behind.
The player has to choose whether to shoot a 3-pointer, which requires more time to tie the game and regain possession, or quickly shoot a 2-pointer which is faster, and spend the rest of the time to regain possession by fouling (opponent takes 2 free throws and we regain possession) a player who can't shoot free throws. The game is simulated for about 10000 times to see which play has the highest win rate. The problem is my 'have possession' is a True/False (Boolean), but when I run it through functions, it is returned as an int. Also, the 'pointsdifference' is always the same every time I run the code.
Firstly, why is my Boolean Variable returned as an integer?
And secondly, the win rate should vary since this is a random experiment, but there are only 2 results present. How could this code be adjusted so that my simulation produces random results?
import numpy as np
trials=10000
threeptpercentage=34.6
midrangepercentage=49.5
opposingmidrangepercentage=55.4
opponentfreethrowpercentage=60.6
timetoshoot2=4
timetoshoot3=7
timetofoul=2
offensereboundpercent=66.4
ftreboundpercent=64.3
pointsdown=3
timeleft=30
haveposession=True
wins3=0
wins2=0
wintake3=[]
wintake2=[]
def foul(timeleft,pointsdown,haveposession):
#if we don't have the posession, foul to regain posession
timeleft=timeleft-timetofoul
#opponent takes 2 free throw
if np.random.randint(1,101)<=opponentfreethrowpercentage:
pointsdown=pointsdown+1
if np.random.randint(1,101)<=opponentfreethrowpercentage:
pointsdown=pointsdown+1
haveposession=True
#opponent misses the freethrow and we rebound it
else:
if np.random.randint(1,101)<=ftreboundpercent:
haveposession=True
elif np.random.randint(1,101)<=offensereboundpercent:
pointsdown=pointsdown+2
haveposession=True
return haveposession,timeleft,pointsdown
def take3(timeleft,pointsdown,haveposession):
timeleft = timeleft-timetoshoot3
#do we make the shot?
if np.random.randint(1,101)<=threeptpercentage:
pointsdown=pointsdown-3
haveposession=False
#can we rebound?
else:
if np.random.randint(1,101)<=ftreboundpercent:
haveposession=False
pointsdown=pointsdown-2
elif np.random.randint(1,101)<=opposingmidrangepercentage:
pointsdown=pointsdown+2
haveposession=True
return haveposession,timeleft,pointsdown
#attempt to make a 2 and hope for another posession
def take2(timeleft,pointsdown,haveposession):
#if we are down by 3 or more, take the 2 quickly. if we are down by 2 or less, we tun down the clock
timeleft = timeleft-timetoshoot2
#do we make the shot?
if np.random.randint(1,101)<=midrangepercentage:
pointsdown=pointsdown-2
haveposession=False
#can the opponent rebound?
else:
if np.random.randint(1,101)<=ftreboundpercent:
haveposession=False
pointsdown=pointsdown-2
return haveposession,timeleft,pointsdown
for i in range(1,trials+1):
while timeleft>0:
if haveposession==True:
timeleft,pointsdown,haveposession=take3(timeleft,pointsdown,haveposession)
else:
timeleft,pointsdown,haveposession=foul(timeleft,pointsdown,haveposession)
if pointsdown<0:
wintake3.append(wins3)
while timeleft>0:
if haveposession==True:
timeleft,pointsdown,haveposession=take2(timeleft,pointsdown,haveposession)
else:
timeleft,pointsdown,haveposession=foul(timeleft,pointsdown,haveposession)
if pointsdown<0:
wintake2.append(wins2)
winrate3=len(wintake3)*100/trials
winrate2=len(wintake2)*100/trials
print('Winrate if shoot a 3-pointer =',winrate3,'%')
print('Winrate if shoot a 2-pointer =',winrate2,'%')
Related
I want to create a battleship AI guessing, where the AI takes random shots until a hit is made.
Once a hit is made, the AI will guess the surrounding coordinates until the orientation of the ship is established.
Once the orientation is known, the AI will guess either side of the hits until the ship is sunk. It will then return to random guessing.
This page under 'a better strategy' explains more of what I want to do but improved so the AI will recognise the orientation.
The code below shows the random guessing currently used:
def ai_guessing():
global player_ships_guessed
while True:
guess_x = random_x()
guess_y = random_y()
# if statement ensuring no guesses are repeated
if playerBoard[guess_x][guess_y] == "O" or playerBoard[guess_x][guess_y] == "S":
break
guess = str(guess_x)+str(guess_y)
What is the best approach to this?
So I have simple project in Python. I have to makea simplified 2 person UNO game. I'm having a problem with the turns. I don't know why but player 2 can't paly the game. It always lets the first player to play. My code is basically like this:
Turn=1
while (Turn>0):
if (Turn%2==1):
#Player 1 plays a card
else:
#Player 1 draws a card
Turn+=1
if (Turn%2==0):
#Player 2 plays a card
else:
#Player 2 draws a card
Turn+=1
So what is the problem in code? How can I handle it? OR is there any suggestions for turn system?
The problem is you are increasing Turn by 1 and then again checking if Turn%2==0 in that iteration itself. For example if Turn is 1 currently, it will go in first if loop and then it will get incremented to become 2. Now it will pass the condition of second if loop too, and again will be incremented. You should put Turn+=1 at the end of all blocks as it is duplicated in both blocks.
Turn=1
while (Turn>0):
if (Turn%2==1):
# Player 1 plays or draws the card
else: #Notice here
# Player 2 plays or draws the card.
Turn+=1
I'm starting to learn programming and trying to write my first flash game bot, but I think I can't sort things out
This game is, player click in 5 areas randomly, if player is lucky, the enemy will get shot and reduce his hp. Enemy's hp is 6, and this game requires player to finish this in no more than 7 shots, which means player has only one chance to miss the guess.
So I "cut" the HP bar into 6 jugdement areas, and use PIL in python to judge the pixel's color change in every area, then let pyautogui to do some auto clicks. Main part of this code is:
while True:
flag = 1
for i in range(6):
s = screenGrab()
pixels = s.load()
pixelJugde_1 = pixels[judgeAreas[i]] # jugde if hp is reduced after this shot
if pixelJugde_1 != (0, 0, 0): # if this shot missed
randomClick() # try again
s = screenGrab()
pixels = s.load()
pixelJugde_2 = pixels[judgeAreas[i]] # second judge of this shot
if (pixelJugde_2 != pixelJugde_1): # hp changed, second try didn't miss
flag = 1 # mark this shot has been tried twice
randomClick() # continue next shot
elif (pixelJugde_2 == pixelJugde_1 and flag == 1): # second try missed
resetResult() # restart the game
break
else:
print 'got shot' # success at first try
randomClick() # next shot
now my problem is, if the first shot has been tried twice and marked, when the next shot begins and misses, it will still try twice, just like the marking flag is not working. So how to fix this?
I've been trying to make a basic text game in Python, and I'm using dictionaries to contain the player's information. I want to make it so that when a player's health reaches 0, the code will stop running. I've had trouble making that happen. My dictionary, which is at the beginning of my code, looks like this:
playerAtt = {}
playerAtt["Weapon"] = "Baseball bat"
playerAtt["Party"] = "Empty"
playerAtt["Health"] = 15
playerAtt["Cash"] = "$100"
print(playerAtt)
if playerAtt['Health'] <= 0:
exit()
The bottom section is what I wrote to try and make the code stop running when the player's health reached zero, but it doesn't seem to work. In one path of my game, your health gets set to zero and the game is supposed to end, but the program continues to run:
townChoice = raw_input("You met a traveler in the town. 'Yo. I'm Bob. Let's be friends.' Will you invite him to your party? Y/N\n")
if townChoice == 'y' or townChoice == 'Y':
print("That kind traveler was not such a kind traveler. He stabbed you with a machete. RIP " + Name + '.')
playerAtt['Health'] == 0
When you reach this part of the game, all it does is print the message, and moves on to the next decision. In this situation, I could just manually end the program by doing exit() under the print command, but there are circumstances where the player only loses a fraction of their health, and they would eventually reach zero. Sorry if this is a stupid question, I've only been working on Python for a few days.
You have two "=" when you set the player's health to 0
I had put 2 == instead of 1 = when defining
playerAtt["Health"].
Also, I needed to make sure it was constantly checking if the player's health was zero, so I used a while loop. I used
while playerAtt["Health"] = 0:
deathmsg()
exit()
to fix it. deathMsg was a function I made to display a random death message, for more information.
Below is the troubling code with a quick breakdown.
if player.attacked == True and delay >= 60: #if it's monster's turn plus a built in delay so everything isn't instant
for enemy in enemies_list: #iterating the all the enemies in the sprite group
if enemy.attack_rdy == True and enemy.health >0 and delay ==60: #if THAT particular monster hasn't attacked, isn't dead, and the delay has been long enough.
player.hit.play() #play the player's damaged sound
damage = random.randrange(each.attack[0],each.attack[1]+1)-player.armor #random attack roll of a tuple assigned to the enemy class
player.health -= damage
enemy.attack_rdy = False #Sets THIS particular enemy so that he may not attack until it's his turn again
player.damaged = True #Just triggers an animation on the player
each.attack_anim = 1 #triggers an animation on the enemy
break #stops the for loop so that everything doesn't happen at once and relies on the delay int.
Problem:
This iteration works properly in that the player is accurately attacked the correct number of times in accordance to the number of enemies attacking him. For some weird reason the same enemy will be attacking all those times however. When the attacking enemy dies, another one simply takes over his task of being the one who attacks. I can make no sense of it.
In true bonehead fashion, after staring at and editing my code for hours I find my blunder mere moments after posting. It's really just a stupid error.
each.attack_anim = 1
SHOULD read
enemy.attack_anim = 1
With blunder corrected, code runs as designed.