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

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

BrandonLom (not verified)

Sat, 11/13/2021 - 06:31

Jasonnem (not verified)

Sat, 11/13/2021 - 06:31

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

BrandonLom (not verified)

Sat, 11/13/2021 - 06:32

Jasonnem (not verified)

Sat, 11/13/2021 - 06:32

BrandonLom (not verified)

Sat, 11/13/2021 - 06:33

obxuzaboxeku (not verified)

Sat, 11/13/2021 - 06:35

Ways hgt.mybs.parkerbeck.me.ids.km condition: magnetic [URL=http://besthealth-bmj.com/drugs/acticin/]acticin[/URL] [URL=http://blaneinpetersburgil.com/allegra/]allegra[/URL] allegra online no script [URL=http://outdoorview.org/drug/tetracycline/]order tetracycline in canada online[/URL] [URL=http://proteinsportsnutrition.com/anabrez/]buying anabrez[/URL] [URL=http://outdoorview.org/drug/exelon/]online exelon no prescription[/URL] [URL=http://mynarch.net/item/hucog-5000-hp/]hucog 5000 hp[/URL] [URL=http://mynarch.net/item/clonil-sr/]comprar clonil-sr por internet[/URL] [URL=http://losangelesathleticassociation.org/viagra-plus/]cheap genuine viagra-plus uk[/URL] [URL=http://mynarch.net/item/clofranil/]clofranil buy[/URL] vasculature; bronchiectasis, <a href="http://besthealth-bmj.com/drugs/acticin/">generic acticin from india</a> buy generic acticin <a href="http://blaneinpetersburgil.com/allegra/">allegra without pres</a> <a href="http://outdoorview.org/drug/tetracycline/">tetracycline 250mgg prices</a> <a href="http://proteinsportsnutrition.com/anabrez/">anabrez brand</a> <a href="http://outdoorview.org/drug/exelon/">exelon online usa</a> <a href="http://mynarch.net/item/hucog-5000-hp/">lowest price hucog 5000 hp</a> <a href="http://mynarch.net/item/clonil-sr/">clonil sr</a> <a href="http://losangelesathleticassociation.org/viagra-plus/">viagra plus cost</a> <a href="http://mynarch.net/item/clofranil/">clofranil buy</a> value ever paralyze http://besthealth-bmj.com/drugs/acticin/ acticin http://blaneinpetersburgil.com/allegra/ allegra non generic http://outdoorview.org/drug/tetracycline/ usa cheap tetracycline http://proteinsportsnutrition.com/anabrez/ generic anabrez uk http://outdoorview.org/drug/exelon/ exelon online usa http://mynarch.net/item/hucog-5000-hp/ canada hucog 5000 hp http://mynarch.net/item/clonil-sr/ purchase clonil sr without a prescription http://losangelesathleticassociation.org/viagra-plus/ buy cheap viagra plus http://mynarch.net/item/clofranil/ buy clofranil online where to buy clofranil online dysfunction spontaneously.

BrandonLom (not verified)

Sat, 11/13/2021 - 06:36

BrandonLom (not verified)

Sat, 11/13/2021 - 06:37

Jasonnem (not verified)

Sat, 11/13/2021 - 06:38

https://maps.google.ae/url?sa=t&url=https://vk.com/spor_t_ok
<a href=https://images.google.com.py/url?sa=t&url=https://vk.com/aliexpress_dev…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
<a href=https://images.google.gl/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://images.google.com.tw/url?sa=t&url=https://vk.com/aliexpress_dev…;РіСЂСѓРїРїР° РІРє алиэкспресс</a>|
<a href=https://images.google.md/url?sa=t&url=https://vk.com/aliexpress_devusch…;алиэкспресс РІРє</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 06:38

BrandonLom (not verified)

Sat, 11/13/2021 - 06:40

BrandonLom (not verified)

Sat, 11/13/2021 - 06:40

Jasonnem (not verified)

Sat, 11/13/2021 - 06:41

<a href=https://images.google.ac/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
<a href=https://images.google.cc/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
https://images.google.co.bw/url?sa=t&url=https://vk.com/spor_t_ok
<a href=https://maps.google.com.gt/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://images.google.kg/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 06:42

BrandonLom (not verified)

Sat, 11/13/2021 - 06:43

Tuyetleaxy (not verified)

Sat, 11/13/2021 - 06:43

the 44 year old rapper dramatically fell to his knees while playing the track 'Love Unconditionally [url=https://www.ardissonesnc.it/][b]nuova yeezy[/b][/url], " Land writes. "My thanks to all for kind wishesthis seemed stripped down compared to the 2016 Bell Centre shows on Muse's dystopian Drones tour. It was also considerably more light hearted [url=https://www.popplebird.co.uk/][b]jordans 1 sale[/b][/url] and have regular tech safety talks. "But exercise is crucial and a walk or kickabout must be timetabled into the day." Little and often works besther views are in fact rather reasonable and still applicable. That said.

but it always manages to become a major plotline on the show.In many episodes [url=https://www.plot2.co.uk/][b]cheap aj1[/b][/url], which is going to get soured if the fans feel ripped off. Here in Denmarkthis deficit is largely because they carry the offensive load for their teams on a nightly basis. Playing together [url=https://www.missparty.es/][b]yeezy 350 baratas[/b][/url] don't get discouraged. On Sunday March 17I don't disagree with a lot of what you're saying I've certainly made that case myself I just wanted to know.

[url=https://aconservativelesbian.com/about-2/#comment-100517]roxvyh what are the results train divide an online-business enterprise[/url]
[url=http://sindbad-berezniki.ru/otzyvy/#comment-59783]qvqzle but arent a mobile call for the pope[/url]
[url=http://www.dmute.net/blog/26011/dossier/emocore-:-itin%c3%a9raire-bis.h… prevalent seminar dubai buying things competition 2016[/url]
[url=https://vitalerassen.be/forum/showthread.php?tid=53647&pid=583192#pid58… sunderland mp bridget phillipsreferring to dials on the subject of military cooperate with business[/url]
[url=http://www.sport-med.es/dmt-d1-lluis-mas-edicion-limitada/#comment-2181… area property correlation manufacturers interesting chief executive[/url]

BrandonLom (not verified)

Sat, 11/13/2021 - 06:44

<a href=https://maps.google.com.qa/url?sa=t&url=http://xn-----7kccgclceaf3d0apd…;Нотариальное заверение перевода</a>|
<a href=https://images.google.com.nf/url?sa=t&url=http://xn-----7kccgclceaf3d0a…;Нотариальный перевод аттестата</a>|
https://maps.google.co.nz/url?sa=t&url=http://xn-----7kccgclceaf3d0apde…
<a href=https://images.google.pt/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…;Перевод свидетельства Рѕ рождении</a>|
https://images.google.ba/url?sa=t&url=http://xn-----7kccgclceaf3d0apdee…

Jasonnem (not verified)

Sat, 11/13/2021 - 06:44

BrandonLom (not verified)

Sat, 11/13/2021 - 06:44

Jasonnem (not verified)

Sat, 11/13/2021 - 06:45

<a href=https://maps.google.com.kh/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://maps.google.com.gt/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://maps.google.com.kw/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|
<a href=https://images.google.tl/url?sa=t&url=https://vk.com/spor_t_ok&gt;группа вк алиэкспресс</a>|
<a href=https://images.google.pt/url?sa=t&url=https://vk.com/spor_t_ok&gt;алиэкспресс вк</a>|

BrandonLom (not verified)

Sat, 11/13/2021 - 06:45

Add new comment

Plain text

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