3.1. 編程實現
這個遊戲比較簡單,沒有設計遊戲的歡迎畫面和結束畫面等,遊戲一開始就是遊戲進行畫面。同時,遊戲也沒有勝負之分,不需要設計得分、生命機制等。接下來,將按照編程思路中的介紹,分3個步 編寫程序和進行測試。
在本地磁盤新建“fkmt”(瘋狂摩托拼音首字母)目錄,根據GameZero的規則,創建相關資源的子目錄,並將字體、圖像和音頻文件放入對應的目錄。
啓動VSCode,打開fkmt目錄,新建version1.jl文件,開始編寫代碼。
1. 準備工作
在這個步驟中 ,主要是進行編寫遊戲控制邏輯前的準備工作,即遊戲配置遊戲中使用的圖像和聲音資源,設置遊戲窗口,創建角色和文本標籤,以及創建摩托車模擬動畫。
(1) 配置圖像和聲音資源
#配置資源 bg_img = "沙漠.png" box_img = "box.png" motor_sound = "motor.wav" alert_sound = "alter.mp3"
(2) 配置遊戲窗口
#創建窗口 # Height of the game window HEIGHT = 295 # Width of the game window WIDTH = 600 # Background color of the game window BACKGROUND = "沙漠.png"
(3) 創建5個全局變量,分別用於記錄摩托車的左邊座標、底部座標、行駛速度和行駛里程,以及用於模擬動畫的圖像索引值。
#全局變量 motor_left= 0 motor_bottom = 40 motor_speed = 0 mileages = 0 index = 1
(4) 創建角色和文本標籤
#創建角色 motor=Actor("motor-1.png") motor.pos=(50,193) box =Actor(box_img, pos=(500,226)) bgA=Actor(bg_img,pos=(0,0)) bgB=Actor(bg_img,pos=(0,0)) #文本標籤 speed_label = TextActor("Speed: 0","moonhouse";pos=(10,15)) mileages_label = TextActor("Mileages: 0","moonhouse";pos=(10,35))
對上面代碼的說明如下。
① 創建兩個角色摩托車motor和大箱子box。其中,摩托車角色默認顯示第一張圖片。
② 創建兩個文本標籤speed_label和mileages_label,分別用於顯示摩托車的速度和里程。
③ 創建兩個角色bgA和bgB,用於實現背景的橫屏滾動。
(5) 在窗口的draw()方法中繪製遊戲畫面。
1 function draw(g::Game) 2 #繪製遊戲畫面 3 global motor_left,motor_bottom 4 clear() 5 draw(bgA) 6 draw(bgB) 7 if motor.bottom < box.bottom 8 draw(motor) 9 draw(box) 10 else 11 draw(box) 12 draw(motor) 13 end 14 draw(speed_label) 15 draw(mileages_label) 16 end
爲了增強真實感,當摩托車和箱子的位置重疊時,根據它們的bottom座標大小決定摩托車和箱子繪製的先後順序,從而實現遮擋效果。
(6) 實現屏幕滾動
function update(g, dt) bgA.pos=(0 - floor(Int,motor_left) % 600, 0) bgB.pos=(600 - floor(Int,motor_left) % 600, 0) end
屏幕背景圖像的滾動速度與摩托車的行駛速度相關。當摩托車速度改變時,根據摩托車left座標計算出角色bgA和bgB在窗口中的起始位置,在窗口的update()方法中控制制背景圖像。請查看編程思路中對屏幕滾動技術的介紹。
代碼中floor是舍入函數,用於取整。在python中取整函數是int(),而在julia中Int()是類型轉換函數(如將String類型轉換爲Int類型)。
下表列出了 Julia 支持的舍入函數:
函數 |
描述 |
返回類型 |
實例 |
round(x) |
x 舍到最接近的整數 |
typeof(x) |
julia> round(3.8) |
round(T, x) |
x 舍到最接近的整數 |
T |
julia> round(Int, 3.8) |
floor(x) |
x 向 -Inf 舍入 |
typeof(x) |
julia> floor(3.8) |
floor(T, x) |
x 向 -Inf 舍入 |
T |
julia> floor(Int, 3.8) |
ceil(x) |
x 向 +Inf 方向取整 |
typeof(x) |
julia> ceil(3.8) |
ceil(T, x) |
x 向 +Inf 方向取整 |
T |
julia> ceil(Int, 3.8) |
trunc(x) |
x 向 0 取整 |
typeof(x) |
julia> trunc(3.8) |
trunc(T, x) |
x 向 0 取整 |
T |
julia> trunc(Int, 3.8) |
(7) 創建摩托車模擬動畫
新增一個計劃任務:schedule_interval(motor_animation,1/16),每隔1/16秒,調用函數motor_animation(),實現圖像的輪換。motor_animation函數的代碼如下:
1 function motor_animation() 2 global index 3 #println(k) 4 if index < 7 5 motor.image = "motor-" * string(index) * ".png" 6 index += 1 7 8 else 9 index=1 10 end 11 end
至此,第1個步驟的工作就完成了。運行程序,就可以看到窗口中繪製出的沙漠背景圖,摩托車的行駛速度和里程顯示爲0,麾託車和箱子出現在沙漠公路上。