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

<a href="http://www.carefactor.net/limited-dee-ford-womens-jersey-kansas-city-ch… dee ford womens jersey kansas city chiefs 55 home red nfl</a> <a href="http://www.masterpharm.net/all-gray-nike-free-2012-mens-shoes-billig-tr… gray nike free 2012 mens shoes billig</a> <a href="http://www.klaava.net/nike-air-max-thea-gold-billig-scarpech">nike air max thea gold billig</a> <a href="http://www.micksanders.net/adidas-nemeziz-17.1-ag-mint-green-shoes-on-s… nemeziz 17.1 ag mint green shoes on sale</a> <a href="http://www.markderry.net/miami-dolphins-flex-fit-hats-handl">miami dolphins flex fit hats</a> <a href="http://www.sanjosedj.net/nike-air-max-vapormax-boys-billig-chaussuresc"… air max vapormax boys billig</a>
bocksberg http://www.bocksberg.com/

randbsolutions (not verified)

Fri, 07/02/2021 - 07:03

In reply to by Ammie (not verified)

<a href="http://www.chapacms.com/nike-internationalist-nero-trainers-asos-booto"… internationalist nero trainers asos</a> <a href="http://www.nuevavista.net/elite-ryan-mathews-youth-jersey-philadelphia-… ryan mathews youth jersey philadelphia eagles 24 drift fashion midnight green nfl</a> <a href="http://www.barimar.net/nike-flyknit-chukka-blanc-or-runningcc">nike flyknit chukka blanc or</a> <a href="http://www.bdranger.com/price-air-force-1-billig-zapatosm">price air force 1 billig</a> <a href="http://www.efthimiades.com/adidas-superstar-slip-on-all-white-shoes-bil… superstar slip on all white shoes billig</a> <a href="http://www.headhonchos.net/elite-kyle-orton-mens-jersey-dallas-cowboys-… kyle orton mens jersey dallas cowboys 18 road white nfl</a>
randbsolutions http://www.randbsolutions.net/

peggymeyerdds (not verified)

Mon, 07/05/2021 - 06:52

In reply to by Ammie (not verified)

<a href="http://www.coolrvpro.com/nike-air-force-1-low-grey-hvid-chaussuresc">ni… air force 1 low grey hvid</a> <a href="http://www.learnstar.net/toddler-philadelphia-eagles-98-connor-barwin-m… philadelphia eagles 98 connor barwin midnight green team color nfl nike jersey</a> <a href="http://www.gilpininc.net/air-max-97-lx-on-feet-billig-zapatosc">air max 97 lx on feet billig</a> <a href="http://www.petrefuge.net/royal-blue-washington-nationals-hat-xl-handf">… blue washington nationals hat xl</a> <a href="http://www.csgdata.net/nike-air-yeezy-sort-green-red-shoessk">nike air yeezy sort green red</a> <a href="http://www.veofilm.net/red-sox-hat-camo-capc">red sox hat camo</a>
cellofire http://www.cellofire.net/

<a href="http://www.eatngo.net/spain-red-grey-air-jordan-12-shoes-billig-running… red grey air jordan 12 shoes billig</a> <a href="http://www.mohawarean.com/2013-super-bowl-new-nfl-jerseys-san-francisco… super bowl new nfl jerseys san francisco 49ers 99 aldon smith white jerseys limited with hall of fame 50th patch jerseys</a> <a href="http://www.longhornsup.com/adidas-ultra-boost-clima-95-billig-scarpeuk"… ultra boost clima 95 billig</a> <a href="http://www.rootlaw.net/air-jordan-future-jimmy-jazz-runninges">air jordan future jimmy jazz</a> <a href="http://www.einspurauto.com/nike-magista-obra-2013-dailymotion-billig-ru… magista obra 2013 dailymotion billig</a> <a href="http://www.tomboone.net/toddler-carolina-panthers-jersey-dressb">toddler carolina panthers jersey</a>
danbloom http://www.danbloom.net/

<a href="http://www.betterdot.net/men-nike-new-orleans-saints-41-roman-harper-el… nike new orleans saints 41 roman harper elite black team color nfl jersey sale</a> <a href="http://www.saveorpave.com/black-and-brown-fake-yeezy-boost-350-v2-scarp… and brown fake yeezy boost 350 v2</a> <a href="http://www.cakesvb.com/nike-running-long-sleeve-top-womens-polos">nike running long sleeve top womens</a> <a href="http://www.cosasco.net/2012-new-nfl-jerseys-buffalo-bills-22-fred-jacks… new nfl jerseys buffalo bills 22 fred jackson blue limited jerseys</a> <a href="http://www.knopfbar.com/uk-purple-shoes-nike-air-max-90-sp-chaussuresl"… purple shoes nike air max 90 sp</a> <a href="http://www.truemailer.net/nike-blazer-mid-metric-royal-rojo-trainersuk"… blazer mid metric royal rojo</a>
ypnathens http://www.ypnathens.com/

<a href="http://www.fosback.net/nike-hypervenom-phinish-leather-fg-review-billig… hypervenom phinish leather fg review billig</a> <a href="http://www.fswriting.com/how-to-lace-air-jordan-6-black-infrared-obuvla… to lace air jordan 6 black infrared</a> <a href="http://www.hapustahl.net/chicago-blackhawks-65-andrew-shaw-2015-stanley… blackhawks 65 andrew shaw 2015 stanley cup white kids jersey</a> <a href="http://www.fcpswcs.com/nike-roshe-run-olive-guld-schoenenfr">nike roshe run olive guld</a> <a href="http://www.thevoliste.net/nike-air-lava-dome-2.4-black-and-grey-running… air lava dome 2.4 black and grey</a> <a href="http://www.trialsuk.net/nike-running-shoes-cheap-all-grey-shoes-running… running shoes cheap all grey shoes</a>
hapustahl http://www.hapustahl.net/

<a href="http://www.baharanit.net/air-jordan-6-rings-black-shoes-for-discount-sc… jordan 6 rings black shoes for discount</a> <a href="http://www.etuevt.com/women-air-jordan-11-black-gold-shoes-on-sale-bill… air jordan 11 black gold shoes on sale billig</a> <a href="http://www.corsicactus.com/nike-womens-free-3.0-v4-blue-grey-yellow-bil… womens free 3.0 v4 blue grey yellow billig</a> <a href="http://www.sarahtkaye.net/nike-air-force-1-low-supreme-year-of-the-drag… air force 1 low supreme year of the dragon billig</a> <a href="http://www.consival.com/jordan-1-black-and-pink-for-cheap-schuheuk">jor… 1 black and pink for cheap</a> <a href="http://www.metrofoods.net/redskins-winter-hat-for-eu-hands">redskins winter hat for eu</a>
freedomrvwi http://www.freedomrvwi.net/

<a href="http://www.betterdot.net/nhl-jerseys-vancouver-canucks-16-trevor-linden… jerseys vancouver canucks 16 trevor linden blue third with 2011 stanley cup jerseys</a> <a href="http://www.saveorpave.com/adidas-yeezy-boost-350-price-retail-sneakerit… yeezy boost 350 price retail</a> <a href="http://www.cakesvb.com/nike-free-5.0-ebay-womens-billig-chaussuresz">ni… free 5.0 ebay womens billig</a> <a href="http://www.cosasco.net/nike-air-presto-blanc-pure-platinum-trainersuk">… air presto blanc pure platinum</a> <a href="http://www.knopfbar.com/new-jordan-super-fly-5-black-white-shoes-billig… jordan super fly 5 black white shoes billig</a> <a href="http://www.truemailer.net/diy-air-force-1-billig-schoenenau">diy air force 1 billig</a>
billgood http://www.billgood.net/

<a href="http://www.biketw.com/nike-air-max-97-womens-uk-billig-runsc">nike air max 97 womens uk billig</a> <a href="http://www.saunasmith.com/adidas-equipment-eqt-support-boost-up-billig-… equipment eqt support boost up billig</a> <a href="http://www.cironajle.com/black-chicago-bulls-snapback-for-sale-capb">bl… chicago bulls snapback for sale</a> <a href="http://www.stephenemay.com/air-jordan-6-30th-anniversary-booto">air jordan 6 30th anniversary</a> <a href="http://www.qubacafe.com/mitchell-and-ness-philadelphia-eagles-reggie-wh… and ness philadelphia eagles reggie white 92 green authentic jersey sale</a> <a href="http://www.sdadhd.com/create-your-own-soccer-uniform-nfld">create your own soccer uniform</a>
mvaesthetic http://www.mvaesthetic.com/

Add new comment

Plain text

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