Refactor main game loop (#291)