Last active
December 18, 2021 20:56
-
-
Save megahomyak/0c613b6af7680271abafcd25ea16554d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from typing import Optional | |
import random | |
@dataclass | |
class Chunk: | |
""" | |
ALL FIELDS HERE ARE JUST DEMO STUBS!!! THEY ARE NOT USED ANYWHERE EXCEPT | |
FOR PRINTING OUT THE DATACLASS!!! | |
""" | |
chunk_x: int | |
chunk_y: int | |
random_number: int | |
@dataclass | |
class XNode: | |
left: Optional["XNode"] = None | |
right: Optional["XNode"] = None | |
chunk: Optional[Chunk] = None | |
@dataclass | |
class YNode: | |
left: "YNode" = None | |
right: "YNode" = None | |
x_node: Optional[XNode] = None | |
def generate_chunk(chunk_x, chunk_y): | |
return Chunk( | |
chunk_x, chunk_y, random_number=random.randint(0, 1_000_000) | |
) | |
def get_last_node(root_node, number, node_factory): | |
while number != 0: | |
if number % 2 == 0: | |
if root_node.left is None: | |
root_node.left = node_factory() | |
root_node = root_node.left | |
else: | |
if root_node.right is None: | |
root_node.right = node_factory() | |
root_node = root_node.right | |
number //= 2 | |
return root_node | |
def get_chunk_node_by_coordinates(chunk_x, chunk_y, root_y_node): | |
root_y_node = get_last_node( | |
root_node=root_y_node, number=chunk_y, node_factory=YNode | |
) | |
if root_y_node.x_node is None: | |
root_y_node.x_node = XNode() | |
root_x_node = get_last_node( | |
root_node=root_y_node.x_node, number=chunk_x, node_factory=XNode | |
) | |
if root_x_node.chunk is None: | |
root_x_node.chunk = generate_chunk(chunk_x, chunk_y) | |
return root_x_node.chunk | |
root_y_node = YNode() | |
print( | |
get_chunk_node_by_coordinates( | |
chunk_x=5, chunk_y=5, root_y_node=root_y_node | |
) | |
) | |
print(get_chunk_node_by_coordinates(5, 5, root_y_node)) | |
print(get_chunk_node_by_coordinates(5, 4, root_y_node)) | |
print(get_chunk_node_by_coordinates(3, 3, root_y_node)) | |
print(root_y_node) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment