投稿時間:2022-01-09 07:11:56 RSSフィード2022-01-09 07:00 分まとめ(13件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
TECH Engadget Japanese 今日からアナタは女子高生!『ドトコイ』で解像度が低すぎるドット絵イケメンと恋に落ちる:発掘!インディゲーム+ https://japanese.engadget.com/dot-koi-211016567.html steam 2022-01-08 21:10:16
python Pythonタグが付けられた新着投稿 - Qiita 機会学習モデルが変数同士の和や積の相互作用を認識するか https://qiita.com/umeboshia_0w/items/af59c6bb5d92f9289edd 2022-01-09 06:02:33
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Djangoのrequest.method=='GET'でうまく条件分岐ができない https://teratail.com/questions/377259?rss=all 2022-01-09 06:26:36
海外TECH MakeUseOf The Top 8 Linux Distros That Have Adopted Flatpak https://www.makeuseof.com/linux-distros-adopted-flatpak/ flatpak 2022-01-08 22:00:12
海外TECH DEV Community Self-built Tic-tac-toe AIs vs Human - The ultimate showdown in five rounds 🥊🏆 https://dev.to/thormeier/self-built-tic-tac-toe-ais-vs-human-the-ultimate-showdown-in-five-rounds-48m0 Self built Tic tac toe AIs vs Human The ultimate showdown in five rounds Happy new year We start this year with an epic showdown Today we ll teach a computer to play Tic tac toe with us by looking at different approaches from a dumbed down version of everything to a highly sophisticated AI I ll play five rounds of games each against the computer and see who s the ultimate Tic tac toe champion Let s get ready to rumble Tic tac what Most people have played Tic tac toe or Noughts and crosses is there a trademark I don t know hopefully not at least once in their life It s played by two players on a by grid The goal is to get of your own symbols either O or X hence Noughts and crosses either on the diagonals a row or a column The turn based game starts out with an empty board where the first player can set their symbol usually X on any cell they like the second player continues with an O on any empty field then another X can be placed on any empty field and so on A quick example of a win for X could look like this X X O X O O XThe last move center row right column or in zero indexed X Y coordinates with top left being was the winning move here Notice that there would ve been two moves to win for X either or The player just happened to chose for whatever reason Each cell can have one of three values either empty O or X One could argue that therefore there are different possible game states But that s actually a gross overestimate These around k states include boards with all X s three X s and one O etc so lots of boards that are technically against the rules A comment on Stackoverflow for the question on how to create a list of all unique Tic tac toe boards sets the number of possible game states at around times less A lot more manageable Coding out the game s rulesSince the majority of this post will be about teaching a machine to beat a human player let s not spend too much time coding the actual game In order to determine if a move is valid we need to answer these questions Was the game already won Was the game a draw Is it actually the turn of the player that want s to currently do a move Are the coordinates the player wants to play on part of the field Is the field the player wants to play on already occupied The board will be a simple array of arrays of strings we can do all these checks on We start with a utility function to count the amount of a given symbol on a board const countSymbolsInBoard board symbol gt board reduce previousRowCount currentRow gt return previousRowCount currentRow filter v gt v symbol length Next we add a function to copy a board const copyBoard board gt board board board board board board board board board Then we ll check if a given board is a draw game jsconst symbolX X const symbolO O export const isDraw board gt board flat every v gt v symbolO v symbolX And a function to check if a board was won by a given symbol with a hardcoded list of possible coordinates game jsexport const winningCoordinates export const hasWon currentBoard isX gt const checkingSymbol isX symbolX symbolO for let coordTriple of winningCoordinates const symbolTriple coordTriple map coords gt currentBoard coords coords if symbolTriple every v gt v checkingSymbol return true return false Awesome Now let s create the function that actually does the move game jsexport const doTurn currentBoard isX x y gt if isDraw currentBoard throw new Error Cannot move on board that is a draw if hasWon currentBoard true hasWon currentBoard false throw new Error Cannot move on board that was already won by someone if x gt y gt throw new Error Coordinates out of bounds x y if currentBoard y x symbolX currentBoard y x symbolO throw new Error Illegal move x y is already occupied const numberOFXs countSymbolsInBoard currentBoard symbolX const numberOFOs countSymbolsInBoard currentBoard symbolO if isX amp amp numberOFXs gt numberOFOs isX amp amp numberOFOs gt numberOFXs throw new Error Illegal move it would be isX O X s turn const newBoard copyBoard currentBoard newBoard y x isX symbolX symbolO return newBoard Almost there Now we ll need some way to actually play this We ll use the command line for this playCli jsimport doTurn hasWon isDraw from game js import createInterface from readline const playGame async gt let isX true let board const rl createInterface input process stdin output process stdout const getInput question gt new Promise resolve gt rl question question resolve while hasWon board true amp amp hasWon board false amp amp isDraw board console table board console log isX X O s turn n const x Number await getInput X coordinate const y Number await getInput Y coordinate try board doTurn board isX x y isX isX catch e console warn e message console table board console log console log isDraw board Draw hasWon board true X has won Y has won process exit playGame This should create a two player version of the game Let s give it a try Nice Now we can add the machine to that First machine strategy RandomnessFirst the machine will simply generate a bunch of random numbers as its turn machineRandom jsexport const getRandomNumber min max gt Math floor Math random max min minWe ll let the human player start and then take turns on who gets to play The human player is always X the machine is always O Adjust the playCli js a bit to add the machine playCli js let x let y if isX x Number await getInput X coordinate y Number await getInput Y coordinate else x getRandomNumber y getRandomNumber I played games against this AI and I m surprised that the AI actually managed to get wins and draws meaning I managed to beat a bunch of fair coin flips out of times Human wins Computer wins Draws Let s see how we can improve this Second strategy Random with defenseIn this approach the random numbers stay They are however accompanied by a defensive strategy If there s a winning triple filled with two opponent s symbols and an empty cell the machine will now fill that cell randomDefensePlay jsimport winningCoordinates from game js const symbolX X const symbolO O const getRandomNumber min max gt Math floor Math random max min minexport const getCoords board isX gt for let coordTriple of winningCoordinates const boardTriple coordTriple map coords gt board coords coords const numberOfOpponentSymbols boardTriple filter s gt isX s symbolO s symbolX length const numberOfEmpty boardTriple filter s gt s length Found a triple the machine can still fill in if numberOfOpponentSymbols amp amp numberOfEmpty for let coords of coordTriple Find the empty cell if board coords coords Fill it in return coords return getRandomNumber getRandomNumber Another games against that AI caught me a bit by surprise Human wins Computer wins Draws Out of games the machine has only won but managed to get from draws up to draws So this strategy sacrifices chances of winning to secure at least a draw Maybe it needs some offensive bit in there as well Third strategy Random Defense OffenseThe offense part of the strategy can be implemented the same way as the defense part Check for triples that miss a single own symbol to complete a row of three If there s none check for any potential winning moves of the opponent as before if there s none fall back to random numbers import winningCoordinates from game js const symbolX X const symbolO O const getRandomNumber min max gt Math floor Math random max min minconst getFillingCoordinatesForSymbol symbol board gt for let coordTriple of winningCoordinates const boardTriple coordTriple map coords gt board coords coords const numberOfMatchingSymbols boardTriple filter s gt s symbol length const numberOfEmpty boardTriple filter s gt s length if numberOfMatchingSymbols amp amp numberOfEmpty for let coords of coordTriple Find the empty cell if board coords coords Fill it in return coords return null export const getCoords board isX gt const ownWinCoords getFillingCoordinatesForSymbol isX symbolX symbolO board if ownWinCoords null return ownWinCoords const opponentWinCoordinates getFillingCoordinatesForSymbol isX symbolO symbolX board if opponentWinCoordinates null return opponentWinCoordinates return getRandomNumber getRandomNumber This strategy should be exceedingly harder to beat And indeed after another games this things turns out to be pretty much on par with a human player who has played games this afternoon already Human wins Computer wins Draws Fourth strategy Brute forceWell we coded out the rules we know that there s only different legal states So let s bruteforce all of them make a tree and let the machine then look up the entire tree in order to find the best solution I do expect to spend a ton of time playing here and I do not expect to win very often We ll start with a class Node that represents a single board state A board state has a score which can be machine has won draw or human has won or null undecided yet With the game s rules we can iterate over all possible game boards and find the next legal moves for every board This will build up a tree of Nodes recursively allowing us to search the tree for the best possible move bruteForcePlay jsimport doTurn hasWon isDraw from game js let createdCount You cannot compare arrays of arrays directly so we create a string representation of the board to compare thatconst areBoardsSame a b gt const flatA a flat map c gt c c join const flatB b flat map c gt c c join return flatA flatB Represents a single board and all it s possible child boards class Node constructor isXsTurn board xCoord yCoord depth createdCount Some logging to see progress if createdCount console log Created createdCount this board board this isXsTurn isXsTurn Score by depth The further down a win is the less likely it is to happen Therefore Try to take paths where a win is less deep this score null if hasWon board true this score depth else if hasWon board false Focus on winning this score depth else if isDraw board this score depth this xCoord xCoord this yCoord yCoord this children this score null this createChildren depth createChildren depth let children Loop through the entire board and create children where allowed for let x x lt x for let y y lt y try const newBoard doTurn this board this isXsTurn x y children push new Node this isXsTurn newBoard x y depth catch Move would be illegal hence the error We consider this as skip this board return children getChildNodeByBoard board Since we ve created all the possible boards if the subtree selection works once it always works So no need for checking return this children filter node gt areBoardsSame node board board Just sum up all the subtrees getScoreSum if this score null return this score return this children map c gt c getScoreSum reduce previous current gt previous current That should take a while And indeed generating all the possibilities yields a total of valid boards What the heck you might ask asking why there s that many possible boards when we were only talking about possible boards before There s several reasons First of all there s many possible ways to get to the same board Let s take a look at this board X O XThere s two ways to arrive at this Either X starts top left then O plays center then X play s bottom right or the other way around Also apparently these don t take rotations into account The rotation of the board doesn t matter for distinct boards And There s two different starting points in this case Either the human player starts or the computer player so we need to double the amount of possible boards as well And lastly there s a ton of duplicates in this tree It s called brute force for a reason right On a side note I m happy that this is Tic tac toe and not chess Chess would ve been a whole lot worse Did you know that there s around million possible boards after moves Generating every single possible game would possibly take longer than the universe has existed so far will take up more single bits than there are particles in the universe Amazing what the human mind can come up with Anyways Back to Tic tac toe We re going to use this tree representation to create an AI The actual AI This thing judges what move should be done next based on the current board and its sub tree export class AI constructor Turn here is false so on the next turn the first X would start this startNodeX new Node false null null this startNodeO new Node true null null this currentSubTree null When a game is over startOver this currentSubTree null getCoords board if this currentSubTree null if board flat join length Empty board this currentSubTree this startNodeX else this currentSubTree this startNodeO this currentSubTree this currentSubTree getChildNodeByBoard board else this currentSubTree this currentSubTree getChildNodeByBoard board We nest this so we can sort better const scoredCoords this currentSubTree children map c gt score c getScoreSum coords c xCoord c yCoord subTree c scoredCoords sort a b gt b score a score Debugging console log scoredCoords Re assign the sub tree for the next move this currentSubTree scoredCoords subTree return scoredCoords coords Spoiler alert The interesting part is that this already more or less resembles the Minimax algorithm that we ll look at next As inefficient as this approach might look it actually achieves insane results Another games against this all knowing AI yields these results Human wins Computer wins Draws The chosen scores and the relevance of depth of a subtree make this version a highly aggressive one If it cannot win it will try to produce a draw If a loss in inevitable it ll delay it as much as possible This AI is keen on not losing A rather interesting part of this strategy Whenever the center is empty it will occupy it the next move Seems like the center is key for winning or at least forcing a draw Of course if you ve found one way to win you can repeat that indefinitely but where s the fun in that Fifth strategy Minimax algorithmThe minimax algorithm isn t too much different from the brute force approach It does a search along a tree as well The key differences are that it doesn t generate the entire tree upfront and that it tries to predict what the human player will do Every move has a so called utility value to the computer player A guaranteed win has the best utility a guaranteed loss in a few turns has less value much like the score we used above The brute force method we ve used above actually tried to find the path with the best chances of winning eventually this one thinks a bit more strategically In order to search the tree we need to assume two things The computer wants to maximize its utilityThe human wants to minimize the computers utilityAnd that s why it s called the minimax algorithm The algorithm works as follows Generate all possible moves and subsequent moves recusrively as a tree up to a certain depth If a certain depth is reached or if the board was won by someone or if it reached a draw the utility score of this leave node in the tree is calculated Go one level up in the tree If the leave nodes were reached by the human player find the minimum else the maximum utility of the child nodes Set this value as the utility of the current node Repeat step alternating between min and maxWhen the root node is reached chose the child node with the maximum reached utility as the move the computer should do Usually it goes a few layers deep imagine chess for example for Tic tac toe around layers should be enough for a really challenging AI How is the utility calculated though Well that s up to us This really helpful article over on towardsdatascience com on the minimax algorithm contains an example implementation for the utility of a move which is what we ll use Makes life a bit easier Another chess related side note I m still happy this is Tic tac toe and not chess Seriously The rules of chess are several orders of magnitude more complex I could only imagine what such a utility calculation would look like I could write a five part series on that alone probably Anyways First we need a function to determine if there s two of one s own symbol in a row and an empty slot the player could fill in const symbolX X const symbolO O const hasTwoInARow board coordTriple gt const symbols coordTriple map triple gt board triple triple return symbols filter s gt s symbolX length amp amp symbols filter s gt s symbolO length amp amp symbols filter s gt s length This we can now use to caulculate the utility for a given move const calculateUtility board gt Guaranteed win go this lane if hasWon board false return Every move is useless until proven otherwise let utility winningCoordinates forEach coordTriple gt The more two in a row configurations we get the more likely a win further down the line This checks if the computer has either gained or maintained such a configuration if hasTwoInARow board coordTriple false utility Opponent still has a two in a row configuration if hasTwoInARow board coordTriple true utility return utility Then we need a function that gives us all possible moves for a given board for a given player const getPossibleMoves board isX gt const possibleMoves for let x x lt x for let y y lt y try const resultingBoard doTurn board isX x y possibleMoves push move x y resultingBoard resultingBoard utility null catch Not a valid board we therefore skip return possibleMoves And finally we can implement the recursive Minimax algorithm const minimax board currentDepth depthLimit isMaximizing gt If we reached a leave node or went as deep as we could we calculate the utility of the result if currentDepth depthLimit hasWon board true hasWon board false isDraw board return move null utility calculateUtility board resultingBoard board const possibleMoves getPossibleMoves board isMaximizing possibleMoves forEach possibleMove gt Recursive call For each possible move we get all the subsequent moves the other player could do const bestMove minimax possibleMove resultingBoard currentDepth depthLimit isMaximizing This is where we set the current node s utility It s the minimax ed utility of all the moves before it possibleMove utility bestMove utility The sorting so the actual min and max part of the algorithm possibleMoves sort a b gt if isMaximizing return a utility b utility return b utility a utility return possibleMoves export const getCoords board gt return minimax board true move Time to play And the last games of this ultimate showdown yielded these results Human wins Computer wins Draws This was interesting It actually lured me into traps a few times gaining early advantages through double two in a row configurations And those have a guarenteed win It behaved a bit weird at times when I didn t do the most ideal move for me or maybe it didn t think that the move I was doing was the most ideal for me which led to me winning without any problems a few times But this AI was the first to actually win more often than the human The resultsI ve played games against the computer let s see who has won more often Human wins Computer wins Draws Even though I got an unfair advantage in the first two rounds I think it s safe to say Human wins I hope you enjoyed reading this article as much as I enjoyed writing it and playing some Tic tac toe If so leave a ️or a I write tech articles in my free time and like to drink a coffee every once in a while If you want to support my efforts you can offer me a coffee or follow me on Twitter or here on dev to You can also support me directly via Paypal 2022-01-08 21:23:40
海外TECH Engadget Mars Perseverance halts rock sample storage due to debris https://www.engadget.com/mars-perserverance-rover-debris-problem-214828462.html?src=rss Mars Perseverance halts rock sample storage due to debrisThe Mars Perseverance rover s sample collection has run into a snag NASA reports the rover stopped caching samples after debris partly blocked the bit carousel the device that stores drill bits and passes sample tubes for internal processing The rover encountered the anomaly on December th but the mission team had to wait until January th to send a command to extract the drill bit undock the robot arm from the carousel and take images to verify what happened The obstacles are believed to be pebbles that fell out of the sample tube when dropping off the coring bit preventing that bit from sitting neatly in the carousel The storage is crucial for NASA s plans to eventually return the samples to Earth This isn t the end to sample gathering NASA JPL s chief sampling engineer Louise Jandura noted the carousel was designed to run with debris It s the first time the team has had to clear debris however and Jandura said operators would take as much time as they needed to get rid of the pebbles in a quot controlled and orderly fashion quot This isn t the first time Perseverance has run into trouble The rover failed to collect samples during its first attempt while the Ingenuity helicopter suffered a processing error during its sixth flight All the same this illustrates the challenges of the mission ーeven a seemingly pedestrian task as storing a sample can go awry in the wrong conditions And when Mars is so distant fixes aren t necessarily easy or certain I recently captured my sixth rock core and have encountered a new challenge Seems some pebble sized debris is obstructing my robotic arm from handing off the tube for sealing storage More images and data to come SamplingMars takes perseverance Blog pic twitter com sfaxuuHNGーNASA s Perseverance Mars Rover NASAPersevere January 2022-01-08 21:48:28
海外TECH CodeProject Latest Articles ThunderboltIoc: .Net Dependency Injection without Reflection! https://www.codeproject.com/Articles/5321466/ThunderboltIoc-Net-Dependency-Injection-without-Re dependency 2022-01-08 21:31:00
海外科学 NYT > Science The James Webb Telescope Finishes Deployment in Space https://www.nytimes.com/2022/01/08/science/james-webb-telescope-nasa-deployment.html telescope 2022-01-08 21:14:10
ニュース BBC News - Home Covid: UK records more than 150,000 deaths https://www.bbc.co.uk/news/uk-59923936?at_medium=RSS&at_campaign=KARANGA brazil 2022-01-08 21:01:17
ニュース BBC News - Home At least five dead after Brazil cliff collapses on boats https://www.bbc.co.uk/news/world-latin-america-59923900?at_medium=RSS&at_campaign=KARANGA cliff 2022-01-08 21:39:12
北海道 北海道新聞 セルビア、ジョコ選手支援 首相、豪と政府間協議 https://www.hokkaido-np.co.jp/article/631465/ 首相 2022-01-09 06:02:00
ビジネス 東洋経済オンライン 富裕層の足「ビジネスジェット」コロナで得た商機 航空大手にとっても「好都合」なビジネス構造 | エアライン・航空機 | 東洋経済オンライン https://toyokeizai.net/articles/-/501174?utm_source=rss&utm_medium=http&utm_campaign=link_back 全日本空輸 2022-01-09 07:00:00
ビジネス 東洋経済オンライン ホンダ「6代目ステップワゴン」王者復権への狼煙 新旧比較と総括、苦戦するミニバン市場で再起 | 新車レポート | 東洋経済オンライン https://toyokeizai.net/articles/-/500209?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2022-01-09 06:30:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)