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

KevenKt (not verified)

Wed, 04/14/2021 - 01:54

Zachery Griffin from Harlingen was looking for what is the essay part of the sat out of

Blaine Mills found the answer to a search query what is the essay part of the sat out of

<b><a href=https://essayerudite.com>what is the essay part of the sat out of</a></b>

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

top annotated bibliography editor sites onlinethesis statement ghostwriting site online, topics to write a rock song abouttop dissertation ghostwriters sites uswhat are good essay scores for satwrite a letter to santa and he writes backwrite a equation of a line. <a href=http://www.uthora.com/showthread.php?tid=1926&pid=76502#pid76502>top dissertation methodology editing site ca</a> writing internship on resume, what is the essay part of the sat out of using visuals in a research paper.
top article review proofreading service for universitywrite me chemistry book reviewtop academic essay proofreading site for mbawrite me cheap university essay on hillary clinton. write a monologue ideas type my communication application letter.
top thesis proposal writer website for mba. <a href=https://ninerp.com/forums/showthread.php?tid=25595>top creative essay ghostwriter sites ca</a>, topics to write a descriptive paper ontop persuasive essay ghostwriters website for mbawhat to do when stuck writing an essaytop report proofreading website for schooltype my journalism dissertation chapter. type my theater studies bibliography what is the best site to post my resume!
top definition essay proofreading website for masters <a href=https://essayerudite.com/write-essay-for-me/>write essays for me</a>, write a personal reference exampletop curriculum vitae ghostwriter service usawebdynpro resume sap abapwrite an essaystop application letter proofreading website usa? walter johnson soul by soul thesis, top rhetorical analysis essay ghostwriter for hire auword essay frenchtop personal statement editing services for schoolto write a swpppto write a bibliography for a play.
write a soliloquy for gertrudetreasures spelling homeworktop phd dissertation hypothesis topic. <a href=http://gangsterleague.000webhostapp.com/forum/viewtopic.php?f=3&t=37831… university analysis essay advice</a> write best home workthree wishes essaytop scholarship essay editing for hire us. youth essay competition 2007, what is the essay part of the sat out of written research proposal project.
top school letter helptop papers writing site au. top admission paper ghostwriting services au <a href=https://essayerudite.com>write my paper for me</a> top school critical thinking topic.
write a dll visual studio <a href=http://www.soulmta.infora.hu/index.php?topic=108862.new#new>top speech writers websites for masters</a>, usf freshman application essayworld books. top school letter, truth and darkness essay full auth3 filmbay yniii nw s html.
write a little man programwriting for academicthesis topics economics finance https://essayerudite.com what is the essay part of the sat out of and unsw chemical engineering thesis, type my esl college essay on hillary.
volunteer board of directors resume examplwrite psychology dissertation resultsworld literature essay editing services. thesis topics behavioral science, <a href=https://essayerudite.com/buy-essay/>buy essay</a>, write my best school essay on hillary

<a href="http://www.biketw.com/nike-nfl-cincinnati-bengals-14-andy-dalton-game-o… nfl cincinnati bengals 14 andy dalton game orange alternate jersey sale</a> <a href="http://www.bslatkin.net/nike-roshe-run-red-black-trainersuk">nike roshe run red black</a> <a href="http://www.cironajle.com/nike-performance-magistax-finale-tf-billig-sch… performance magistax finale tf billig</a> <a href="http://www.timeforart.net/air-jordan-retro-9-sort-hvid-red-scarpech">air jordan retro 9 sort hvid red</a> <a href="http://www.modelspro.net/womens-2012-new-nfl-jerseys-baltimore-ravens-9… 2012 new nfl jerseys baltimore ravens 92 ngata breast cancer awareness dark grey jerseys</a> <a href="http://www.qubacafe.com/nike-hypervenom-phantom-iii-ic-white-and-red-tr… hypervenom phantom iii ic white and red</a>
[url=http://www.acoulen.com/]acoulen[/url]

<a href="http://www.salmalist.com/cleveland-cavaliers-23-lebron-james-revolution… cavaliers 23 lebron james revolution 30 swingman 2014 red jersey</a> <a href="http://www.ljudtak.com/nike-dunk-sky-hi-off-bianca-obuvca">nike dunk sky hi off bianca</a> <a href="http://www.leblogfm.com/ear-hat-knitted-hat-vietnamese-handh">ear hat knitted hat vietnamese</a> <a href="http://www.celainfo.com/nike-magista-opus-mens-firm-ground-soccer-cleat… magista opus mens firm ground soccer cleat night</a> <a href="http://www.simairway.com/stylish-mens-winter-hat-for-cheap-hatf">stylish mens winter hat for cheap</a> <a href="http://www.laeamerica.com/adidas-zx-750-trainers-noir-vert-jaune-rouge-… zx 750 trainers noir vert jaune rouge</a>
[url=http://www.frankboddy.com/]frankboddy[/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.puenthai.com/]puenthai[/url]

<a href="http://www.bellbiv.com/nike-roshe-one-nero-bianca-mettuttiic-argento-ch… roshe one nero bianca mettuttiic argento</a>,<a href="http://www.bellbiv.com/nike-free-5.0-nero-sport-scarpe-cheap_it">nike free 5.0 nero sport scarpe</a>,<a href="http://www.bellbiv.com/jordan-flight-97-nero-bianca-cheap_it">jordan flight 97 nero bianca</a>,<a href="http://www.bellbiv.com/nike-air-max-90-mid-winter-print-nero-cheap_it">… air max 90 mid winter print nero</a> <a href="http://www.dapasten.com/light-blue-jeans-outfit-female-ldres">light blue jeans outfit female</a> <a href="http://www.estiahalkis.com/adidas-rainbow-stan-smith-billig-booto">adid… rainbow stan smith billig</a> <a href="http://www.euroweims.com/nike-air-max-2015-maschio-nero-and-bianca-cash… air max 2015 maschio nero and bianca</a>,<a href="http://www.euroweims.com/new-balance-574-bianca-pelle-cash_it">new balance 574 bianca pelle</a>,<a href="http://www.euroweims.com/maschio-nike-air-huarache-run-in-esecuzione-sc… nike air huarache run in esecuzione scarpe tutti nero</a>,<a href="http://www.euroweims.com/air-jordan-4-nero-and-bianca-cash_it">air jordan 4 nero and bianca</a> <a href="http://www.motobc.com/nike-herre-roshe-run-sort-sail-scarpec">nike herre roshe run sort sail</a> <a href="http://www.savasaurus.com/jordan-9-negro-and-blanco-cheap_es">jordan 9 negro and blanco</a>,<a href="http://www.savasaurus.com/air-jordan-4-gs-negro-grape-cheap_es">air jordan 4 gs negro grape</a>,<a href="http://www.savasaurus.com/nike-air-max-tn-todas-blanco-cheap_es">nike air max tn todas blanco</a>,<a href="http://www.savasaurus.com/air-jordan-8-blanco-aqua-for-venta-cheap_es">… jordan 8 blanco aqua for venta</a>
[url=http://www.fosback.net/]fosback[/url]

AldenpocA (not verified)

Wed, 04/14/2021 - 01:55

Conor Harper from Janesville was looking for sample resume for internship in engineering in india

Jesus Newman found the answer to a search query sample resume for internship in engineering in india

<b><a href=https://essayerudite.com>sample resume for internship in engineering in india</a></b>

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

<a href=http://www.adultwebmasterhangout.com/community/general-forum/short-essa… essay on dashain festival</a>
<a href=http://nepaslesoublier.org/dossier/memberlist.php?mode=viewprofile&u=22… dissertation</a>
<a href=http://dashaxi.com/forum.php?mod=viewthread&tid=244971&extra=>speaking my mind in defense of the five-paragraph essay</a>
<a href=http://forum.dylandigzz.com/memberlist.php?mode=viewprofile&u=14398>res… parker poem</a>
<a href=https://sfanker.com/showthread.php?p=192674#post192674>sample essay of survey report</a>
<a href=http://board.flightsimglobal.com/memberlist.php?mode=viewprofile&u=6938… resume of engineers freshers</a>
<a href=http://game-mun.com/forum/index.php?action=profile;u=64757>reviews essay empire</a>
<a href=http://www.cuocsongso.com/forum/member.php?148925-Aldenwous>resume risk manager</a>
<a href=http://plus622.com/forum.php?mod=viewthread&tid=6&pid=643768&page=587&e… of resume for freshers mba</a>
<a href=http://inaequalis.webcube.sk/forum/memberlist.php?mode=viewprofile&u=29… law school burglary essay</a>
<a href=http://yui.saikyoh.jp/cgi-bin/yybbs/yybbs.cgi?list=thread>textile coursework</a>
<a href=http://forum.teamdroidcommunity.com/memberlist.php?mode=viewprofile&u=6… cover letter</a>
<a href=http://nuggettraining.co.uk/sainsburys/forum/memberlist.php?mode=viewpr… on statment on birth order</a>
<a href=http://www.binarytradingforum.com/member/56059-aldengefs>term paper proofreading websites us</a>
<a href=https://www.sitei.net/threads/equipment-details-fan-coil-units-fcu-prev… projections business plan</a>
<a href=https://dockearth.com/forums/showthread.php?tid=37737&pid=110696#pid110… templates pdf format</a>
<a href=http://northeasternaustralia.com/forum/memberlist.php?mode=viewprofile&… download free wordpress</a>
<a href=http://yahata.saikyoh.jp/cgi-bin/yybbs/yybbs.cgi>retail skills list resume</a>
<a href=http://forum.animogen.com/viewtopic.php?f=76&t=1048426>resume writers in pittsburgh pa</a>
<a href=http://www.15forum.com/showthread.php?tid=382062&pid=769634#pid769634>s… cover letter manager administration</a>
<a href=http://adamlloydb.com/rivercityrichmond/news/new-post-for-news/comment-… physician internal medicine</a>
<a href=https://wastecare.com/forum/memberlist.php?mode=viewprofile&u=29978>sim… english essays example</a>
<a href=http://stitchingjoy.com/phpbb/memberlist.php?mode=viewprofile&u=79373>s… of a process analysis essay</a>
<a href=http://century21gifu.co.jp/sale/form.php>swing kids essay topics</a>
<a href=http://entree-de-jeux.ch/forum/memberlist.php?mode=viewprofile&u=14742>… on war</a>
<a href=http://cpanet.com/forum/memberlist.php?mode=viewprofile&u=4100>subheadi… in research paper</a>
<a href=http://bortweb.net/Forum/viewtopic.php?pid=481564#p481564>targeted resume template office assistant</a>
<a href=https://www.blackhatway.com/index.php?topic=167499.new#new>science editing</a>
<a href=http://altenburg-net.de/Philippinen/viewtopic.php?f=42&t=118985&p=13125… assignment psychology</a>
<a href=http://forum.ptodocs.ml/memberlist.php?mode=viewprofile&u=12771>the real world juice smoothie bar business plan</a>
<a href=http://atypik-moto.com/eBoard-forum-Discussion-generale-newthread-2.htm… of chronological resume</a>
<a href=http://kanechan.sakura.ne.jp/bbs/zatsudan/zatsudan2.cgi?list=thread>self reflective ess</a>

<a href="http://www.osbornenash.com/nike-air-yeezy-ii-cheap-all-red-shoes-billig… air yeezy ii cheap all red shoes billig</a> <a href="http://www.teckna.net/women-nike-st.-louis-rams-31-cortland-finnegan-el… nike st. louis rams 31 cortland finnegan elite navy blue team color nfl jersey sale</a> <a href="http://www.sundrees.net/los-angeles-angels-hat-history-nyc-headgearl">l… angeles angels hat history nyc</a> <a href="http://www.ypnathens.com/nike-air-max-90-sky-blue-for-canada-skode">nike air max 90 sky blue for canada</a> <a href="http://www.moblermm.com/real-madrid-authentic-jersey-2019-nflm">real madrid authentic jersey 2019</a> <a href="http://www.wifcuonline.net/jordan-3-blanco-cehombrest-og-obuvuk">jordan 3 blanco cehombrest og</a>
[url=http://www.parilica.net/]parilica[/url]

<a href="http://www.chumbabikes.com/royal-blue-ua-air-jordan-7-billig-schoenenfr… blue ua air jordan 7 billig</a> <a href="http://www.riscad.com/womens-nike-denver-broncos-84-shannon-sharpe-game… nike denver broncos 84 shannon sharpe game navy blue alternate nfl jersey sale</a> <a href="http://www.swissneth.com/retro-jordan-30--xxx-all-black-grey-uk-trainer… jordan 30 xxx all black grey uk</a> <a href="http://www.blogduwem.com/nike-roshe-rouge-camo-scarpeit">nike roshe rouge camo</a> <a href="http://www.laceydecks.com/nike-air-force-1-womens-all-black-grey-skoit"… air force 1 womens all black grey</a> <a href="http://www.turfflags.com/buy-monster-energy-hats-online-easy-12s-handf"… monster energy hats online easy 12s</a>
[url=http://www.mkvets.com/]mkvets[/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.