Unreal Snake Game 1.0.0
Utils.h
1// Snake Game, Copyright LifeEXE. All Rights Reserved.
2
3#pragma once
4
5#include "CoreMinimal.h"
6#include "Types.h"
7
8namespace SnakeGame
9{
10class SNAKEGAME_API IPositionRandomizer
11{
12public:
13 virtual bool generatePosition(const Dim& dim, const TArray<CellType>& cells, Position& position) const = 0;
14 virtual ~IPositionRandomizer() = default;
15};
16
17class SNAKEGAME_API PositionRandomizer : public IPositionRandomizer
18{
19public:
20 virtual bool generatePosition(const Dim& dim, const TArray<CellType>& cells, Position& position) const override
21 {
22 const uint32 startX = FMath::RandRange(1, dim.width - 2);
23 const uint32 startY = FMath::RandRange(1, dim.height - 2);
24 Position randomPosition = {startX, startY};
25
26 do
27 {
28 const uint32 currentIndex = posToIndex(randomPosition, dim);
29 if (cells[currentIndex] == CellType::Empty)
30 {
31 position = randomPosition;
32 return true;
33 }
34
35 if (++randomPosition.x > dim.width - 2)
36 {
37 randomPosition.x = 1;
38 if (++randomPosition.y > dim.height - 2)
39 {
40 randomPosition.y = 1;
41 }
42 }
43 } while (randomPosition.x != startX || randomPosition.y != startY);
44
45 return false;
46 }
47
48private:
49 FORCEINLINE Position indexToPos(uint32 index, const Dim& dim) const { return Position(index % dim.width, index / dim.width); }
50 FORCEINLINE uint32 posToIndex(const Position& position, const Dim& dim) const { return position.x + position.y * dim.width; }
51};
52
53using IPositionRandomizerPtr = TSharedPtr<IPositionRandomizer>;
54
55} // namespace SnakeGame
Definition: Utils.h:11
Definition: Utils.h:18
Definition: SnakeGame.Build.cs:6
Definition: Types.h:12
Definition: Types.h:18