def multisolveF(self, firstGuess, games): wins = [] losses = 0 codes = [] most = 0 least = 10 for i in range(games): g = m.Game(colors = self.colors, pegs=self.pegs, silent=True) win, game = self.solveF(g, firstGuess, hush=True) guesses = game.rounds() answer = game.cheat() if guesses < least: least = guesses least_g = answer if guesses > most: most = guesses most_g = answer if win: wins.append(guesses) else: game.display_board() losses = losses + 1 codes.append(answer) print("Won", len(wins), "number of times with an average of: ", sum(wins)/len(wins), "rounds played.") print("The game that took the most guesses was", most, "with the code", most_g) print("The game that took the least guesses was", least, "with the code", least_g) print("Lost", losses, "number of times to these codes:", codes) return codes
def __init__(self): """Initializes the instances of the game and the AI.""" self.game = mastermind.Game( max_value=DEFAULT_MAX_VALUE, num_digits=DEFAULT_NUM_DIGITS, num_tries=DEFAULT_NUM_TRIES) self.bot = ai.AI( max_value=DEFAULT_MAX_VALUE, num_digits=DEFAULT_NUM_DIGITS) self.enable_rating = True
async def on_message(message): # we do not want the bot to reply to itself if message.author == client.user: return if message.content.startswith('!hello'): msg = 'Hello {0.author.mention}'.format(message) await client.send_message(message.channel, msg) if message.content.startswith('!fall2018'): msg = 'The Fall 2018 semester is ' + botlogic.percentFall2018( ) + '% over.' await client.send_message(message.channel, msg) if message.content.startswith('!winter2019'): msg = 'The Winter 2019 semester is ' + botlogic.percentWinter2019( ) + '% over.' await client.send_message(message.channel, msg) if message.content.startswith('!rollcharacter'): initialmsg = message.content.format(message) arguments = initialmsg.split(" ") if len(arguments) == 1: msg = 'Here is your DnD character! \n\n' + dndlogic.rollCharacter( ).format(message) await client.send_message(message.channel, msg) elif len(arguments) == 3: msg = dndlogic.rollCharacterInput(arguments[1], arguments[2]).format(message) await client.send_message(message.channel, msg) else: msg = "Try '!rollcharacter' for a fully randomized character, or '!rollcharacter <race> <class>' to" \ " choose your race and/or class! If you wish to randomize either your race or class, simply type" \ " 'any' in place of the race and/or class!" await client.send_message(message.channel, msg) if message.content.startswith('!kingdedede'): await playAudio(message.author, 'https://www.youtube.com/watch?v=-KOlVl77SkQ&t=') if message.content.startswith('!denver'): await playAudio(message.author, 'https://www.youtube.com/watch?v=1vrEljMfXYo') if message.content.startswith('!stop'): await leave(message.author) if message.content.startswith('!play'): msg = message.content.format(message) arguments = msg.split(" ") reply = "" #Create a blank string to add to for x in arguments[1:]: #Skip the first element in the list reply += x + " " #Add each "word" from the message as a separate string final = searchVideo(reply) #Search for the given text on YouTube await client.send_message(message.channel, final) #Show video link in text chat await playAudio(message.author, final) #Play the audio if 'this is so sad' in message.content: await playAudio(message.author, searchVideo("Despacito")) if message.content.startswith('!rps'): msg = message.content.format(message) arguments = msg.split(" ") hand = arguments[1] reply = botlogic.rockPaperScissors(hand) + hand.format(message) await client.send_message(message.channel, reply) if message.content.startswith('hewwo?'): msg = "https://i.kym-cdn.com/entries/icons/original/000/024/221/upload.png" await client.send_message(message.channel, msg) if message.content.startswith('!mm'): msg = message.content.format(message) arguments = msg.split(" ") if arguments[1] == "start": if len(mmGames) == 0: mmGames.append(mastermind.Game()) await client.send_message( message.channel, "**New MasterMind game has been started!**") elif mmGames[0] != None: if not mmGames[0].ongoing: mmGames[0] = mastermind.Game() await client.send_message( message.channel, "**New MasterMind game has been started!**") else: await client.send_message( message.channel, "**There's currently an ongoing game!**") else: await client.send_message(message.channel, "**We've reached the limit of 10**") elif arguments[1] == "guess": args = [arguments[2], arguments[3], arguments[4], arguments[5]] for x in args: if x not in mastermind.colorList: await client.send_message( message.channel, "I don't recognize one or more of those colors.") break else: rtn = mmGames[0].guess(arguments[2], arguments[3], arguments[4], arguments[5]) await client.send_message(message.channel, rtn) break
def __init__(self, parent, **kwargs): """Constructor""" wx.Panel.__init__(self, parent=parent) self.parent = parent #-------- initialize game self.colorIDX = np.nonzero(kwargs['codejar'])[0] kwargs['codejar'] = (np.array(kwargs['codejar'])[np.nonzero( kwargs['codejar'])]) self.game = mastermind.Game(**kwargs) self.game.initialize() #-------- determine mode (human or AI?) if not kwargs['mode'] == 0: print "Computer player" self.human_player = False self.agent = mastermind.AppAgent(game=self.game, mode=kwargs['mode'], r=kwargs['r'], t=kwargs['t']) else: print "Human player" self.human_player = True mainSizer = wx.BoxSizer(wx.VERTICAL) newGameTxt = wx.StaticText(self, label="Drag and Drop marbles" \ " to desired position") mainSizer.Add(newGameTxt, flag=wx.LEFT | wx.TOP, border=10) mainSizer.Add((-1, 10)) #-------- load images self.black_token = wx.Image(path + 'img/b.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.white_token = wx.Image(path + 'img/w.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() #-------- initialize stats window self.parent.statsFrame.InitializeStats(panel=self) self.UpdateStatistics() #-------- main game panel contentSizer = wx.BoxSizer(wx.HORIZONTAL) bgrd = wx.Image(path + 'img/h.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() fgs = wx.FlexGridSizer(self.game.maxguess, int(self.game.codelength), 6, 6) self.pegsbgrd = [ wx.StaticBitmap(self, -1, bgrd, size=(bgrd.GetWidth(), bgrd.GetHeight())) for i in np.arange(self.game.maxguess * self.game.codelength) ] fgs.AddMany(self.pegsbgrd) contentSizer.Add(fgs, proportion=1, flag=wx.LEFT, border=0) ln = wx.StaticLine(self, -1, style=wx.LI_VERTICAL, size=(5, 230)) contentSizer.Add((6, -1)) contentSizer.Add(ln, flag=wx.TOP) contentSizer.Add((6, -1)) #-------- feedback panel fbgrid = wx.FlexGridSizer(self.game.maxguess, self.game.codelength, 16, 6) fbo = wx.Image(path + 'img/o.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.fbs = [ wx.StaticBitmap(self, -1, fbo, size=(fbo.GetWidth(), fbo.GetHeight())) for i in np.arange(self.game.maxguess * self.game.codelength) ] fbgrid.AddMany(self.fbs) contentSizer.Add(fbgrid, proportion=1, flag=wx.LEFT | wx.TOP, border=4) mainSizer.Add(contentSizer, proportion=1, flag=wx.LEFT, border=10) mainSizer.Add((-1, 20)) #--------- guess btn guessbtn = wx.Button(self, -1, 'Make Guess') mainSizer.Add(guessbtn, flag=wx.LEFT | wx.RIGHT | wx.TOP, border=10) self.Bind(wx.EVT_BUTTON, self.MakeGuess, guessbtn) #-------- pegbox png = wx.Image(path + 'img/0.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() pegbox = wx.FlexGridSizer(1, self.game.Ncolors, 5, 5) self.pegtl = [ self.Marble(self, id=i, bitmap=wx.Image(path + 'img/%d.png' % self.colorIDX[i], wx.BITMAP_TYPE_ANY).ConvertToBitmap()) for i in np.arange(self.game.Ncolors) ] pegbox.AddMany(self.pegtl) peglabel = wx.StaticText(self, label="Peg Box:") mainSizer.Add(peglabel, flag=wx.LEFT | wx.TOP, border=10) mainSizer.Add((-1, 10)) mainSizer.Add(pegbox, proportion=1, flag=wx.LEFT | wx.RIGHT | wx.EXPAND, border=10) mainSizer.Add((-1, 10)) #-------- layout self.SetSizer(mainSizer) self.current_guess = [-1] * self.game.codelength
aG, bG, cG, dG = np.meshgrid(nn, gn, s1, s2) aG = aG.flatten() bG = bG.flatten() cG = cG.flatten() dG = dG.flatten() dall = pd.DataFrame({'id': aG, 'game': bG, 's1': cG, 's2': dG}) df = df.loc[df.id == dall.id[taskid], :] df = df.loc[df.game == dall.game[taskid], :] df.index = np.arange(0, len(df - 1)) game = mastermind.Game(codelength=3, codejar=[ df.code1[0], df.code2[0], df.code3[0], df.code4[0], df.code5[0], df.code6[0] ], logging=False) # game.initialize(code=[df.truth1[0], df.truth2[0], df.truth3[0]]) # for i in np.arange(len(df)): if i == 0: fs = game.get_feasible_set() ent = game.get_ents(fs, t=dall.s1[taskid], r=dall.s2[taskid]) prob = game.get_probs() first = game.codepool[:, 0].flatten() second = game.codepool[:, 1].flatten() third = game.codepool[:, 2].flatten() outfile = pd.DataFrame({
def multisolveAll(self, iterations): #For testing purposes specifically total_results = [] colors = self.colors for i in range(iterations): codelist = [] if self.pegs == 4: for i in range(colors): for j in range(colors): for k in range(colors): for l in range(colors): codelist.append([i, j, k, l]) elif self.pegs == 5: for i in range(colors): for j in range(colors): for k in range(colors): for l in range(colors): for h in range(colors): codelist.append([i, j, k, l, h]) elif self.pegs == 6: for i in range(colors): for j in range(colors): for k in range(colors): for l in range(colors): for h in range(colors): for y in range(colors): codelist.append([i, j, k, l, h, y]) codesResults = [] for c in codelist: g = m.Game(code=c, colors = self.colors, pegs=self.pegs, silent=True) win, game = self.solve(g, hush=True) codesResults.append(game.rounds()) total_results.append(codesResults) workbook = xlsxwriter.Workbook('Results.xlsx') #Write to an Excel Doc sheet1 = workbook.add_worksheet() for i in range(len(codelist)): sheet1.write(i+1, 0, str(codelist[i])) for i in range(len(total_results)): for j in range(len(total_results[i])): sheet1.write(j+1, i+1, total_results[i][j]) codesResults2 = [] total_results2 = [] for i in range(iterations): codesResults = [] for c in codelist: g = m.Game(code=c, colors = self.colors, pegs=self.pegs, silent=True) win, game = self.solveF(g, [0, 0, 1, 1], hush=True)#Change this line to test codesResults2.append(game.rounds()) total_results2.append(codesResults2) sheet2 = workbook.add_worksheet() for i in range(len(codelist)): sheet2.write(i+1, 0, str(codelist[i])) for i in range(len(total_results2)): for j in range(len(total_results2[i])): sheet2.write(j+1, i+1, total_results2[i][j]) workbook.close()
import pytest import mastermind import random game = mastermind.Game([1, 2, 3, 4], 6, 4) FIXTURE_SPECIFIC = [(0, 1, 3, 2), (0, 1, 5, 4), (0, 0, 0, 0)] FIXTURE_RANDOM = [tuple(random.sample(range(5), 3)) for _ in range(5)] def test_guess_all_right(): guess_red, guess_white = game.guess((1, 2, 3, 4)) assert guess_red == 4 and guess_white == 0 def test_guess_none_right(): guess_red, guess_white = game.guess((6, 6, 6, 6)) assert guess_red == 0 and guess_white == 0 def test_guess_two_right(): guess_red, guess_white = game.guess((1, 2, 6, 6)) assert guess_red == 2 and guess_white == 0 def test_guess_all_right_wrong_order(): guess_red, guess_white = game.guess((4, 3, 2, 1)) assert guess_red == 0 and guess_white == 4