豆类游戏是两个玩家互相对战并且必须从包含 16 个豆子的一堆中拾取豆子的游戏。您每回合可以拿 1、2 或 3 个豆子。选择最后一个豆子的玩家输了。
if you start
total = 16 you chose 3 making the total 13
the opponent chooses 1,2,3 making the total 12,11,10
to get your next answer you force the opponent to land on 9
so in turn you take the total 12,11,10 -9 to get your output of 1,2 or 3
Now you want them to land on 5 to ensure you victory.
the iteration begins here, where the opponent chooses 1,2,3 making the total 8,7,6
so in turn you take the total 8,7,6 -5 to get your output of 1,2,or 3.
By doing this you now have control of the numbers 4,3,and 2.
If they chose 1 total=4 you chose 3 you win.
If they chose 2 total=3 you chose 2 you win.
If they chose 3 total=2 you chose 1 you win.
这是测试它的代码。
Beans 测试驱动程序
from myPlayer_28 import player as otherPlayer # load opponent's player code
from simple2 import player as me # load your player code
def play(player0, player1):
"""Plays a single game of 'Heap of Beans'. Winning player's # (0 or 1) is returned"""
beans = 16 # Starting bean heap
while True:
take = player0(beans) # find out how many beans player0 takes
if 1 <= take <= 3 and take <= beans: # legal # of beans taken?
beans -= take # adjust count of remaining beans
else: # user made bad move
print("Bad move:", beans, "bean(s) and", take, "taken.")
beans = 0 # force lose for bad move
if beans == 0: # does player0 lose?
return 1 # player 1 wins
take = player1(beans) # find out how many beans player1 takes
if 1 <= take <= 3 and take <= beans: # legal # of beans taken?
beans -= take # adjust count of remaining beans
else: # user made bad move
print("Bad move:", beans, "bean(s) and", take, "taken.")
beans = 0 # force lose for bad move
if beans == 0: # does player1 lose?
return 0 # player 0 wins
def main():
"""Play 100 games of 'Heap of Beans' with each player starting 50 times."""
wins = [0,0] # win accumulators for player0 and player1
for i in range(100):
if i%2:
winner = play(me,otherPlayer)
else:
winner = play(otherPlayer,me)
winner = (winner+1)%2
wins[winner] += 1
print("My wins:", wins[0], " Other wins:", wins[1])
main()
这很简单 2 我正在运行的程序。
import random
def player(beans):
if beans > 4:
return random.randrange(1,4)
if beans == 1:
return 1
return beans - 1
新代码我已经显着改变了我的代码。
def player(beans):
if beans==16:
return 3
if beans==15:
return 2
if beans==14:
return 1
if beans==13:
return 1
if beans <=12 and beans >=10:
return beans-9
if beans==9:
return 1
if beans >=6 and beans<9:
return beans -5
if beans ==5:
return 1
else:
if beans ==4:
return 3
elif beans ==3:
return 2
elif beans==2:
return 1
elif beans ==1:
return 1
对于这个问题有这么多的代码,我深表歉意。但是,我想向那些查看它的人展示它正在测试什么,因此如果他们愿意,他们可以复制所有代码以自己运行它。
“新” 我的代码赢得了 96% 的时间,但我喜欢它赢得 100% 的时间,这不可能吗?