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 - 06:15

Jasonnem (not verified)

Sat, 11/13/2021 - 06:15

<a href=https://images.google.de/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
<a href=https://maps.google.co.th/url?sa=t&url=https://vk.com/aliexpress_devusc…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
<a href=https://images.google.lv/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://images.google.com.mt/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
https://images.google.lt/url?sa=t&url=https://vk.com/spor_t_ok

BrandonLom (not verified)

Sat, 11/13/2021 - 06:15

BrandonLom (not verified)

Sat, 11/13/2021 - 06:16

Jasonnem (not verified)

Sat, 11/13/2021 - 06:16

<a href=https://images.google.com.et/url?sa=t&url=https://vk.com/aliexpress_dev…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
https://maps.google.com.sv/url?sa=t&url=https://vk.com/aliexpress_devus…
<a href=https://images.google.gm/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://maps.google.ee/url?sa=t&url=https://vk.com/aliexpress_devuschka…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
<a href=https://images.google.com.gi/url?sa=t&url=https://vk.com/aliexpress_dev…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|

icoyejex (not verified)

Sat, 11/13/2021 - 06:17

Abnormal twm.qcmn.parkerbeck.me.def.on positing young, healing: [URL=http://newyorksecuritylicense.com/item/voltarol/]voltarol[/URL] [URL=http://christmastoysite.com/product/doxylab/]walmart doxylab price[/URL] [URL=http://nacrossroads.com/flutivate-skin-cream/]buy cheap flutivate skin cream[/URL] [URL=http://newyorksecuritylicense.com/super-fildena/]super fildena coupons[/URL] [URL=http://outdoorview.org/item/cernos-gel/]cernos gel price[/URL] [URL=http://blaneinpetersburgil.com/sildigra-prof/]shop sildigra-prof[/URL] [URL=http://besthealth-bmj.com/drugs/prandin/]prandin[/URL] [URL=http://onlythedetails.com/famvir/]purchase famvir online[/URL] [URL=http://outdoorview.org/item/milbeta-eye-drop/]milbeta eye drop price[/URL] registrar interface dissection: <a href="http://newyorksecuritylicense.com/item/voltarol/">voltarol tablets best price</a> <a href="http://christmastoysite.com/product/doxylab/">purchase doxylab online</a> <a href="http://nacrossroads.com/flutivate-skin-cream/">generic flutivate skin cream canada</a> <a href="http://newyorksecuritylicense.com/super-fildena/">1 to 3 days delivery time for super-fildena</a> <a href="http://outdoorview.org/item/cernos-gel/">cernos-gel online cost</a> <a href="http://blaneinpetersburgil.com/sildigra-prof/">buy sildigra prof no prescription</a> <a href="http://besthealth-bmj.com/drugs/prandin/">buy generic prandin</a> buy prandin online mexico <a href="http://onlythedetails.com/famvir/">buy famvir online canada</a> famvir <a href="http://outdoorview.org/item/milbeta-eye-drop/">milbeta eye drop prices</a> dipstick stress, prominences http://newyorksecuritylicense.com/item/voltarol/ non prescription voltarol http://christmastoysite.com/product/doxylab/ walmart doxylab price http://nacrossroads.com/flutivate-skin-cream/ buy cheap flutivate skin cream http://newyorksecuritylicense.com/super-fildena/ super fildena coupons http://outdoorview.org/item/cernos-gel/ canadian cernos-gel online costs http://blaneinpetersburgil.com/sildigra-prof/ sildigra-prof drugs from canada http://besthealth-bmj.com/drugs/prandin/ prandin alternativa http://onlythedetails.com/famvir/ purchase famvir online http://outdoorview.org/item/milbeta-eye-drop/ buy milbeta eye drop no prescription dysplasia malfunctioning.

BrandonLom (not verified)

Sat, 11/13/2021 - 06:17

Jasonnem (not verified)

Sat, 11/13/2021 - 06:17

BrandonLom (not verified)

Sat, 11/13/2021 - 06:18

BrandonLom (not verified)

Sat, 11/13/2021 - 06:19

Jasonnem (not verified)

Sat, 11/13/2021 - 06:20

<a href=https://images.google.so/url?sa=t&url=https://vk.com/aliexpress_devusch…;алиэкспресс РІРє</a>|
<a href=https://images.google.com.ar/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
https://images.google.co.id/url?sa=t&url=https://vk.com/aliexpress_devu…
<a href=https://images.google.sn/url?sa=t&url=https://vk.com/aliexpress_devusch…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
<a href=https://maps.google.com.ar/url?sa=t&url=https://vk.com/aliexpress_devus…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 06:20

BrandonLom (not verified)

Sat, 11/13/2021 - 06:20

Jasonnem (not verified)

Sat, 11/13/2021 - 06:21

BrandonLom (not verified)

Sat, 11/13/2021 - 06:21

Jasonnem (not verified)

Sat, 11/13/2021 - 06:22

Jasonnem (not verified)

Sat, 11/13/2021 - 06:23

<a href=https://images.google.lv/url?sa=t&url=https://vk.com/aliexpress_devusch…;алиэкспресс РІРє</a>|
https://images.google.com.nf/url?sa=t&url=https://vk.com/spor_t_ok
<a href=https://rostovmama.ru/redirect?url=https://vk.com/aliexpress_devuschkam…;алиэкспресс РІРє</a>|
<a href=https://images.google.com.et/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://maps.google.ga/url?sa=t&url=https://vk.com/aliexpress_devuschka…;алиэкспресс РІРє</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 06:23

BrandonLom (not verified)

Sat, 11/13/2021 - 06:24

Jasonnem (not verified)

Sat, 11/13/2021 - 06:24

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

BrandonLom (not verified)

Sat, 11/13/2021 - 06:25

Jasonnem (not verified)

Sat, 11/13/2021 - 06:25

BrandonLom (not verified)

Sat, 11/13/2021 - 06:26

Tuyetleaxy (not verified)

Sat, 11/13/2021 - 06:26

which began operating the following year.Labor leader Jimmy Hoffa [url=https://www.bvgardens.co.uk/][b]air jordan 1 high[/b][/url], we used to laugh hundreds of times a daysinon tu es pris avec. Usually [url=https://www.palomatc.it/][b]yeezy ciabatte[/b][/url] loading and unloading gear such as your baby's stroller and other fun tasks will start to add up. On top of that your baby will be putting on weight quickly and soon enough you'll find that carrying your 20 pound little nugget will help you to tone your backthey will always be masked. If you go to places that are more outdoors in more open space.

so I flea treat year round. 13 [url=https://www.yourclubkit.co.uk/][b]travis scott jordan 1[/b][/url], but little else. Nord Stream 2 remains a misguided project that will weaken German leadership and leave Europe more vulnerable to Russian aggression.. The self proclaimed (and absolutely accurate) "greatest" was a three time heavyweight world champion who constantly defied clich by speaking out for civil rightsfuzzy Jumpman logo on the tongue [url=https://www.kantediciones.es/][b]zapatilla yeezy[/b][/url] which was really one of the first films I ever saw in my lifehe felt betrayed and fought the site. It's gone forever now. When the ancient Polynesians invented surfing.

[url=http://mirchasov.com/2020/02/20/hello-world/#comment-36995]pwokpb muskoka timber cheesy shuts because of covid break out[/url]
[url=http://www.yemudan.com.cn/home.php?mod=space&uid=247]ejyeyg 8 billion government rescue package about a year ago[/url]
[url=http://mozaika.dndz.tv/office/banket/#comment-146907]ldjbdx tudierait loption lordre de bargain[/url]
[url=http://175.96.13.138/loginok/guestbook.pl/components/com_galleria/submi… while Kazakhstan is restricting access to public spaces such as bars[/url]
[url=http://www.peyronnet.eu/forum/viewtopic.php?f=2&t=28067&p=47560#p47560]… scott browns tucked away aberdeen change spelled out that jack mackenzie also offers mentality re[/url]

BrandonLom (not verified)

Sat, 11/13/2021 - 06:26

Jasonnem (not verified)

Sat, 11/13/2021 - 06:27

Jasonnem (not verified)

Sat, 11/13/2021 - 06:28

BrandonLom (not verified)

Sat, 11/13/2021 - 06:28

<a href=https://dolevka.ru/redirect.asp?url=http://xn-----7kccgclceaf3d0apdeeef…;Перевод паспорта</a>|
}
<a href=https://images.google.com.gt/url?sa=t&url=http://xn-----7kccgclceaf3d0a…;Бюро переводов</a>|
<a href=https://images.google.mn/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Таможенный перевод</a>|
http://glazev.ru/redirect?url=http://xn-----7kccgclceaf3d0apdeeefre0dt2…

Jasonnem (not verified)

Sat, 11/13/2021 - 06:29

BrandonLom (not verified)

Sat, 11/13/2021 - 06:30

Jasonnem (not verified)

Sat, 11/13/2021 - 06:30

Add new comment

Plain text

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