Лучший способ реализовать игровое воспроизведение?

Вы можете пройти через последовательность с желаемыми смещениями, используйте itertools, чтобы сгладить обратно в одномерный список.

>>> import itertools
>>> d =  ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
>>> list(itertools.chain.from_iterable([d[::3], d[1::3], d[2::3]]))
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']

Вы также можете сделать что-то подобное, используя numpy, изменив форму массива, транспонировав, затем снова сплюснув

>>> import numpy as np
>>> d =  np.array(['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'])
>>> np.reshape(d, (d.size//3, 3)).T.flatten()
array(['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3'], dtype='<U2')
11
задан Lucky 20 July 2012 в 14:03
поделиться

8 ответов

A good playback mechanism is not something that can be simply added to a game without major difiiculties. The best would be do design the game infrastructure with it in mind. The command pattern can be used to achieve such a game infrastructure.

For example:

public interface Command{
    void execute();
}
public class MoveRightCommand implements Command {
   private Grid theGrid;
   private Player thePlayer;

   public MoveRightCommand(Player player, Grid grid){
        this.theGrid = grid;
        this.thePlayer = player;
       }

   public void execute(){
     player.modifyPosition(0, 1, 0, 0);
   } 
}

And then the command can be pushed in an execution queue both when the user presses a keyboard button, moves the mouse or without a trigger with the playback mechanism. The command object can have a time-stamp value (relative to the beginning of the playback) for precise playback...

14
ответ дан 3 December 2019 в 02:11
поделиться

Шон Харгривз недавно опубликовал в своем блоге сообщение о том, как они реализовали воспроизведение в MotoGP. Обсуждается несколько разных подходов и их плюсы и минусы.

http://blogs.msdn.com/shawnhar/archive/2009/03/20/motogp-replays.aspx

8
ответ дан 3 December 2019 в 02:11
поделиться

Assuming that your game is deterministic, it might be sufficient if you recorded the inputs of the users (option 2). However, you would need to make sure that you are recognizing the correct and consistent times for these events, such as when it was recognized by the server. I'm not sure how you handle events in the grid.

My worry is that if you don't have a mechanism that can uniformly reference timed events, there might be a problem with the way your code handles distributed users.

Consider a game like Halo 3 on the XBOX 360 for example - each client records his view of the game, including server-based corrections.

3
ответ дан 3 December 2019 в 02:11
поделиться

I would simply say that the best way to record a replay of a game depends entirely on the nature of the game. Being grid based isn't the issue; the issue is how predictable behaviour is following a state change, how often there are new inputs to the system, whether there is random data being injected at any point, etc, You can store an entire chess game just by recording each move in turn, but that wouldn't work for a first person shooter where there are no clear turns. You could store a first person shooter by noting the exact time of each input, but that won't work for an RPG where the result of an input might be modified by the result of a random dice roll. Even the seemingly foolproof idea of taking a snapshot as often as possible isn't good enough if important information appears instantaneously and doesn't persist in any capturable form.

Interestingly this is very similar to the problem you get with networking. How does one computer ensure that another computer is made aware of the game state, without having to send that entire game state at an impractically high frequency? The typical approach ends up being a bespoke mixture of event notifications and state updates, which is probably what you'll need here.

2
ответ дан 3 December 2019 в 02:11
поделиться

То, как вы к этому подходите, будет во многом зависеть от языка, который вы используете для своей игры, но в общих чертах есть много подходов, в зависимости от того, хотите ли вы использовать много памяти или хотите задержка. Было бы полезно, если бы вы могли подумать о том, на какие жертвы вы готовы пойти.

Но, казалось бы, наилучшим подходом может быть просто сохранить ввод от пользователя, как уже упоминалось, и либо сохранить позиции всех актеров / спрайтов в игре одновременно, что так же просто, как сохранение направления, скорости и тайла x, y или, если все может быть детерминированным, игнорируйте актеров / спрайтов, так как вы можете получить их информацию

Насколько недетерминированной является ваша игра, также было бы полезно дать лучшее предложение.

Если есть большое динамическое движение, такое как ударное дерби,

2
ответ дан 3 December 2019 в 02:11
поделиться

Нет необходимости сохранить все на сцене для каждого кадра. Сохраняйте изменения постепенно и используйте некоторые хорошие методы интерполяции. Я бы на самом деле не использовал подход, основанный на шаблонах команд, а скорее делал бы проверки с фиксированной скоростью для каждого игрового объекта и смотрел бы, изменился ли какой-либо атрибут. Если есть изменение, то это изменение записывается в некотором хорошем кодировании, и воспроизведение даже не станет таким большим.

2
ответ дан 3 December 2019 в 02:11
поделиться

Why not record several times a second and then compress your output, or perhaps do this:

recordInitialState();
...
runs 30 times a second:
recordChangeInState(previousState, currentState);
...

If you only record the change in state with a timestamp(and each change is small, and if there is no change, then record nothing), you should end up with reasonable file sizes.

2
ответ дан 3 December 2019 в 02:11
поделиться

Однажды я сделал это, позаимствовав идею сжатия видео: ключевые кадры и промежуточные кадры. По сути, каждые несколько секунд вы сохраняете полное состояние мира. Затем, один раз за обновление игры, вы сохраняете все изменения состояния мира, произошедшие с момента последнего обновления игры. Детали (как часто вы сохраняете ключевые кадры? Что именно считается «изменением состояния мира»?) Будут зависеть от того, какую игровую информацию вам нужно сохранить.

В нашем случае мир состоял из множества, многие игровые объекты, большинство из которых в любой момент времени оставались неподвижными, поэтому такой подход сэкономил нам много времени и памяти при записи положений объектов, которые не двигались. В вашем случае компромиссы могут быть другими.

1
ответ дан 3 December 2019 в 02:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: