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

Johnniecheep (not verified)

Sat, 06/12/2021 - 08:11

2837 просмотровРади устранения проблем, связанных с опасностью чтобы здоровья людей, мокрый, худой атмосфера повинен выводиться наружу и заменяться свежим. Такую пристройку к стандартной кабине обычно устанавливают для коммерческие автомобили малой и средней грузоподъемности. Коли водитель не реагирует на данные запросы, порядок с помощью соответствующих средств автоматически переводит транспортное лекарство в порядок минимального риска. Связка агрегатирования с орудиями комплектуется сообразно требованию заказчика. У каждого уписывать приманка достоинства и ограничения сообразно применению. Производители спецтехникиОсушение воздуха
<a href=https://tss123.ru/catalog>оказание услуг спецтехники</a>
[url=https://tss123.ru/catalog/arenda-spetstekhniki/avtokrany]аренда автокрана 32[/url]
https://tss123.ru/catalog/inertnye-materialy/shcheben - щебень 20 40 цена за 1 м3

Особая разновидность – узкопроходные штабелеры. Максимальная ширина посередине спальника – 1950 мм, и здесь удачно вписана «постель» длиной 1880 мм. Зачастую это сложный дело – единственно для составление свода правил ради системы экстренного торможения в грузовиках потребовалось едва три года. В первую вошли факторы точный канцерогенные, во вторую – потенциально канцерогенные чтобы человека, в третью – факторы, которые временно не могут являться классифицированы с точки зрения их канцерогенности для человека, в четвертую – безопасные ради здоровья человека. Эта отличие вызвана тем, сколько подвод трубопроводов присутствие двухэтапном монтаже непременно принужден подводиться к внутреннему блоку слева. Например, некоторый сельхозпроизводители отказываются через дорогостоящей реконструкции мехтоков. Только они возникают. Очищение воздуха необходимо людям, страдающим от аллергий. Свободно покупать дорогую технику, поскольку тариф обслуживания может позже вырасти. Стандартный доверие не длится более двух-трех лет. В-третьих, убедитесь, сколько вы используете термостат эффективно. Этот процесс лежит в основе работы любого кондиционера и не зависит от его типа, модели иначе производителя. и крутящим моментом 1645/2219 Нм при 2000/1400 об/мин;0 комментариевСпальник «Луидор-Тюнинг» изнутри утеплен монтажной пеной (за исключением задней стенки). Следовательно в разница от других игроков рынка мы не стремимся угощать прорывные технические решения в надежде, который когда-нибудь они получат законодательную основу. Поэтому вид, сообразно которой перемещается штабелер, должна быть ровной и жесткой. У компании лакомиться шеренга патентов, одиноко из которых — уникальная порядок стабилизации заднего моста. Для того, для претендовать на получение кредита в банке, нуждаться предоставить определенное обеспечение. Монтаж и установка наружной рекламы никак не обходится без автовышки09.08.2021

vndlipas (not verified)

Sat, 06/12/2021 - 08:16

azixisetuz (not verified)

Sat, 06/12/2021 - 08:17

Timing pwf.icnl.parkerbeck.me.gdy.jz transfusion [URL=http://aawaaart.com/buy-propecia-w-not-prescription/ - buy propecia w not prescription[/URL - [URL=http://graphicatx.com/item/kemadrin/ - online kemadrin without prescription paypal[/URL - [URL=http://a1sewcraft.com/item/viagra/ - cheap viagra pills[/URL - [URL=http://pukaschoolinc.com/xenical/ - xenical sale now buy cheap[/URL - [URL=http://davincipictures.com/product/buy-cialis-online-cheap/ - buy cialis online germany[/URL - [URL=http://thesteki.com/item/lasix-com-lowest-price/ - buy lasix mexico[/URL - [URL=http://themusicianschoice.net/generic-prednisone-canada-pharmacy/ - prednisone buy in canada[/URL - [URL=http://otrmatters.com/item/clomid-nl/ - acheter du clomid en suisse[/URL - [URL=http://gaiaenergysystems.com/viagra/ - cheap viagra[/URL - viagra [URL=http://creativejamaicans.com/benadryl-online/ - benadryl pills[/URL - [URL=http://recipiy.com/viagra-lowest-price/ - viagra lowest price[/URL - [URL=http://eyogsupplements.com/item/viagra/ - viagra[/URL - [URL=http://nutrabeautynutrition.com/pill/ortho-tri-cyclen/ - ortho tri cyclen without dr prescription[/URL - [URL=http://elearning101.org/propecia-brand/ - propecia brand[/URL - [URL=http://thesteki.com/doxycycline/ - discount doxycycline perscription drug[/URL - cheap doxycycline glossitis, malabsorption; skills <a href="http://aawaaart.com/buy-propecia-w-not-prescription/">buy propecia w not prescription</a> <a href="http://graphicatx.com/item/kemadrin/">kemadrin texas</a> <a href="http://a1sewcraft.com/item/viagra/">discount viagra</a> <a href="http://pukaschoolinc.com/xenical/">achat xenical 120</a> <a href="http://davincipictures.com/product/buy-cialis-online-cheap/">generic 10mg cialis cheapest prices</a> genuine cialis for cheap <a href="http://thesteki.com/item/lasix-com-lowest-price/">lasix lowest price</a> lasix lowest price <a href="http://themusicianschoice.net/generic-prednisone-canada-pharmacy/">www…; <a href="http://otrmatters.com/item/clomid-nl/">acheter du clomid en suisse</a> <a href="http://gaiaenergysystems.com/viagra/">www.viagra.com</a&gt; <a href="http://creativejamaicans.com/benadryl-online/">discount benadryl</a> <a href="http://recipiy.com/viagra-lowest-price/">viagra on line</a> <a href="http://eyogsupplements.com/item/viagra/">walmart viagra price</a> buying viagra <a href="http://nutrabeautynutrition.com/pill/ortho-tri-cyclen/">ortho tri cyclen</a> <a href="http://elearning101.org/propecia-brand/">propecia</a&gt; <a href="http://thesteki.com/doxycycline/">doxycycline</a&gt; land http://aawaaart.com/buy-propecia-w-not-prescription/ buy propecia w not prescription http://graphicatx.com/item/kemadrin/ vente kemadrin belgique http://a1sewcraft.com/item/viagra/ subaction showcomments viagra thanks remember http://pukaschoolinc.com/xenical/ australia buy xenical http://davincipictures.com/product/buy-cialis-online-cheap/ cialis prices buy cialis online cheap http://thesteki.com/item/lasix-com-lowest-price/ india tadalafil 100mg http://themusicianschoice.net/generic-prednisone-canada-pharmacy/ prednisone without a prescription www.prednisone.com http://otrmatters.com/item/clomid-nl/ clomid without a percription acheter du clomid en suisse http://gaiaenergysystems.com/viagra/ viagra http://creativejamaicans.com/benadryl-online/ benadryl benadryl http://recipiy.com/viagra-lowest-price/ viagra online no script http://eyogsupplements.com/item/viagra/ viagra viagra from canada http://nutrabeautynutrition.com/pill/ortho-tri-cyclen/ canada ortho tri cyclen http://elearning101.org/propecia-brand/ propecia lowest price for propecia http://thesteki.com/doxycycline/ doxycycline doxycycline prices purposeful acknowledging public.

vndlipas (not verified)

Sat, 06/12/2021 - 08:26

vndlipas (not verified)

Sat, 06/12/2021 - 08:26

vndlipas (not verified)

Sat, 06/12/2021 - 08:28

vndlipas (not verified)

Sat, 06/12/2021 - 08:29

vndlipas (not verified)

Sat, 06/12/2021 - 08:31

eyegavifo (not verified)

Sat, 06/12/2021 - 08:32

A bah.qwah.parkerbeck.me.ige.yr unattributable unemployment slurring [URL=http://eatingaftergastricbypass.net/lasix-coupons/]online lasix no prescription[/URL] lasix [URL=http://themusicianschoice.net/drug/buying-hydroxychloroquine/]best canadian pharmacy to buy hydroxychloroquine[/URL] lowest price on generic hydroxychloroquine [URL=http://otrmatters.com/lowest-tadalafil-price/]lowest tadalafil price[/URL] [URL=http://aawaaart.com/product/levitra/]purchase levitra online[/URL] lowest price for levitra [URL=http://elearning101.org/vidalista/]prices for vidalista[/URL] [URL=http://thesteki.com/vidalista-brand/]vidalista brand[/URL] [URL=http://elearning101.org/item/cialis/]non prescription cialis[/URL] [URL=http://iliannloeb.com/product/pharmacy/]pharmacy without a doctor[/URL] [URL=http://healthkosh.com/product/kamagra/]buy kamagra sydney[/URL] [URL=http://elearning101.org/item/nizagara/]nizagara pharmacy canada[/URL] [URL=http://frankfortamerican.com/flagyl/]metronidazole 500mg antibiotic[/URL] [URL=http://gaiaenergysystems.com/tadalafil/]tadalafil[/URL] [URL=http://eatingaftergastricbypass.net/item/online-generic-hydroxychloroqu… generic hydroxychloroquine[/URL] [URL=http://themusicianschoice.net/drug/cialis/]cialis cost[/URL] [URL=http://mrcpromotions.com/priligy/]overnight priligy canada[/URL] priligy pharmacy canada unvalidated <a href="http://eatingaftergastricbypass.net/lasix-coupons/">order lasix online in us</a> lasix online pharmacy <a href="http://themusicianschoice.net/drug/buying-hydroxychloroquine/">most reliable site to buy hydroxychloroquine</a> <a href="http://otrmatters.com/lowest-tadalafil-price/">comprare tadalafil farmacia</a> <a href="http://aawaaart.com/product/levitra/">levitra best price usa</a> <a href="http://elearning101.org/vidalista/">vidalista 40mg tablets price</a> <a href="http://thesteki.com/vidalista-brand/">vidalista</a&gt; vidalista from india <a href="http://elearning101.org/item/cialis/">buying cialis</a> no prescription cialis <a href="http://iliannloeb.com/product/pharmacy/">pharmacy</a&gt; <a href="http://healthkosh.com/product/kamagra/">buy kamagra sydney</a> <a href="http://elearning101.org/item/nizagara/">canada nizagara</a> <a href="http://frankfortamerican.com/flagyl/">buy flagyl</a> buy flagyl <a href="http://gaiaenergysystems.com/tadalafil/">tadalafil sur le net</a> <a href="http://eatingaftergastricbypass.net/item/online-generic-hydroxychloroqu… hydroxychloroquine</a> <a href="http://themusicianschoice.net/drug/cialis/">price of cialis</a> <a href="http://mrcpromotions.com/priligy/">generico priligy</a> epilepsy, internet non-invasive http://eatingaftergastricbypass.net/lasix-coupons/ buy lasix in uk online lasix http://themusicianschoice.net/drug/buying-hydroxychloroquine/ lowest price on generic hydroxychloroquine hydroxychloroquine generic canada http://otrmatters.com/lowest-tadalafil-price/ lowest tadalafil price http://aawaaart.com/product/levitra/ levitra best price usa http://elearning101.org/vidalista/ vidalista 10 achat http://thesteki.com/vidalista-brand/ generic vidalista from canada http://elearning101.org/item/cialis/ cialis http://iliannloeb.com/product/pharmacy/ generico pharmacy barato http://healthkosh.com/product/kamagra/ kamagra http://elearning101.org/item/nizagara/ nizagara price at walmart http://frankfortamerican.com/flagyl/ metronidazole online http://gaiaenergysystems.com/tadalafil/ united states tadalafil http://eatingaftergastricbypass.net/item/online-generic-hydroxychloroqu… buy hydroxychloroquine online http://themusicianschoice.net/drug/cialis/ cialis commercial http://mrcpromotions.com/priligy/ priligy opioids arabinoside.

vndlipas (not verified)

Sat, 06/12/2021 - 08:35

Add new comment

Plain text

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