4.3. 編程實現
(續上)
在原書的案例中,這個捕魚遊戲程序的代碼量是最多的,爲了降低初學者的學習難度,原書分4個階段編寫這個遊戲程序,併爲每個階段建一個版本。
接下來,按照前面介紹原書的編程思路和分階段多版本的思想來編寫這個遊戲程序。
- 搭建遊戲框架
首先建立一個名爲“bydr”(捕魚達人的拼音首字母)的文件夾作爲該入遊戲的項目目錄,在該目錄中建立“fonts”、“images”、“music”文件夾用於存放遊戲中使用的各種資源文件,然後將這個遊戲的圖像和聲音素材文件複製到這些目錄中。
接着,在“bydr”項目目錄中創建一個 version1.jl文件。在第 1 個階段,將搭建捕魚遊戲的基本框架,包括加載資源文和建立魚的參數配置表,創建遊戲窗口和顯示背景圖像,建立面向鼠標指針旋轉的大大炮角色,等等。
(1) 加載遊戲資源和建立魚的參數配置表
新建一個空白源文件並以game_res.jl 作爲文件名保存到根目錄中。 在這個源文件中編寫代碼加載遊戲中使用的圖像和聲音資源。
1 music="音樂珊瑚.mp3" 2 bg_img = "珊瑚海岸.jpg" 3 panel_img = "panel.png" 4 cannon_img = "cannon.png" 5 bullet_img = "bullet.png" 6 fishing_net_img = "fishing_net.png" 7 gold_coin_imgs = """["gold_coin_000.png","gold_coin_001.png","gold_coin_002.png","gold_coin_003.png","gold_coin_004.png","gold_coin_005.png","gold_coin_006.png","gold_coin_007.png","gold_coin_008.png","gold_coin_009.png"]""" 8 silver_coin_imgs = """["sil-ver_coin_000.png","silver_coin_001.png","silver_coin_002.png","silver_coin_003.png","silver_coin_004.png","silver_coin_005.png","silver_coin_006.png","gold_coin_007.png","silver_coin_008.png","silver_coin_009.png"]""
注意gold_coin_imgs和silver_coin_imgs,原書python代碼是賦值序列幀大圖的圖片名稱,這裏將序列幀大圖拆分出單個圖片,以數組字符串形式賦值給這兩個變量。
然後按照原書表31-2中的數據建立一個複合結構的字典變量fishes_config,並按以下形式將各種魚的參數組織好。
fishes_config =""" { "小黃魚":{"max":50, "alive":0, "turn":1, "life":1, "score":1, "speed":40, "file":["fish1_01.png","fish1_02.png","fish1_03.png","fish1_04.png","fish1_05.png","fish1_06.png","fish1_07.png","fish1_08.png"], "rows":8}, #添加其他魚的參數 …… }
在上面代碼中,字典變量fishes_config 中各個鍵名錶示的用途如原書表 31-3 所示。
需要說明的是,在本文中,上表的file鍵,爲字符串數組,記錄了將序列幀大圖拆分出來的單個圖片名稱。rows是序列幀大圖中網格的行數,已不需要,但暫時保留。
(2) 創建遊戲窗口和顯示背景圖像等。
在這version1.jl文件中,創建一些全局變量、遊戲窗口、顯示得分的標籤和大炮角色等,並在遊戲窗口的draw()方法中繪製出遊戲畫面。在編輯器窗口中輸人下面的代碼。
1 game_include("game_res.jl") 2 game_include("actor_plus.jl") 3 import JSON 4 5 # Height of the game window 6 HEIGHT = 668 7 # Width of the game window 8 WIDTH = 1024 9 # Background color of the game window 10 BACKGROUND = bg_img 11 #全局變量 12 fishes, bullets, nets, coins = [], [], [], [] 13 score, game_time, auto_play = 0, 0, false 14 dictFishes=JSON.parse(fishes_config) 15 panel = Actor(panel_img;pos=(130,597)) 16 cannon = Actor(cannon_img, pos=(507,610)) 17 score_label=TextActor("000000","Arial-Black",font_size=24, col-or=Int[255,255,255,255]) 18 score_label.pos=(165,635) 19 20 # The draw function is called by the framework. All we do here is draw the Actor 21 function draw(g::Game) 22 clear() 23 draw(panel) 24 draw(score_label) 25 draw(cannon) 26 end
(3) 在遊戲窗口的on_mouse_move()方法中讓大炮面向鼠標指針轉動。
function on_mouse_move(g::Game, pos) x, y = pos point(cannon,x,y) end
至此,這個遊戲程序的第1個版本完成。運行程序,就可以看到窗口中顯示背景圖、大炮等;同時,隨着鼠標指針的移動,大炮角色也跟着轉動。