user5182412
user5182412

Reputation:

Screen not updated after N iterations

I run a very simple "Snake"-like game on my excel, which means I need the screen to be updated continuously, inside my main-while loop. The "snake" (a colored cell basically) is moving randomly within a 20x20 table.

It works well for several seconds, however, ay some point screen stops updating; ans excel stops responding, while still running the code. This leads to a crash.

I remplaced while loop with a For loop, which avoids crashing, but still, the screen stops updating until the loop is ended. When the loops stops, the screen is updated one last time. I also included "Sleep" statements after each function, however, this doesn't help. Here is the main code:

    Sub main()
    Dim table(20, 20) As Integer
    Dim index_move As Integer
    'Position class contains only X and Y parameters
    Dim index_actual_head_pos As Position 
    Set index_actual_head_pos = New Position

    Dim i As Long
    index_actual_head_pos.x = 5
    index_actual_head_pos.y = 15
    Application.ScreenUpdating = True

    For i = 1 To 50 'this remplaces the initial while loop
    'next line generates a random movement, bounded by a 20x20 matrix
    index_move = generer_movement(index_actual_head_pos)
    'next line updates the "snake" position params
    Call update_position(index_actual_head_pos, index_move)
    'next line deletes previous snake and draws a new one
    Call draw(index_actual_head_pos)
    Sleep (200)
    Next i
    End Sub

Please, note that the problem is really screen updating. As stated before, I don't know how to force excel to update screen continuously

Many thanks,

Denis

Upvotes: 1

Views: 219

Answers (1)

user4039065
user4039065

Reputation:

You should probably abandon that Sleep(200) and let the Excel application object do some processing for the 200 milli-seconds instead.

dim dTill as double   'should be at the top with the other var declarations

dtill = Timer + 0.200
do while timer < dTill and timer > 0.200: DoEvents: loop

The timer > 0.200 is important because Timer resets at midnight and you wouldn't want it to stall everything for 24 hours if you crossed midnight during that ¹⁄₅ second.

Upvotes: 1

Related Questions