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.dapasten.com/white-sox-hat-with-chicago-flag-2017-hands">whi… sox hat with chicago flag 2017</a> <a href="http://www.nanopose.com/2012-new-nfl-jerseys-san-francisco-49ers-23-lam… new nfl jerseys san francisco 49ers 23 lamichael james lights out black elite jerseys</a> <a href="http://www.carasello.com/air-jordan-11-retro-low-georgetown-grey-mist-o… jordan 11 retro low georgetown grey mist</a> <a href="http://www.ladagebeheer.com/toronto-blue-jays-5-panel-hat-linux-handc">… blue jays 5 panel hat linux</a> <a href="http://www.evestips.com/how-many-years-did-michael-jordan-play-sneakerl… many years did michael jordan play</a> <a href="http://www.blusealdoors.com/49ers-new-hats-hato">49ers new hats</a>
[url=http://www.fibuilders.com/]fibuilders[/url]

<a href="http://www.fieldnfab.net/nike-elastico-turf-blue-zapatosfr">nike elastico turf blue</a> <a href="http://www.toruseurope.com/blue-white-under-armour-fat-tire-schuheca">b… white under armour fat tire</a> <a href="http://www.mkvets.com/2013-super-bowl-new-nfl-jerseys-baltimore-ravens-… super bowl new nfl jerseys baltimore ravens 52 ray lewis elite black jerseys with baltimore ravens art patch</a> <a href="http://www.vonbredow.net/ben-roethlisberger-autographed-helmet-for-chea… roethlisberger autographed helmet for cheap</a> <a href="http://www.crozetrose.com/all-white-adidas-superstar-suede-billig-chaus… white adidas superstar suede billig</a> <a href="http://www.wislabs.net/all-white-red-under-armour-curry-3zero-australia… white red under armour curry 3zero australia shoes billig</a>
[url=http://www.freedomrvwi.net/]freedomrvwi[/url]

<a href="http://www.docinsider.net/kansas-city-royals-sky-blue-hat-reviews-handd… city royals sky blue hat reviews</a> <a href="http://www.fotowerft.net/black-and-white-air-jordan-10-shoes-spain-scho… and white air jordan 10 shoes spain</a> <a href="http://www.brassmedia.net/unmatched-jonathan-weeks-jersey-houston-texan… jonathan weeks jersey houston texans 46 men white game jersey nike nfl jersey sale</a> <a href="http://www.sagerllp.net/black-white-red-jordan-super.fly-4-for-uk-billi… white red jordan super.fly 4 for uk billig</a> <a href="http://www.gastropol.net/nike-air-max-90-sort-wolf-grey-sneakerit">nike air max 90 sort wolf grey</a> <a href="http://www.sweetpee.net/ny-hat-grey-hatl">ny hat grey</a>
[url=http://www.laceydecks.com/]laceydecks[/url]

<a href="http://www.aviurban.net/nike-air-max-classic-sale-billig-schoenenfr">ni… air max classic sale billig</a> <a href="http://www.coolrvpro.com/youth-nike-tennessee-titans-78-leger-douzable-… nike tennessee titans 78 leger douzable limited navy blue alternate nfl jersey sale</a> <a href="http://www.loveliteuk.com/maria-sharapova-tennis-dress-ldred">maria sharapova tennis dress</a> <a href="http://www.actisia.net/nike-air-max-98-size-4-billig-runningcc">nike air max 98 size 4 billig</a> <a href="http://www.londonbery.com/los-angeles-dodgers-fitted-hats-reviews-capd"… angeles dodgers fitted hats reviews</a> <a href="http://www.petrefuge.net/all-grey-new-nike-air-max-billig-scarpedk">all grey new nike air max billig</a>
[url=http://www.mcarta.net/]mcarta[/url]

<a href="http://www.motobc.com/red-jacquizz-rodgers-youth-jersey-nfl-atlanta-fal… jacquizz rodgers youth jersey nfl atlanta falcons 32 elite home jerseys</a> <a href="http://www.cavalangue.com/nike-air-presto-men-navy-white-ii-shoes-runsm… air presto men navy white ii shoes</a> <a href="http://www.paradopolis.com/elite-brad-wing-womens-jersey-pittsburgh-ste… brad wing womens jersey pittsburgh steelers 9 home black nfl</a> <a href="http://www.ppmataro.com/nike-lunarestoa-cool-grey-out-boot0">nike lunarestoa cool grey out</a> <a href="http://www.refbdc.com/cleaning-north-face-down-jacket-northfacec">clean… north face down jacket</a> <a href="http://www.eddmtogo.com/oakland-athletics-baseball-cap-rate-map-handi">… athletics baseball cap rate map</a>
[url=http://www.mfaads.com/]mfaads[/url]

<a href="http://www.motobc.com/red-jacquizz-rodgers-youth-jersey-nfl-atlanta-fal… jacquizz rodgers youth jersey nfl atlanta falcons 32 elite home jerseys</a> <a href="http://www.cavalangue.com/nike-air-presto-men-navy-white-ii-shoes-runsm… air presto men navy white ii shoes</a> <a href="http://www.paradopolis.com/elite-brad-wing-womens-jersey-pittsburgh-ste… brad wing womens jersey pittsburgh steelers 9 home black nfl</a> <a href="http://www.ppmataro.com/nike-lunarestoa-cool-grey-out-boot0">nike lunarestoa cool grey out</a> <a href="http://www.refbdc.com/cleaning-north-face-down-jacket-northfacec">clean… north face down jacket</a> <a href="http://www.eddmtogo.com/oakland-athletics-baseball-cap-rate-map-handi">… athletics baseball cap rate map</a>
[url=http://www.billsodds.com/]billsodds[/url]

<a href="http://www.samsunlobe.com/curry-2.5-basketballe-runst">curry 2.5 basketballe</a> <a href="http://www.bucuburger.com/game-robert-ayers-mens-jersey-new-york-giants… robert ayers mens jersey new york giants 91 home royal blue nfl</a> <a href="http://www.eurorumo.com/elite-zach-fulton-womens-jersey-kansas-city-chi… zach fulton womens jersey kansas city chiefs 73 home red nfl</a> <a href="http://www.thpcstore.com/boston-red-sox-mlb-hat-key-capr">boston red sox mlb hat key</a> <a href="http://www.sinspi.com/nike-philadelphia-eagles-7-ron-jaworski-white-eli… philadelphia eagles 7 ron jaworski white elite jersey</a> <a href="http://www.ekytalk.com/men-nike-cardinals-76-mike-iupati-red-team-color… nike cardinals 76 mike iupati red team color nfl vapor untouchable limited jersey</a>
[url=http://www.aptarismrm.com/]aptarismrm[/url]

<a href="http://www.liverachies.com/nike-mercurial-superfly-nz-billig-runninges"… mercurial superfly nz billig</a> <a href="http://www.nolteknows.com/game-antrel-rolle-youth-jersey-new-york-giant… antrel rolle youth jersey new york giants 26 road white nfl</a> <a href="http://www.chumbabikes.com/black-red-white-lebron-e.e-uk-shoes-scarpeuk… red white lebron e.e uk shoes</a> <a href="http://www.kamelefon.com/game-brandon-mcmanus-mens-jersey-denver-bronco… brandon mcmanus mens jersey denver broncos 8 home orange super bowl 50 bound nfl</a> <a href="http://www.riscad.com/nike-magista-opus-wolf-grey-sg-08-boote">nike magista opus wolf grey sg 08</a> <a href="http://www.swissneth.com/adidas-yeezy-boost-350-perfect-replica-billig-… yeezy boost 350 perfect replica billig</a>
[url=http://www.mmmeliacakes.com/]mmmeliacakes[/url]

Add new comment

Plain text

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