Making a game with animation frames in Excel

Submitted by MisterBeck on Mon, 05/18/2020 - 14:24

Why might you make a game Excel? For learning and for fun. So let's get to it.

The Beginnings of a Game.

There are two Windows API functions we will use which make a game in Excel possible.

#If VBA7 Then
    '64 bit declares here
    Private Declare PtrSafe Function GetAsyncKeyState Lib "user32.dll" (ByVal nVirtKey As Long) As Integer
    Private Declare PtrSafe Function timeGetTime Lib "winmm.dll" () As Long
#Else
    '32 bit declares here
    Private Declare Function GetAsyncKeyState Lib "user32.dll" (ByVal nVirtKey As Long) As Integer
    Private Declare Function timeGetTime Lib "winmm.dll" () As Long
#End If

The GetAsyncKeySate will be for reading the keyboard inputs (Left, Right, Up, Down). timeGetTime will be used for the game counter to iterate frames. That's all you really need. Everything else can be down in VBA pure. Next we come to the game loop. It will be a Do Loop which will loop forever until we stop it and the game ends. Because this is a tight loop we need DoEvents to allow Excel to receive other commands and prevent the window from locking up.
 

Do
    DoEvents

    'Game code goes here.
Loop

 

Now we need a way to control and time updating the game state. timeGetTime is the answer. It returns the current time in milliseconds since boot time. The Do Loop will run continuously, and the if statement will continuously check the current time against the last frame's timestamp. When the current time exceeds the last frame time by a certain amountm the game "tick" over, update game the game state, and animate the next frame. I chose 50 milliseconds arbitrarily. Increasing or decreasing that value will decrease and increase the game's "clock speed."

'if time exceeds last time + gamespeed, then advance game by one and animate new frame.
If timeGetTime - lastFrameTime > 50 Then        
    'Game code goes here
End if


Now the game code itself. In this game, you control a black rectangle and move it around the screen using the arrow keys. Nice, right? Less of a game than Pong.

The game logic is very simple.

1) check if an arrow key is pressed.
2) if so, move a colored cell in that direction
3) repeat

To read the keystate, I'm using an enum in conjunction with GetAysyncKeyState like this.

Private Enum Direction
    None = 0
    Up = 1
    Down
    Left
    Right
End Enum

Private Function ReadDirectionKeyDown() As Direction
    ReadDirectionKeyDown = None

    If (GetAsyncKeyState(vbKeyUp) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Up
    ElseIf (GetAsyncKeyState(vbKeyDown) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Down
    ElseIf (GetAsyncKeyState(vbKeyRight) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Right
    ElseIf (GetAsyncKeyState(vbKeyLeft) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Left
    End If

End Function


Inside the game loop we have a Select Case for each direction, and an X,Y coordinates for the location of the colored cell. Simply update the the X and Y, color the new cell black, and color the previous cell white.

Dim D As Direction
D = ReadDirectionKeyDown
Select Case D
	Case Up
		Cells(y, x).Interior.ColorIndex = -4142
		y = y - 1
		Cells(y, x).Interior.ColorIndex = 1
	Case Down
		Cells(y, x).Interior.ColorIndex = -4142
		y = y + 1
		Cells(y, x).Interior.ColorIndex = 1
	Case Left
		Cells(y, x).Interior.ColorIndex = -4142
		x = x - 1
		Cells(y, x).Interior.ColorIndex = 1
	Case Right
		Cells(y, x).Interior.ColorIndex = -4142
		x = x + 1
		Cells(y, x).Interior.ColorIndex = 1
End Select

The End. You have a "game." Ok, not a full game, but you have a controllable character in a space. Here's the entire module.

Option Explicit
#If VBA7 Then
    '64 bit declares here
    Private Declare PtrSafe Function GetAsyncKeyState Lib "user32.dll" (ByVal nVirtKey As Long) As Integer
    Private Declare PtrSafe Function timeGetTime Lib "winmm.dll" () As Long
#Else
    '32 bit declares here
    Private Declare Function GetAsyncKeyState Lib "user32.dll" (ByVal nVirtKey As Long) As Integer
    Private Declare Function timeGetTime Lib "winmm.dll" () As Long
#End If


Private Const KEY_DOWN    As Integer = &H8000   'If the most significant bit is set, the key is down
Private Const KEY_PRESSED As Integer = &H1      'If the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState

Private Enum Direction
    None = 0
    Up = 1
    Down
    Left
    Right
End Enum

Private Function ReadDirectionKeyDown() As Direction
    ReadDirectionKeyDown = None

    If (GetAsyncKeyState(vbKeyUp) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Up
    ElseIf (GetAsyncKeyState(vbKeyDown) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Down
    ElseIf (GetAsyncKeyState(vbKeyRight) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Right
    ElseIf (GetAsyncKeyState(vbKeyLeft) And KEY_DOWN) = KEY_DOWN Then
        ReadDirectionKeyDown = Left
    End If

End Function


Sub Game()

    Dim x As Long
    Dim y As Long
        
    x = 3
    y = 8
    
    Dim lastFrameTime As Long
    lastFrameTime = timeGetTime     'start the tick counter
    
    Dim D As Direction
    
    Do
        DoEvents
        
        'if time exceeds last time + gamespeed, then advance game by one and animate new frame.
        If timeGetTime - lastFrameTime > 20 Then
            
            lastFrameTime = timeGetTime     'get current time and set to lastframe.
            
            'All game code goes here.
            '*********************************
            
            D = ReadDirectionKeyDown
            
            Select Case D
            
                Case Up
                    Cells(y, x).Interior.ColorIndex = -4142
                    y = y - 1
                    Cells(y, x).Interior.ColorIndex = 1
                Case Down
                    Cells(y, x).Interior.ColorIndex = -4142
                    y = y + 1
                    Cells(y, x).Interior.ColorIndex = 1
                Case Left
                    Cells(y, x).Interior.ColorIndex = -4142
                    x = x - 1
                    Cells(y, x).Interior.ColorIndex = 1
                Case Right
                    Cells(y, x).Interior.ColorIndex = -4142
                    x = x + 1
                    Cells(y, x).Interior.ColorIndex = 1
                
            End Select
            
            '*********************************
        End If
        
    Loop
    
End Sub

 

Comments

BrandonLom (not verified)

Sat, 11/13/2021 - 01:21

<a href=https://images.google.co.za/url?sa=t&url=http://xn-----7kccgclceaf3d0ap…;Переводчик Р±СЋСЂРѕ переводов</a>|
<a href=https://images.google.tm/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Бюро переводов</a>|
https://vn44.ru/site/away.html?url=http://xn-----7kccgclceaf3d0apdeeefr…
https://maps.google.com.ai/url?sa=t&url=http://xn-----7kccgclceaf3d0apd…
<a href=https://maps.google.co.vi/url?sa=t&url=http://xn-----7kccgclceaf3d0apde…;Юридический перевод</a>|

Jasonnem (not verified)

Sat, 11/13/2021 - 01:21

<a href=http://glazev.ru/redirect?url=https://vk.com/aliexpress_devuschkam&gt;алиэкспресс вк</a>|
https://maps.google.bg/url?sa=t&url=https://vk.com/aliexpress_devuschkam
<a href=https://images.google.co.nz/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://maps.google.co.ao/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
<a href=https://maps.google.com.et/url?sa=t&url=https://vk.com/aliexpress_devus…;алиэкспресс РІРє</a>|

Jasonnem (not verified)

Sat, 11/13/2021 - 01:22

<a href=https://716.kz/redirect?url=https://vk.com/aliexpress_devuschkam&gt;алиэкспресс вк</a>|
https://images.google.st/url?sa=t&url=https://vk.com/aliexpress_devusch…
<a href=https://maps.google.co.ma/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
<a href=https://images.google.hu/url?sa=t&url=https://vk.com/aliexpress_devusch…;алиэкспресс РІРє</a>|
<a href=https://images.google.co.kr/url?sa=t&url=https://vk.com/aliexpress_devu…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 01:23

Jasonnem (not verified)

Sat, 11/13/2021 - 01:24

BrandonLom (not verified)

Sat, 11/13/2021 - 01:24

<a href=https://images.google.mn/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Перевод документов Новокузнецк</a>|
http://delyagin.ru/redirect?url=http://xn-----7kccgclceaf3d0apdeeefre0d…
https://mineland.net/away.php?url=http://xn-----7kccgclceaf3d0apdeeefre…
<a href=https://images.google.ga/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Нотариальный перевод аттестата</a>|
<a href=https://images.google.be/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Резюме перевод РЅР° английский</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 01:25

Jasonnem (not verified)

Sat, 11/13/2021 - 01:26

<a href=https://maps.google.co.tz/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
<a href=https://images.google.com.pg/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
https://images.google.la/url?sa=t&url=https://vk.com/aliexpress_devusch…
<a href=https://maps.google.com.gh/url?sa=t&url=https://vk.com/aliexpress_devus…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
https://maps.google.com.bo/url?sa=t&url=https://vk.com/aliexpress_devus…

Jasonnem (not verified)

Sat, 11/13/2021 - 01:27

<a href=https://images.google.pl/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
https://images.google.com.nf/url?sa=t&url=https://vk.com/spor_t_ok
<a href=https://images.google.az/url?sa=t&url=https://vk.com/aliexpress_devusch…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
https://images.google.com.pk/url?sa=t&url=https://vk.com/spor_t_ok
<a href=http://gorodnews.ru/jumplink.php?url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 01:28

kyivarurakovi (not verified)

Sat, 11/13/2021 - 01:28

Some yvt.bkzr.parkerbeck.me.rnm.pn closes abciximab, explore [URL=http://proteinsportsnutrition.com/drugs/tastylia/ - generic tastylia lowest price[/URL - [URL=http://temeculapowdercoating.com/product/tenovate/ - non prescription tenovate[/URL - tenovate [URL=http://besthealth-bmj.com/product/super-levitra/ - super-levitra tablets online[/URL - [URL=http://thecluelessmomph.com/aurogra/ - aurogra cheap[/URL - [URL=http://mynarch.net/pill/premarin/ - premarin paid with paypal[/URL - [URL=http://medipursuit.com/lithobid/ - lithobid[/URL - [URL=http://kamo-family.com/tadarise-pro/ - tadarise pro capsules[/URL - [URL=http://besthealth-bmj.com/drugs/deltasone/ - deltasone[/URL - [URL=http://kamo-family.com/item/clenbuterol/ - low price clenbuterol[/URL - low price clenbuterol debulking bereaved, <a href="http://proteinsportsnutrition.com/drugs/tastylia/">tastylia without dr prescription usa</a> <a href="http://temeculapowdercoating.com/product/tenovate/">where can i purchase tenovate online</a> <a href="http://besthealth-bmj.com/product/super-levitra/">super levitra</a> <a href="http://thecluelessmomph.com/aurogra/">aurogra without a prescription</a> <a href="http://mynarch.net/pill/premarin/">buying premarin</a> <a href="http://medipursuit.com/lithobid/">lithobid</a&gt; <a href="http://kamo-family.com/tadarise-pro/">tadarise pro uk</a> order tadarise-pro today <a href="http://besthealth-bmj.com/drugs/deltasone/">deltasone</a&gt; <a href="http://kamo-family.com/item/clenbuterol/">clenbuterol</a&gt; reminded http://proteinsportsnutrition.com/drugs/tastylia/ tastylia http://temeculapowdercoating.com/product/tenovate/ buy tenovate in south africa online http://besthealth-bmj.com/product/super-levitra/ super-levitra sin receta espa?±a http://thecluelessmomph.com/aurogra/ aurogra cheap http://mynarch.net/pill/premarin/ premarin w/out pres http://medipursuit.com/lithobid/ lithobid.com http://kamo-family.com/tadarise-pro/ guaranteed lowest price on tadarise-pro http://besthealth-bmj.com/drugs/deltasone/ deltasone http://kamo-family.com/item/clenbuterol/ clenbuterol price walmart clenbuterol canada praevias potential convex secondary.

Jasonnem (not verified)

Sat, 11/13/2021 - 01:28

BrandonLom (not verified)

Sat, 11/13/2021 - 01:28

<a href=https://images.google.co.id/url?sa=t&url=http://xn-----7kccgclceaf3d0ap…;Медицинский перевод</a>|
<a href=https://100kursov.com/away/?url=http://xn-----7kccgclceaf3d0apdeeefre0d…;Нотариальный перевод аттестата</a>|
<a href=https://maps.google.co.th/url?sa=t&url=http://xn-----7kccgclceaf3d0apde…;Таможенный перевод</a>|
https://maps.google.ge/url?sa=t&url=http://xn-----7kccgclceaf3d0apdeeef…
https://solovei.info/url/?url=http://xn-----7kccgclceaf3d0apdeeefre0dt2…

BrandonLom (not verified)

Sat, 11/13/2021 - 01:29

Jasonnem (not verified)

Sat, 11/13/2021 - 01:29

BrandonLom (not verified)

Sat, 11/13/2021 - 01:30

<a href=https://images.google.ps/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Перевод справки</a>|
<a href=https://images.google.no/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Перевод трудовой книжки</a>|
<a href=https://images.google.bj/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Нотариальный перевод документов апостиль</a>|
http://www.vladinfo.ru/away.php?url=http://xn-----7kccgclceaf3d0apdeeef…
<a href=https://images.google.co.zm/url?sa=t&url=http://xn-----7kccgclceaf3d0ap…;Заверение печатью Р±СЋСЂРѕ переводов</a>|

Jasonnem (not verified)

Sat, 11/13/2021 - 01:31

<a href=https://images.google.ki/url?sa=t&url=https://vk.com/aliexpress_devusch…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
<a href=https://images.google.ac/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
<a href=https://maps.google.com.ua/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
https://images.google.com.mx/url?sa=t&url=https://vk.com/aliexpress_dev…
<a href=https://images.google.sr/url?sa=t&url=https://vk.com/aliexpress_devusch…;алиэкспресс РІРє</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 01:31

BrandonLom (not verified)

Sat, 11/13/2021 - 01:32

https://images.google.com.kh/url?sa=t&url=http://xn-----7kccgclceaf3d0a…
https://images.google.rs/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…
<a href=https://images.google.es/url?sa=t&url=https://www.instagram.com/buro_pe…;Перевод документов Новокузнецк</a>|
<a href=https://images.google.mu/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Перевод трудовой книжки</a>|
<a href=https://images.google.com.ph/url?sa=t&url=http://xn-----7kccgclceaf3d0a…;Технический перевод</a>|

Jasonnem (not verified)

Sat, 11/13/2021 - 01:32

BrandonLom (not verified)

Sat, 11/13/2021 - 01:32

akipeteakijj (not verified)

Sat, 11/13/2021 - 01:32

Malabsorption vvy.okjq.parkerbeck.me.kme.xa condition: <a href=http://christmastoysite.com/valproic-acid-er/>valproic acid er generic</a> <a href=http://yourbirthexperience.com/v-tada-super/>v tada super</a> <a href=http://agami360.com/pravachol/>pravachol</a&gt; purchase pravachol <a href=http://yourbirthexperience.com/hucog-2000-hp/>prices for hucog 2000 hp</a> <a href=http://altavillaspa.com/voveran-emulgel/>lowest price generic voveran emulgel</a> online generic voveran emulgel <a href=http://christmastoysite.com/melalong-ad-cream/>melalong ad cream</a> generic to melalong-ad-cream <a href=http://agami360.com/drugs/campicillin/>campicillin</a&gt; <a href=http://newyorksecuritylicense.com/s-citadep/>s citadep to buy</a> <a href=http://onlythedetails.com/frusenex/>cheap 100 frusenex</a> gamete, <a href="http://christmastoysite.com/valproic-acid-er/">on line valproic acid er</a> <a href="http://yourbirthexperience.com/v-tada-super/">generic v tada super from india</a> <a href="http://agami360.com/pravachol/">australian pravachol online</a> <a href="http://yourbirthexperience.com/hucog-2000-hp/">hucog 2000 hp buy online</a> <a href="http://altavillaspa.com/voveran-emulgel/">voveran emulgel</a> <a href="http://christmastoysite.com/melalong-ad-cream/">cheap melalong-ad-cream next day shipping</a> <a href="http://agami360.com/drugs/campicillin/">campicillin without prescription</a> <a href="http://newyorksecuritylicense.com/s-citadep/">s citadep</a> <a href="http://onlythedetails.com/frusenex/">frusenex en ligne</a> mapping http://christmastoysite.com/valproic-acid-er/ generic valproic acid er at walmart http://yourbirthexperience.com/v-tada-super/ v tada super without an rx http://agami360.com/pravachol/ purchase pravachol http://yourbirthexperience.com/hucog-2000-hp/ generic hucog 2000 hp lowest price http://altavillaspa.com/voveran-emulgel/ order voveran emulgel online http://christmastoysite.com/melalong-ad-cream/ melalong-ad-cream replica http://agami360.com/drugs/campicillin/ generic campicillin canada http://newyorksecuritylicense.com/s-citadep/ generic s citadep uk http://onlythedetails.com/frusenex/ frusenex 100 mg tablet initiative, fibrosis, occurs.

Jasonnem (not verified)

Sat, 11/13/2021 - 01:33

BrandonLom (not verified)

Sat, 11/13/2021 - 01:33

BrandonLom (not verified)

Sat, 11/13/2021 - 01:34

Jasonnem (not verified)

Sat, 11/13/2021 - 01:34

BrandonLom (not verified)

Sat, 11/13/2021 - 01:35

<a href=https://kirov-portal.ru/away.php?url=http://xn-----7kccgclceaf3d0apdeee…;Нотариальное заверение перевода</a>|
https://images.google.gr/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…
<a href=https://images.google.ae/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Печать перевод</a>|
https://images.google.com.gi/url?sa=t&url=http://xn-----7kccgclceaf3d0a…
<a href=https://maps.google.com.bh/url?sa=t&url=https://vk.com/perevod_s_italya…;Перевод СЃ итальянского РЅР° СЂСѓСЃСЃРєРёР№</a>|

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.