這是HTML5項目的源代碼,該項目使用神經網絡和遺傳算法在Flappy Bird視頻遊戲中實現機器學習算法。該程序教會了一隻小鳥如何最佳地拍打,以便盡可能長時間安全地穿越障礙。
完整的教程提供了更多詳細信息和演示,您可以在這裡找到:
http://www.askforgametask.com/tutorial/machine-learning-algorithm-flappy-bird
在這裡,您還可以觀看一個簡單的算法介紹的簡短視頻:
https://www.youtube.com/watch?v=Aewmdojejf0
所有代碼均使用用於神經網絡實現的Phaser框架和突觸神經網絡庫中的HTML5編寫。
要玩遊戲,每個單元(鳥)都有自己的神經網絡,包括接下來的3層:
一個帶有2個神經元的輸入層,呈現出鳥看到的內容:
1) horizontal distance between the bird and the closest gap
2) height difference between the bird and the closest gap
帶有6個神經元的隱藏層
具有1個神經元的輸出層,用於提供以下操作:
if output > 0.5 then flap else do nothing
使用了突觸神經網絡庫來實現整個人工神經網絡,而不是從頭開始製作新的神經網絡。
該程序中實現的機器學習的主要概念是基於神經進化形式。它使用進化算法(例如遺傳算法)來訓練人工神經網絡。這是主要步驟:
與隨機神經網絡創建新的10個單位(鳥)的新人群
讓所有單元通過使用自己的神經網絡同時玩遊戲
對於每個單元,計算其適應性功能以衡量其質量為:
fitness = total travelled distance - distance to the closest gap
當所有單元被殺死時,使用遺傳算法運算符(選擇,交叉和突變)評估當前人群,如下所示:
1. sort the units of the current population in decreasing order by their fitness ranking
2. select the top 4 units and mark them as the winners of the current population
3. the 4 winners are directly passed on to the next population
4. to fill the rest of the next population, create 6 offsprings as follows:
- 1 offspring is made by a crossover of two best winners
- 3 offsprings are made by a crossover of two random winners
- 2 offsprings are direct copy of two random winners
5. to add some variations, apply random mutations on each offspring.
回到步驟2
由於該程序是使用移動器框架和突觸神經網絡庫中的HTML5編寫的,因此您需要以下文件:
整個遊戲邏輯都在gameplay.js文件中實現。它由以下課程組成:
App.Main
,具有以下基本功能的主要例程:
TreeGroup Class
,擴展的移相組類,代表移動障礙。該組包含一個頂部和底部樹斑點。
Tree Class
,擴展的移位精靈類,代表樹林。
Bird Class
,擴展的移相雪翼級課程代表鳥類精靈。
Text Class
,用於繪製文本的擴展Phaser bitmaptext類。
遺傳算法在遺傳文件中實現,該文件由以下類組成:
GeneticAlgorithm Class
,即處理所有遺傳算法操作的主要類別。它需要兩個參數: max_units在人口和top_units中設置總單位數,以設置用於不斷發展的人群的許多頂級單位(獲勝者)。這是它的基本功能: