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.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>
[url=http://www.bdranger.com/]bdranger[/url]

<a href="http://www.ncgrassfed.com/curry-sneakers-youth-blanc-obuvu">curry sneakers youth blanc</a> <a href="http://www.qubacafe.com/limited-customized-womens-jersey-baltimore-rave… customized womens jersey baltimore ravens road white nfl</a> <a href="http://www.sdadhd.com/2016-air-jordan-9-low-retro-pantone-newest-online… air jordan 9 low retro pantone newest online</a> <a href="http://www.zdarusa.com/texas-rangers-mlb-hat-for-uk-hato">texas rangers mlb hat for uk</a> <a href="http://www.galsing.com/2014-15-fc-bacelona-7-pedro-home-soccer-aaa--t-s… 15 fc bacelona 7 pedro home soccer aaa t shirt womens</a> <a href="http://www.ganenkou.com/adidas-nmd-r1-singapore-malaysia-scarpeuk">adid… nmd r1 singapore malaysia</a>
[url=http://www.crcfoods.com/]crcfoods[/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.biketw.com/]biketw[/url]

Kegankess (not verified)

Tue, 04/13/2021 - 09:08

Paul Bradley from Kansas City was looking for cheap best essay writing websites for school

Zakary Bird found the answer to a search query cheap best essay writing websites for school

<b><a href=https://essayerudite.com>cheap best essay writing websites for school</a></b>

<a href=https://essayerudite.com><img src="http://essayerudite.com/images/banner/500x500.jpg"></a&gt;

<a href=https://www.naijacore.com/memberlist.php?mode=viewprofile&u=557>business plan template engineering services</a>
<a href=https://www.html5videobank.com/community/showthread.php?tid=20355&pid=1… curriculum vitae ghostwriter for hire for school</a>
<a href=https://forum.lsbclan.net/index.php?topic=71845.new>buy cheap college essay on trump</a>
<a href=http://funrespawn.free.bg/cgi-php/phpbb3/memberlist.php?mode=viewprofil… essays online</a>
<a href=http://forumdearduino.com.br/phpBB3/memberlist.php?mode=viewprofile&u=7… typist resume</a>
<a href=http://pranavkikkerimusic.com/cgi-bin/forum/memberlist.php?mode=viewpro… and contrast essays</a>
<a href=http://forum.dphen.com/memberlist.php?mode=viewprofile&u=1019>coursewor… software</a>
<a href=https://granttrainingcenter.com/forum/memberlist.php?mode=viewprofile&u… application personal essay format</a>
<a href=http://thecoachchat.com/memberlist.php?mode=viewprofile&u=4295>business plan sample sandwich shop</a>
<a href=http://www.wenyifeiyan.com/home.php?mod=space&uid=109232>compare and contrast poetry essay layout</a>
<a href=http://107.170.174.203/index.php?action=profile;u=245>custom article review editing website for university</a>
<a href=http://www.musslima.org/forum/member.php?u=7158>cheap course work ghostwriters service for masters</a>
<a href=http://www.pajaritoflyingclub.com/forum/memberlist.php?mode=viewprofile… film studies content</a>
<a href=http://weebbun.com/showthread.php?tid=75435>cheap annotated bibliography writers services for college</a>
<a href=http://forum-hd.com/viewtopic.php?f=158&t=277088&p=382158#p382158>chiro… business plan template</a>
<a href=http://lzx.lezaizhuan.com/space-uid-2447515.html>cover letter goals objectives</a>
<a href=http://www.driverconnection.net/forums/viewtopic.php?pid=232393#p232393… english as second language argumentative essay</a>
<a href=https://teikalamata.gr/showthread.php/43832-essay-on-inductive-and-dedu… proofreading website au</a>
<a href=http://alwasa6h.com/vb/showthread.php?p=198598&posted=1#post198598>cons… on the revolutionary war selected essays</a>
<a href=https://www.snpo.org/directory/directoryapplication.php>cover letter mutual contact example</a>
<a href=http://theorie-spatiale.fr/forum/memberlist.php?mode=viewprofile&u=371>… assignment ghostwriter services usa</a>

Davinpymn (not verified)

Tue, 04/13/2021 - 09:08

Terrence Duncan from Green Bay was looking for customer satisfaction research paper

Spencer Fisher found the answer to a search query customer satisfaction research paper

<b><a href=https://essayerudite.com>customer satisfaction research paper</a></b>

<a href=https://essayerudite.com><img src="http://essayerudite.com/images/banner/500x500.jpg"></a&gt;

esl critical essay writing website usa, esl thesis writing service usadissertation abstracts international part b science and engineeringdo my esl expository essay on hillary clintoneasy classification essaycustom critical analysis essay editing for hire for college. <a href=http://138.201.138.240/>customer support director resume</a> discursive essay on human cloning, customer satisfaction research paper esl dissertation abstract editing for hire gb.
esl creative essay ghostwriters website cacustom university paper. esl creative essay writers website for mba esl critical analysis essay ghostwriting services.
custom literature review editor for hire usa. <a href=https://brodzio.pl/forum/showthread.php?tid=694923>dissertation infections from spitting</a>, definitional essay examplecustom dissertation conclusion editor site for collegecustom university essay ghostwriter website onlineesl persuasive essay writers websites us. early childhood special education teacher resume sample custom masters research paper assistance!
dream essay introduction <a href=https://essayerudite.com/dissertation-writing-service/>dissertation writing assistance</a>, custom movie review writers sitesesl personal statement writers websites for schooldo you indent on a cover letteresl research proposal writers site for masters? custom dissertation editing sites gb, custom critical thinking editing for hire uk.
do my sociology case studydissertation topics for psychologyeducation pros cons of homework. <a href=http://digital-tacho.eu/forum/showthread.php?tid=91991>custom masters essay proofreading site uk</a> esl academic essay writer service for mbadissertation introduction writers service. dissertation proposal editing services online, customer satisfaction research paper do not go gentle into that good night analysis essays.
esl cv editor services ukdo math problems online. esl blog writers services for school <a href=https://essayerudite.com>custom essay writing</a> custom home work writers websites us.
custom college essay proofreading for hire usa <a href=https://ultimatedunitedbrothersclub.com/index.php?topic=159772.new#new>… thesis statement ghostwriters for hire for mba</a>, eric ogilvy resumedissertation hypothesis editor service caesl persuasive essay writer service uk. employee essay privacy right, esl paper writers site usa.
descriptive essay rubric - middle schoolengineering college admissions essay https://essayerudite.com customer satisfaction research paper and english war poetry coursework, custom rhetorical analysis essay editing services for school.
esl creative writing editor site for universitydescriptive essay about my living roomesl book review proofreading service for masters. custom mba dissertation chapter examples, <a href=https://essayerudite.com/correct-my-essay/>correct my essay</a>, esl personal statement editor services for phd

<a href="http://www.betterdot.net/ua-clutchfit-drive-low-schwarz-butye">ua clutchfit drive low schwarz</a> <a href="http://www.saveorpave.com/janoski-grey-black-billig-runsm">janoski grey black billig</a> <a href="http://www.cakesvb.com/nike-magista-obra-netshoes-reviews-billig-zapato… magista obra netshoes reviews billig</a> <a href="http://www.cosasco.net/nike-sb-team-edition-hvit-svart-gum-schoenenuk">… sb team edition hvit svart gum</a> <a href="http://www.knopfbar.com/mens-2015-nike-nfl-detroit-lions-t-shirts-49-nf… 2015 nike nfl detroit lions t shirts 49</a> <a href="http://www.truemailer.net/mens-kansas-city-royals-25-kendrys-morales-kc… kansas city royals 25 kendrys morales kc blue alternate baseball jersey with 2015 world series patch</a>
[url=http://www.madeonearth.net/]madeonearth[/url]

<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>
[url=http://www.qubacafe.com/]qubacafe[/url]

<a href="http://www.biketw.com/jordan-retro-12-white-black-taxi-red-for-cheap-sc… retro 12 white black taxi red for cheap</a> <a href="http://www.bslatkin.net/nike-philadelphia-eagles-92-reggie-white-black-… philadelphia eagles 92 reggie white black alternate mens stitched nfl new elite jersey</a> <a href="http://www.cironajle.com/nike-stefan-janoski-max-blu-gituttio-zapatosca… stefan janoski max blu gituttio</a> <a href="http://www.timeforart.net/adidas-superstar-1-cielo-azul-trainersca">adi… superstar 1 cielo azul</a> <a href="http://www.modelspro.net/47-brand-rams-hat-for-cheap-headgearl">47 brand rams hat for cheap</a> <a href="http://www.qubacafe.com/nike-huarache-free-run---mens-skode">nike huarache free run - mens</a>
[url=http://www.trialsuk.net/]trialsuk[/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.