Это вторая часть нашего учебного пособия по Corona SDK Whack A Mole. В сегодняшнем уроке мы добавим наш интерфейс и начнем программировать взаимодействие с игрой. Читай дальше!
Где мы остановились. , ,
Пожалуйста, ознакомьтесь с первой частью серии, чтобы полностью понять и подготовиться к этому уроку.
Шаг 1: Загрузка звуков
Звуковые эффекты, используемые в игре, будут загружены при запуске. Это сделает их готовыми к игре немедленно.
| 
 1 
 | 
 local hit = audio.loadSound(‘hit.wav’) 
 | 
Шаг 2: переменные
Эти переменные мы будем использовать. Прочитайте комментарии в коде, чтобы узнать о них больше. Некоторые из их имен говорят сами за себя, поэтому дальнейших комментариев там не будет.
| 
 1 
2 
3 
4 
 | 
 local timerSource 
local currentWorms = 0 —worms already shown 
local wormsHit = 0 
local totalWorms = 10 —total worms to hit 
 | 
Шаг 3: Объявление функций
Объявите все функции как локальные в начале.
| 
 01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 
 | 
 local Main = {} 
local startButtonListeners = {} 
local showCredits = {} 
local hideCredits = {} 
local showGameView = {} 
local prepareWorms = {} 
local startTimer = {} 
local showWorm = {} 
local popOut = {} 
local wormHit = {} 
local alert = {} 
 | 
Шаг 4: Конструктор
Далее мы создадим функцию, которая будет инициализировать всю игровую логику:
| 
 1 
2 
3 
 | 
 function Main() 
    —code 
end 
 | 
Шаг 5: Добавьте заголовок
Теперь мы помещаем TitleView на сцену и вызываем функцию, которая добавит слушателей касаний к кнопкам.
| 
 1 
2 
3 
4 
5 
6 
7 
8 
 | 
 function Main() 
    titleBg = display.newImage(‘titleBg.png’) 
    playBtn = display.newImage(‘playBtn.png’, display.contentCenterX — 25.5, display.contentCenterY + 40) 
    creditsBtn = display.newImage(‘creditsBtn.png’, display.contentCenterX — 40.5, display.contentCenterY + 85) 
    titleView = display.newGroup(titleBg, playBtn, creditsBtn) 
         startButtonListeners(‘add’) 
end 
 | 
Шаг 6: Пуск слушателей кнопки
Эта функция добавляет необходимых слушателей к кнопкам TitleView .
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
 | 
 function startButtonListeners(action) 
    if(action == ‘add’) then 
        playBtn:addEventListener(‘tap’, showGameView) 
        creditsBtn:addEventListener(‘tap’, showCredits) 
    else 
        playBtn:removeEventListener(‘tap’, showGameView) 
        creditsBtn:removeEventListener(‘tap’, showCredits) 
    end 
end 
 | 
Шаг 7: Показать кредиты
Экран кредитов отображается, когда пользователь нажимает кнопку кредитов. Прослушиватель касаний добавляется в представление кредитов, чтобы удалить его.
| 
 1 
2 
3 
4 
5 
6 
 | 
 function showCredits:tap(e) 
    playBtn.isVisible = false 
    creditsBtn.isVisible = false 
    creditsView = display.newImage(‘creditsView.png’) 
    transition.from(creditsView, {time = 300, x = -creditsView.width, onComplete = function() creditsView:addEventListener(‘tap’, hideCredits) creditsView.x = creditsView.x — 0.5 end}) 
end 
 | 
Шаг 8: Скрыть кредиты
При нажатии на экран кредитов, он будет отключен со сцены и удален.
| 
 1 
2 
3 
4 
5 
 | 
 function hideCredits:tap(e) 
    playBtn.isVisible = true 
    creditsBtn.isVisible = true 
    transition.to(creditsView, {time = 300, x = -creditsView.width, onComplete = function() creditsView:removeEventListener(‘tap’, hideCredits) display.remove(creditsView) creditsView = nil end}) 
end 
 | 
Шаг 9: Показать игровой вид
Когда нажата кнопка « Воспроизведение» , вид заголовка изменяется и удаляется, открывая вид игры. Текст оценки добавляется на этом шаге тоже.
| 
 1 
2 
3 
4 
5 
6 
 | 
 function showGameView:tap(e) 
    transition.to(titleView, {time = 300, x = -titleView.height, onComplete = function() startButtonListeners(‘rmv’) display.remove(titleView) titleView = nil end}) 
    score = display.newText(‘0’ .. ‘/’ .. totalWorms, 58, 6, native.systemFontBold, 16) 
    score:setTextColor(238, 238, 238) 
    prepareWorms() 
end 
 | 
Шаг 10: Подготовь червей
Следующая функция создает и помещает червей в сцену. Мы скрываем их позже и добавляем к каждому прослушивателю.
| 
 01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
 | 
 function prepareWorms() 
    w1 = display.newImage(‘worm.png’, 80.5, 11) 
    w2 = display.newImage(‘worm.png’, 198.5, 51) 
    w3 = display.newImage(‘worm.png’, 338.5, 34) 
    w4 = display.newImage(‘worm.png’, 70.5, 110) 
    w5 = display.newImage(‘worm.png’, 225.5, 136) 
    w6 = display.newImage(‘worm.png’, 376.5, 96) 
    w7 = display.newImage(‘worm.png’, 142.5, 211) 
    w8 = display.newImage(‘worm.png’, 356.5, 186) 
         worms = display.newGroup(w1, w2, w3, w4, w5, w6, w7, w8) 
         for i = 1, worms.numChildren do 
        worms[i]:addEventListener(‘tap’, wormHit) 
        worms[i].isVisible = false 
    end 
         startTimer() 
end 
 | 
Шаг 11: Проверка кода
Вот полный код, написанный в этом руководстве, вместе с комментариями, которые помогут вам идентифицировать каждую часть:
| 
 001 
002 
003 
004 
005 
006 
007 
008 
009 
010 
011 
012 
013 
014 
015 
016 
017 
018 
019 
020 
021 
022 
023 
024 
025 
026 
027 
028 
029 
030 
031 
032 
033 
034 
035 
036 
037 
038 
039 
040 
041 
042 
043 
044 
045 
046 
047 
048 
049 
050 
051 
052 
053 
054 
055 
056 
057 
058 
059 
060 
061 
062 
063 
064 
065 
066 
067 
068 
069 
070 
071 
072 
073 
074 
075 
076 
077 
078 
079 
080 
081 
082 
083 
084 
085 
086 
087 
088 
089 
090 
091 
092 
093 
094 
095 
096 
097 
098 
099 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
 | 
 — Whack A Worm Game 
— Developed by Carlos Yanez 
— Hide Status Bar 
display.setStatusBar(display.HiddenStatusBar) 
— Import MovieClip 
local movieclip = require(‘movieclip’) 
— Graphics 
— [Background] 
local bg = display.newImage(‘gameBg.png’) 
— [Title View] 
local titleBg 
local playBtn 
local creditsBtn 
local titleView 
— [Credits] 
local creditsView 
— [Score] 
local score 
— [Worms] 
local w1 
local w2 
local w3 
local w4 
local w5 
local w6 
local w7 
local w8 
local worms 
local lastWorm = {} 
— Load Sound 
local hit = audio.loadSound(‘hit.wav’) 
— Variables 
local timerSource 
local currentWorms = 0 
local wormsHit = 0 
local totalWorms = 10 
— Functions 
local Main = {} 
local startButtonListeners = {} 
local showCredits = {} 
local hideCredits = {} 
local showGameView = {} 
local prepareWorms = {} 
local startTimer = {} 
local showWorm = {} 
local popOut = {} 
local wormHit = {} 
local alert = {} 
— Main Function 
function Main() 
    titleBg = display.newImage(‘titleBg.png’) 
    playBtn = display.newImage(‘playBtn.png’, display.contentCenterX — 25.5, display.contentCenterY + 40) 
    creditsBtn = display.newImage(‘creditsBtn.png’, display.contentCenterX — 40.5, display.contentCenterY + 85) 
    titleView = display.newGroup(titleBg, playBtn, creditsBtn) 
         startButtonListeners(‘add’) 
end 
function startButtonListeners(action) 
    if(action == ‘add’) then 
        playBtn:addEventListener(‘tap’, showGameView) 
        creditsBtn:addEventListener(‘tap’, showCredits) 
    else 
        playBtn:removeEventListener(‘tap’, showGameView) 
        creditsBtn:removeEventListener(‘tap’, showCredits) 
    end 
end 
function showCredits:tap(e) 
    playBtn.isVisible = false 
    creditsBtn.isVisible = false 
    creditsView = display.newImage(‘creditsView.png’) 
    transition.from(creditsView, {time = 300, x = -creditsView.width, onComplete = function() creditsView:addEventListener(‘tap’, hideCredits) creditsView.x = creditsView.x — 0.5 end}) 
end 
function hideCredits:tap(e) 
    playBtn.isVisible = true 
    creditsBtn.isVisible = true 
    transition.to(creditsView, {time = 300, x = -creditsView.width, onComplete = function() creditsView:removeEventListener(‘tap’, hideCredits) display.remove(creditsView) creditsView = nil end}) 
end 
function showGameView:tap(e) 
    transition.to(titleView, {time = 300, x = -titleView.height, onComplete = function() startButtonListeners(‘rmv’) display.remove(titleView) titleView = nil end}) 
    score = display.newText(‘0’ .. ‘/’ .. totalWorms, 58, 6, native.systemFontBold, 16) 
    score:setTextColor(238, 238, 238) 
    prepareWorms() 
end 
function prepareWorms() 
    w1 = display.newImage(‘worm.png’, 80.5, 11) 
    w2 = display.newImage(‘worm.png’, 198.5, 51) 
    w3 = display.newImage(‘worm.png’, 338.5, 34) 
    w4 = display.newImage(‘worm.png’, 70.5, 110) 
    w5 = display.newImage(‘worm.png’, 225.5, 136) 
    w6 = display.newImage(‘worm.png’, 376.5, 96) 
    w7 = display.newImage(‘worm.png’, 142.5, 211) 
    w8 = display.newImage(‘worm.png’, 356.5, 186) 
         worms = display.newGroup(w1, w2, w3, w4, w5, w6, w7, w8) 
         for i = 1, worms.numChildren do 
        worms[i]:addEventListener(‘tap’, wormHit) 
        worms[i].isVisible = false 
    end 
         startTimer() 
end 
 | 
В следующий раз…
В следующей и последней части серии мы рассмотрим анимацию червей, события касания, чтобы «поразить» червя, и последние шаги, которые необходимо предпринять перед выпуском приложения, такие как тестирование приложения, создание начального экрана, добавление значка. и, наконец, создание приложения. Оставайтесь с нами для финальной части!