There are 2 streams that draw 2 cars on the console and imitate their movement.

The machine “Enemy” descends from above, and the player must bypass it. Object rendering is done through lock .

The problem is that when I need to “slow down” the player’s machine, then moving it to the left to the right will also slow down (it shouldn’t be your idea). The speed is implemented as a time adjustment Thread.Sleep(int delta) .

Tell me, please, possible solutions to this problem.

  • As I understand it, the stream that is responsible for the movement of the player’s object always works, which is not necessary, it may be worth making it through the event and locking it only if an event occurs? - Mikhail Znak
  • there is a good book about how to write games gameprogrammingpatterns.com/contents.html - Mikhail Vaysman
  • @Mikhail Vaysman so far everything is done solely for the sake of practice, I think the link will be useful, but later - Mikhail Znak
  • @Mikhail Vaysman can point out more precisely which of the patterns? - Mikhail Znak

1 answer 1

The idea of ​​running the logic of different objects in different threads, and hoping for the scheduler to speed up and slow down, does not seem good to me. In the end, the transfer of control to another thread is not guaranteed. (Well, this solution obviously does not scale in the case when there are a lot of objects, but this is already a technical detail.)

I would do it differently: I would introduce a coordinating class that would take turns asking the objects to make their own “move” and took care of the necessary delay (for example, by polling the speed of the objects). With this design, everything runs in one thread, and the coordinator plays the role of a scheduler.

  • 1. Is it possible to achieve such an effect (when the speed is slowed down, not to lose the player's “maneuverability”) with several streams? (I can achieve the desired effect, but there is a problem with drawing, it starts to draw and erase the figures incorrectly). 2. If you use your advice, it is not quite clear to me what it is different from — making your “move” - from the same method with lock and why the delay in single-threaded mode will not slow down 2 objects? If it is easy to describe, please, describe the scheme in more detail - Mikhail Znak
  • @MikhailZnak: (1) Probably possible, but this is not quite the right way, so problems will still come out from time to time. (Well, I don’t know how you draw the figures.) - VladD
  • @MikhailZnak: (2) The difference is that you use the real timer as your game time timer, and hope that the “moves” (that is, the iterations of your cycle in each of the streams) will be executed in parallel. For the case when you count the moves manually in one stream, you are guaranteed the order of status updates and do not need synchronization. And still it is not necessary to do drawing in another stream, because there is only one stream. - VladD