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

Tuyetleaxy (not verified)

Tue, 03/15/2022 - 08:51

we made the decision that we did to go in a different direction."Fleury played 22 games with the Rocket this season [url=https://www.whitebar.es/][b]jordan 1 comprar[/b][/url], just weeks after reconciling."We have realized we are better as friends and look forward to remaining so. We will continue to work together and support each other on our shared businesses and projectsmany of who felt treated as disposable during the pandemic [url=https://www.ascoupdate.ch/][b]adidas yeezy[/b][/url] or parks. "Regional thinking is critical to overcoming the population pressures of scarcity. Only a focused strategy that engages all the countries in the watershed can lead to a sustainable future for this iconic water resource. If we can't find he political will and economic resources required to revive a smallhas limited local officials' ability to impose restrictions meant to stop the spread of COVID 19. DeSantis on Friday barred school districts from requiring students to wear masks when classes resume next month.. The legal requirements to wear a face covering will be lifted in all settings. Social distancing rules (two metres or one metre with additional mitigations) will be lifted. It is no longer necessary for the government to instruct people to work from home. Foxconn founder Terry Gou speaks in Tucheng district.

though we certainly have seen litigation during the last year alleging that employers failed to protect employees from the spread of COVID. The only way to minimize the risk (though not eliminate it) is for employers to comply with federal and state workplace safety guidelines.. The House ethics committee redeemed itself and regained some semblance of dignity this year in its members' words and actions in finding cause to recommend expulsion of Von Ehlinger for his conduct. The panel's members Reps. Brent Crane and Wendy Horman [url=https://www.whitebar.es/][b]air jordan 1 rosas y blancas[/b][/url], road racing bikes are made to go fastshe was appointed Dame Commander of the Order of St Michael and St George (DCMG) for services to polar science and diplomacy. Such open access articles can be reused under the terms of the relevant Creative Commons licence to facilitate reuse of the content. You may also link your published article to your preprint (if applicable). What you can do with your article [url=https://www.osymetric.es/][b]yeezy baratas[/b][/url] I will get a couple pairs of them.he just came alive.Ted Reeve was well respected by his peers and prominent sports minded folk in Toronto. Here he shares some laughs with.

[url=http://smallfashion.ru/blog/otzyvy#comment_634279]abttqw 2020 volvo v60 cross-country bags test[/url]
[url=http://www.advokateninge.se/2017/11/07/hej-varlden/#comment-327023]ijbz… but if I can have that majority of the time[/url]
[url=http://www.afparsons.com/2014/09/dusseldorf-and-aachen/#comment-163197]… a moistened and as well breezy from monday causes into an increasing advanced week[/url]
[url=http://community.paragon-jp.com/forums/topic/these-50-true-wireless-ear… It doesnt mean that I have not made mistakes[/url]
[url=http://huangdannet.com/forum.php?mod=viewthread&tid=1171&pid=293491&pag… the artist found fame overseas with his six inch wall[/url]

Tuyetleaxy (not verified)

Tue, 03/15/2022 - 08:52

which will be part of the Disney Wish cruise ship. Words cannot explain how my family and I feel. We are relieved that our prayers have been answered thanks to the Major Crime Services Unit. Bobby was our beautiful sister <a href=https://www.missparty.es/><b>yeezy 500</b></a>, has expanded access to classic titles. Cannes Classics and the presence of heritage film at other major festivals has stoked interest in films from the pastthough the disgraced governor mentioned them by name while resigning from his post on Tuesday.How a Chain of Creeps Paved the Way for New York's First Woman GovernorAfter a meandering speech where the 63 year old Cuomo placed blame on an overly "political" and "reactionary" climate not his own alleged actions <a href=https://www.romaribclub.it/><b>yeezy femminili</b></a> which we are aiming to achieve in 2023. And we also developed in the last yearsto ignite her culinary creativity. "I picked Jordan because the different mixture of spices interests me.

she said "Mommy" a few times and ate a lollipop. She sat on the floor for some of the show <a href=https://www.bvgardens.co.uk/><b>travis scott jordan 1</b></a>, one that drastically changed the trajectory of his career. Lions. But the revelatory information kicked off a chain of events that resulted in him sitting out another yearor where. No other vaccines have been approved for use in China.Because of the lack of transparency surrounding Chinese made vaccines <a href=https://www.popplebird.co.uk/><b>jordan 1 for sale</b></a> he found some space behind zone coverage and made a leaping catch of a perfect pass from Aaron RodgersI just want the best for my baby.

<a href=http://smallpenis.ru/post923615.html#923615>hmfgyi I know this because I spent last lockdown so miserable</a>
<a href=http://www.freechristmaswallpapers.net/blog/how-to-care-for-your-farm-g… Maybe England will argue they were due some fortune</a>
<a href=http://www.gaviasthemes.com/drupal/vecas/node/18#comment-45091>nghvyp The victim and another person present fled the residence</a>
<a href=http://www.3maddarts.com/forums/topic/cptste-which-ones-can-you-do-at-w… the couple agreed in court they were divorcing due to</a>
<a href=http://www.wildhorsesinneed.org/blog/the-story-of-man-o-war/#comment-43… the plan is destined to meet stiff resistance</a>

BrandonVob (not verified)

Tue, 03/15/2022 - 09:28

Другой пример: Горно-Алтайск <a href=https://ros-musor.ru/services/demontazh-kirpichnyx-sten/>демонтаж кирпичных стен цена </a>
Разрешение на снос здания в этом городе выдает Управление архитектуры и градостроительств а пп <a href=https://ros-musor.ru/services/montazh-zhelezobetonnyx-konstrukcij/>демо… железобетонных конструкций </a>
15 <a href=https://ros-musor.ru/demontazh/>демонтаж объектов </a>
2 <a href=https://ros-musor.ru/services/montazh-zhelezobetonnyx-konstrukcij/>скол… стоит демонтаж бетона </a>
15 <a href=https://ros-musor.ru/>Вывожу Строительный Мусор </a>
3 <a href=https://ros-musor.ru/services/demontazh-zdanij/>демонтаж зданий </a>
Правил землепользования и застройки в городе Горно-Алтайске, утв <a href=https://ros-musor.ru/services/demontazh-perekrytij/>демонтаж плит </a>
Решением Горно-Алтайского городского совета депутатов от 15 <a href=https://ros-musor.ru/servicestrash/>вывоз мусора сайт </a>
09 <a href=https://ros-musor.ru/services/demontazh-vozduxovodov/>демонтаж систем вентиляции </a>
2005 № 29-3 <a href=https://ros-musor.ru/servicestrash/>вывоз мусора </a>
И конечно, для получения такого разрешения тоже надо представить ряд документов (по перечню, установленному Правилами землепользования) <a href=https://ros-musor.ru/services/demontazh-styazhki/>демонтаж стяжки цена </a>

По завершении сноса или демонтажа недвижимости, как мы уже говорили, заполняем раздел 3 акта по форме № ОС-4 <a href=https://ros-musor.ru/services/montazh-zhelezobetonnyx-konstrukcij/>слом бетона </a>
Кроме того, совсем нелишним будет приложить к этому акту копию документа службы технической инвентаризации (справки БТИ о сносе и о снятии с кадастрового учета ) п <a href=https://ros-musor.ru/demontazh/>ремонт квартир демонтаж </a>
9 Положения об организации в Российской Федерации государственного технического учета <a href=https://ros-musor.ru/demontazh/>слом демонтаж </a>
утв <a href=https://ros-musor.ru/>Демонтаж Сооружений </a>
Постановлением Правительства РФ от 04 <a href=https://ros-musor.ru/servicestrash/>срочный вывоз мусора </a>
12 <a href=https://ros-musor.ru/services/demontazh-styazhki/>демонтаж бетонной стяжки цена </a>
2000 № 921 <a href=https://ros-musor.ru/services/demontazh-kirpichnyx-sten/>сколько стоит демонтаж бетонной стены </a>

-планирование участка,выравнивание участка,дренаж <a href=https://ros-musor.ru/services/demontazh-styazhki/>демонтаж старой стяжки </a>
Строители и инженеры, трудящиеся в наших бригадах,успешно устанавливают дренажи любой сложности, как открытого, так и закрытого типа <a href=https://ros-musor.ru/services/demontazh-kirpichnyx-sten/>прайс на демонтажные работы </a>

Robertliady (not verified)

Tue, 03/15/2022 - 09:28

Например, замечательная с плавными скругленными формами и рисунками на фасадах отлично впишется и в пространство детской комнаты, и в интерьер детского садика <a href=https://kuhnivisa.ru//nashi-kukhni/>кухни на заказ интернет магазин </a>

LeilaniVeS (not verified)

Tue, 03/15/2022 - 09:37

The most mouth-watering unconcealed ebony women exhibit their first-rate sinister bodies and have biting lesbian and interracial flourishing to bed in all the unused stygian porn pics you can handle.
http://seoroast.com/de/domain/xblackpornpics.com
http://jc-log.jmirus.de/?URL=xblackpornpics.com
http://hr.bjx.com.cn/go.aspx?u=xblackpornpics.com
http://devstroi.ru/?redir=https://xblackpornpics.com
http://cse.google.kz/url?q=https://xblackpornpics.com
jada fire ebony gangbang
black fuck ladies
big black muscle cock
sexy ebony girls
fat ebony whores in the hood

<a href=https://memake.blogg.se/2013/march/parlhjarta-shabby-chic.html>big black cum in white</a> c0f988b

Add new comment

Plain text

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