Jump to content

Aspect11

Member
  • Posts

    205
  • Joined

  • Last visited

Awards

This user doesn't have any awards

Recent Profile Visitors

1,268 profile views

Aspect11's Achievements

  1. So this is my BSP script: # Builtin from typing import Optional import random # Pip import numpy as np # Constants EMPTY = 0 FLOOR = 1 WALL = 2 PLAYER_START = 3 DEBUG_WALL = 9 MIN_CONTAINER_SIZE = 6 MIN_ROOM_SIZE = 5 HALLWAY_THICKNESS = 2 class Rect: def __init__(self, x1: int, y1: int, x2: int, y2: int) -> None: self.x1: int = x1 self.y1: int = y1 self.x2: int = x2 self.y2: int = y2 def __repr__(self) -> str: return ( f"<Rect (Top-left=({self.x1}, {self.y1})) (Bottom-right=({self.x2}," f" {self.y2}))>" ) @property def width(self) -> int: """Returns the width of the rect.""" return self.x2 - self.x1 + 1 @property def height(self) -> int: """Returns the height of the rect.""" return self.y2 - self.y1 + 1 @property def center_x(self) -> int: """Returns the x coordinate of the center position.""" return int((self.x1 + self.x2) / 2) @property def center_y(self) -> int: """Returns the y coordinate of the center position.""" return int((self.y1 + self.y2) / 2) class Leaf: def __init__( self, x1: int, y1: int, x2: int, y2: int, grid: np.ndarray, debug_lines: bool = False, ) -> None: self.left: Optional[Leaf] = None self.right: Optional[Leaf] = None self.container: Rect = Rect(x1, y1, x2, y2) self.room: Optional[Rect] = None self.grid: np.ndarray = grid self.split_vertical: Optional[bool] = None self.debug_lines: bool = debug_lines def __repr__(self) -> str: return ( f"<Leaf (Left={self.left}) (Right={self.right})" f" (Top-left position=({self.container.x1}, {self.container.y1}))>" ) def split(self) -> None: """Splits a container either horizontally or vertically.""" # Test if this container is already split or not. This container will always # have a left and right leaf when splitting since the checks later on in this # function ensure it is big enough to be split if self.left is not None and self.right is not None: self.left.split() self.right.split() # Return just to make sure this container isn't split again with left and # right being overwritten return # To determine the direction of split, we test if the width is 25% larger than # the height, if so we split vertically. However, if the height is 25% larger # than the width, we split horizontally. Otherwise, we split randomly split_vertical = bool(random.getrandbits(1)) if ( self.container.width > self.container.height and self.container.width / self.container.height >= 1.25 ): split_vertical = True elif ( self.container.height > self.container.width and self.container.height / self.container.width >= 1.25 ): split_vertical = False # To determine the range of values that we could split on, we need to find out # if the container is too small. Once we've done that, we can use the x1, y1, x2 # and y2 coordinates to specify the range of values if split_vertical: max_size = self.container.width - MIN_CONTAINER_SIZE else: max_size = self.container.height - MIN_CONTAINER_SIZE if max_size <= MIN_CONTAINER_SIZE: # Container to small to split return # Create the split position. This ensures that there will be MIN_CONTAINER_SIZE # on each side pos = random.randint(MIN_CONTAINER_SIZE, max_size) # Split the container if split_vertical: # Split vertically making sure to adjust pos, so it can be within range of # the actual container pos = self.container.x1 + pos if self.debug_lines: self.grid[self.container.y1 : self.container.y2 + 1, pos] = DEBUG_WALL # Create child leafs self.left = Leaf( self.container.x1, self.container.y1, pos - 1, self.container.y2, self.grid, self.debug_lines, ) self.right = Leaf( pos + 1, self.container.y1, self.container.x2, self.container.y2, self.grid, self.debug_lines, ) else: # Split horizontally making sure to adjust pos, so it can be within range of # the actual container pos = self.container.y1 + pos if self.debug_lines: self.grid[pos, self.container.x1 : self.container.x2 + 1] = DEBUG_WALL # Create child leafs self.left = Leaf( self.container.x1, self.container.y1, self.container.x2, pos - 1, self.grid, self.debug_lines, ) self.right = Leaf( self.container.x1, pos + 1, self.container.x2, self.container.y2, self.grid, self.debug_lines, ) # Set the leaf's split direction self.split_vertical = split_vertical def create_room(self) -> None: """Creates a random sized room inside a container.""" # Test if this container is already split or not. If it is, we do not want to # create a room inside it otherwise it will overwrite other rooms if self.left is not None and self.right is not None: self.left.create_room() self.right.create_room() # Return just to make sure this container doesn't create a room overwriting # others return # Pick a random width and height making sure it is at least MIN_ROOM_SIZE but # doesn't exceed the container width = random.randint(MIN_ROOM_SIZE, self.container.width) height = random.randint(MIN_ROOM_SIZE, self.container.height) # Use the width and height to find a suitable x and y position which can create # the room x_pos = random.randint( self.container.x1, self.container.x1 + self.container.width - width ) y_pos = random.randint( self.container.y1, self.container.y1 + self.container.height - height ) # Update the grid with the walls and floors self.grid[y_pos : y_pos + height, x_pos : x_pos + width] = WALL self.grid[y_pos + 1 : y_pos + height - 1, x_pos + 1 : x_pos + width - 1] = FLOOR # Create the room rect self.room = Rect(x_pos, y_pos, x_pos + width - 1, y_pos + height - 1) global counter self.grid[self.room.center_y, self.room.center_x] = counter counter += 1 def create_hallway(self): # CREATE HALLWAYS HERE pass And the function that runs it: from bsp import Leaf import numpy as np def make_map() -> None: # Create constants used during the generation width = 40 height = 20 split_count = 5 grid = np.full((height, width), 0, np.int8) bsp = Leaf(0, 0, width - 1, height - 1, grid) for count in range(split_count): bsp.split() bsp.create_room() print(grid) And I am currently working on the create_hallway() function which is meant to create a 5 wide (a 2 on the outside and 3 1's in the middle) hallway from one leaf to another. Note that due to the if statement in split(), there may be an odd amount of containers, I'm not sure how to fix this, maybe someone could help. However, I want to know how can I create a path from one leaf to another?
  2. So I'm trying to make a graph program that plots weight over a given time period with using BMI to display which points are underweight, healthyweight and overweight. Here's my current code: import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import seaborn as sns import pandas as pd from datetime import datetime import csv weights = [] dates = [] newWeight = float(input("Enter new weight: ")) newDate = datetime.today().date() with open("re.txt", "a") as file: lineCount = sum(1 for line in open('re.txt')) newRecord = f"{lineCount},{newWeight},{newDate}\n" file.write(newRecord) with open("re.txt", "r") as file: csv_reader = csv.reader(file, delimiter=",") for count, record in enumerate(csv_reader): if count == 0: continue else: weights.append(record[1]) date = datetime(year=int(record[2][0:4]), month=int(record[2][5:7]), day=int(record[2][8:10])).date() dates.append(date) df = pd.DataFrame({"Weight": weights, "Dates": dates}, columns=["Weight", "Dates"]) print(df) df["Dates"] = pd.to_datetime(df["Dates"]) df.sort_values(by="Dates", inplace=True, ascending=False) sns.set_theme(style="dark") dates = [datetime.date(x) for x in df["Dates"]] graph = sns.scatterplot(data=df, x=dates, y="Weight", color="black") currentAxis = plt.gca() #currentAxis.add_patch(Rectangle((0,0), 1000000, 51.2559, facecolor="yellow")) #currentAxis.add_patch(Rectangle((0,51.2559), 1000000, 62.5957, facecolor="green")) #currentAxis.add_patch(Rectangle((0,62.5957), 1000000, 200, facecolor="red")) plt.show() #df.to_csv("re.txt") However, when I run the code (without the rectangles), this is the result: https://ibb.co/BPX77mW And with the rectangles: https://ibb.co/BPX77mW If anyone can find where I've gone wrong, that'll be great. Thanks!
  3. Damm, that's what I forgot. Thanks XD I don't think so, but maybe I'm wrong. Thanks anyway!
  4. So here's my code: class Vertex: def __init__(self, name): self.name = name self.connections = {} def addNeighbour(self, neighbour, cost): self.connections[neighbour] = cost class Graph: def __init__(self): self.vertexs = {} def addVertex(self, newVertex): new = Vertex(newVertex) self.vertexs[newVertex] = new def addEdge(self, src, dest, cost): self.vertexs[src].addNeighbour(self.vertexs[dest], cost) def dfs(self, start, end, visited): visited[start] = True print(start, end=' ') if start == end: # End node found return True else: # Use depth first search for connection in graph.vertexs[start].connections: if visited[connection.name] == False: if self.dfs(connection.name, end, visited) == True: # Return true to stop extra nodes from being searched return True def bfs(self, start, end, visited, queue): if len(queue) == 0: # Queue is empty queue.append(start) visited[start] = True currentNode = queue.pop(0) print(currentNode, end=' ') if start == end: # End node found return True else: # Do breadth first search for connection in graph.vertexs[currentNode].connections: if visited[connection.name] == False: # Queue all its unvisited neighbours queue.append(connection.name) for newNode in queue: self.bfs(newNode, end, visited, queue) def dijkstra(self, start, end, visited, distances): visited[start] = True for count, connection in enumerate(graph.vertexs[start].connections): # Set each neighbour's distance cost = list(graph.vertexs[start].connections.values()) distances[count] = cost[count] smallestIndex = min(distances, key=distances.get) for connection in graph.vertexs[start].connections: if visited[smallestIndex] == False: self.dijkstra(connection.name, end, visited, distances) def setup(): graphList = { # Node number: [destination number, cost] 0: [[1, 4], [2, 2], [3, 5]], 1: [[1, 1], [3, 2]], 2: [[0, 3]], 3: [[2, 5]] } count = 0 graph = Graph() for i in range(len(graphList)): graph.addVertex(i) for arr in graphList.values(): for i in range(len(arr)): graph.addEdge(count, arr[i][0], arr[i][1]) count += 1 return graph, graphList graph, graphList = setup() def g(): print("DFS travsersal path from node 0 to node 3:") graph.dfs(0, 3, [False, False, False, False]) print() print("BFS traversal path from node 0 to node 3") graph.bfs(0, 3, [False, False, False, False], []) print() print("Shortest possible path from node 0 to 3:") print() graph.dijkstra(2, 3, [False, False, False, False], {0: float('inf'), 1: float('inf'), 2: float('inf'), 3: float('inf')}) What's meant to happen is that after node 2 (the start), the distances dictionary should be: {0: 3, 1: inf, 2: inf, 3: inf} This happens successfully, but when it moves onto node 0, the dictionary is now set to: {0: 4, 1: 2, 2: 5, 3: inf} What it is meant to be (as it adds up the distances): {0: 3, 1: 7, 2: inf, 3: 5} I don't know whats wrong so if anyone can find it, that'll be much appreciated. Thanks!
  5. Thanks. I knew it was a simple solution, just didn't click with me. I'll try it out tomorrow.
  6. So here's my current code: class Vertex: def __init__(self, name): self.name = name self.connections = {} def addNeighbour(self, neighbour, cost): self.connections[neighbour] = cost class Graph: def __init__(self): self.vertexs = {} def addVertex(self, newVertex): new = Vertex(newVertex) self.vertexs[newVertex] = new def addEdge(self, src, dest, cost): self.vertexs[src].addNeighbour(self.vertexs[dest], cost) def dfs(self, start, end, visited, path): visited[start] = True path.append(start) if start == end: # End node found print("found") else: # Use depth first search for connection in graph.vertexs[start].connections: if visited[connection.name] == False: self.dfs(connection.name, end, visited, path) return path def setup(): graphList = { 0: [1, 2], 1: [3], 2: [1], 3: [0, 2] } count = 0 graph = Graph() for i in range(4): graph.addVertex(i) for arr in graphList.values(): for i in range(len(arr)): graph.addEdge(count, arr[i], 1) count += 1 return graph graph = setup() traversalResult = graph.dfs(0, 3, [False, False, False, False], []) print(traversalResult) It can find the target node with depth first search, however, once the node has been found, it will continue to loop for one more time since it hasn't searched node 3 from node 0. How can I fix this so it just stops once the node has been found? Many thanks!
  7. So I managed to fix that problem, but there's one more. Its not moving the nodes upwards when I move the in-order successor to replace another node. For example in the following tree, if I wanted to delete 59: 59 / \ 46 72 / \ 64 87 \ 67 It would use 64 as the in-order successor which would replace 59. However, it doesn't replace the 64 node with 67. The code: import random randomList = [] randomListSize = 10 class Node: def __init__(self, rootValue): self.data = rootValue self.left = None self.right = None class Tree: def createNode(self, data): return Node(data) def insertNode(self, node, data): if node is None: # Create root node return self.createNode(data) # Root node already exists if data < node.data: # New node data is less than root node node.left = self.insertNode(node.left, data) elif data > node.data: # New node data is bigger than root node node.right = self.insertNode(node.right, data) # Save new node data return node def searchNode(self, node, data): if node is None or node.data == data: # Node is found return node elif node.data > data: # Node may be to the left of the root return self.searchNode(node.left, data) elif node.data < data: # Node may be to the right of the root return self.searchNode(node.right, data) else: # Node is not found return None def deleteNode(self, node, data): if self.searchNode(node, data) is None: print("Node doesn't exist") return None else: # Node exists if data < node.data: node.left = self.deleteNode(node.left, data) elif data > node.data: node.right = self.deleteNode(node.right, data) elif data == node.data: # Node has no children if node.left is None and node.right is None: del node return None # Node has 1 child elif node.left is None: temp = node.right node = None return temp elif node.right is None: temp = node.left node = None return temp else: # Node has 2 children so find inorder successor temp = self.inorderSuccessor(node.right) node.data = temp.data def inorderSuccessor(self, node): while node.left is not None: node = node.left return node def preorder(self, node): # Root then left sub-tree then right sub-tree if node is not None: print(node.data) self.preorder(node.left) self.preorder(node.right) def inorder(self, node): # Left sub-tree then root then right sub-tree if node is not None: self.inorder(node.left) self.inorder(node.right) def postorder(self, node): # Left sub-tree then right sub-tree then root if node is not None: self.postorder(node.left) self.postorder(node.right) print(node.data) def setup(): randomList = [] for i in range(randomListSize): randomList.append(random.randint(1, 100)) print(randomList) randomList = [59, 90, 93, 23, 60, 85, 64, 23, 15, 15] print(randomList) tree = Tree() root = tree.insertNode(None, randomList[0]) # Create root node for i in range(len(randomList) - 1): tree.insertNode(root, randomList[i + 1]) # Create each child node return tree, root def traverse(): while True: try: user = int(input("1 for preorder, 2 for inorder and 3 for postorder: ")) if user == 1: tree.preorder(root) elif user == 2: tree.inorder(root) elif user == 3: tree.postorder(root) else: print("Invalid choice") except ValueError: print("Invalid choice") break if __name__ == "__main__": tree, root = setup() while True: try: userChoice = int( input("Enter 1 to add a node, 2 to search for a node, 3 to delete a node and 4 to traverse the tree: ")) if userChoice == 1: newNode = int(input("Enter a number: ")) tree.insertNode(root, newNode) elif userChoice == 2: userSearch = int(input("Enter a number: ")) if tree.searchNode(root, userSearch) is not None: print(userSearch, "exists") else: print("Node doesn't exist") elif userChoice == 3: removeNode = int(input("Enter a number: ")) tree.deleteNode(root, removeNode) elif userChoice == 4: traverse() else: print("Invalid choice") except ValueError: print("Invalid choice") Thanks!
  8. So I'm trying to create a binary tree within python using classes but my deleteNode() function seems to be not working. Does anyone know why? import random randomList = [] randomListSize = 10 class Node: def __init__(self, rootValue): self.data = rootValue self.left = None self.right = None class Tree: def createNode(self, data): return Node(data) def insertNode(self, node, data): if node is None: # Create root node return self.createNode(data) # Root node already exists if data < node.data: # New node data is less than root node node.left = self.insertNode(node.left, data) elif data > node.data: # New node data is bigger than root node node.right = self.insertNode(node.right, data) # Save new node data return node def searchNode(self, node, data): if node is None or node.data == data: # Node is found return node elif node.data > data: # Node may be to the left of the root return self.searchNode(node.left, data) elif node.data < data: # Node may be to the right of the root return self.searchNode(node.right, data) else: # Node is not found return None def deleteNode(self, node, data): if self.searchNode(node, data) is None: print("Node doesn't exist") return None else: # Node exists if data < node.data: self.deleteNode(node.left, data) # DELETED NODE IS STILL RETURNED elif data > node.data: self.deleteNode(node.right, data) elif data == node.data: # Node has no children if node.left is None and node.right is None: del node return None # Node has 1 child elif node.left is None: temp = node.right node = None return temp elif node.right is None: temp = node.left node = None return temp else: # Node has 2 children print() return node def preorder(self, node): # Root then left sub-tree then right sub-tree if node is not None: print(node.data) self.preorder(node.left) self.preorder(node.right) def inorder(self, node): # Left sub-tree then root then right sub-tree if node is not None: self.inorder(node.left) print(node.data) self.inorder(node.right) def postorder(self, node): # Left sub-tree then right sub-tree then root if node is not None: self.postorder(node.left) self.postorder(node.right) print(node.data) def setup(): randomList = [] for i in range(randomListSize): randomList.append(random.randint(1,100)) tree = Tree() root = tree.insertNode(None, randomList[0]) # Create root node for i in range(len(randomList)-1): tree.insertNode(root,randomList[i+1]) # Create each child node return tree, root def traverse(): while True: try: user = int(input("1 for preorder, 2 for inorder and 3 for postorder: ")) if user == 1: tree.preorder(root) elif user == 2: tree.inorder(root) elif user == 3: tree.postorder(root) else: print("Invalid choice") except ValueError: print("Invalid choice") break if __name__ == "__main__": tree, root = setup() while True: try: userChoice = int(input("Enter 1 to add a node, 2 to search for a node, 3 to delete a node and 4 to traverse the tree: ")) if userChoice == 1: newNode = int(input("Enter a number: ")) tree.insertNode(root, newNode) elif userChoice == 2: userSearch = int(input("Enter a number: ")) if tree.searchNode(root, userSearch) is not None: print(userSearch, "exists") else: print("Node doesn't exist") elif userChoice == 3: removeNode = int(input("Enter a number: ")) tree.deleteNode(root, removeNode) elif userChoice == 4: traverse() else: print("Invalid choice") except ValueError: print("Invalid choice") Thanks!
  9. I know they have a built in json utility library, but it doesn't really help me.
  10. So I am trying to make a script that will write a JSON file like this: And this is my code: using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.SceneManagement; public class Statistics : MonoBehaviour { public Player player; public GameManager manager; public EnemyDeathCounter enemyDeaths; static float timeCounter; static int totalSpent; string path = "Assets/Statistics.json"; void Update() { totalTime(); endGame(); } void totalTime() { if(manager.gameInProgressInspector) { timeCounter += Time.deltaTime; } } void endGame() { if(player.playerDead == true || manager.gameCompleted) { // End game collectStatistics(); SceneManager.LoadScene("Leaderboard"); } } void collectStatistics() { statData statData = new statData(); string oldDataRaw = File.ReadAllText(path); statData oldData = JsonUtility.FromJson<statData>(oldDataRaw); //statData.username //DO USERNAME INPUT IN MENU CLASS statData.timeToComplete = timeCounter; statData.playerLevel = player.playerLevel; statData.armourLevel = player.armourLevel; statData.weaponLevel = player.weaponLevel; statData.totalMoney = player.totalMoneySpent; statData.enemiesKilled = enemyDeaths.count; statData.gameCompleted = manager.gameCompleted; statData.score = completedScore(calculateScore(statData.timeToComplete, statData.playerLevel, statData.armourLevel, statData.weaponLevel, statData.totalMoney, statData.enemiesKilled), statData.gameCompleted); string json = JsonUtility.ToJson(statData, true); File.WriteAllText(path, json); } int calculateScore(float timeToComplete, int playerLevel, int armourLevel, int weaponLevel, int totalMoney, int enemiesKilled) { if(totalMoney == 0 || enemiesKilled == 0) { // TotalMoney and/or enemiesKilled are 0 so need to be excluded int score = playerLevel * armourLevel * weaponLevel; if(totalMoney == 0 & enemiesKilled == 0) { // Both are 0 score = (score * 100)/Mathf.RoundToInt(timeToComplete); return score; } else if(totalMoney == 0) { // Just totalMoney is 0 score *= enemiesKilled; score = (score * 100)/Mathf.RoundToInt(timeToComplete); return score; } else if(enemiesKilled == 0) { // Just enemiesKilled is 0 score *= totalMoney; score = (score * 100)/Mathf.RoundToInt(timeToComplete); return score; } else { return 0; } } else { // TotalMoney and enemiesKilled are both bigger than 0 int score = playerLevel * armourLevel * weaponLevel * totalMoney * enemiesKilled; score = (score * 100)/Mathf.RoundToInt(timeToComplete); return score; } } int completedScore(int score, bool gameCompleted) { if(gameCompleted == true) { score *= 1; return score; } else { score *= 0; return score; } } private class statData { public string username; public float timeToComplete; public int playerLevel; public int armourLevel; public int weaponLevel; public int totalMoney; public int enemiesKilled; public bool gameCompleted; public int score; } } I have no idea how to make this work. If anyone has any ideas on how I could do this or even if I can do it a better way, they'll be greatly appreciated. Thanks!
  11. I've done that (kinda stupid me) and I've modified it like: import os names = [] directory = "1/" with open("names.txt") as file: for line in file: names.append(line.replace('\n', '')) i = 0 for filename in os.listdir(directory): print(filename) try: os.rename(directory + filename, directory + names[i] + '.pdf') except FileExistsError: continue i += 1 with open("names.txt") as file: for line in file: print(line) But the second 'with open' shows that the files have been renamed bu in the file explorer, they haven't
  12. It's line 15, it doesn't increment through the array
  13. But it still does read the filenames from the folder. I only can't seem to increment through each value in the array.
  14. So I'm trying to create a where there is a folder of files each of which need to be renamed and there is an text document with all the filenames that need to be used inside. I basically want it to loop through and rename each file in the folder to the corresponding one in the text document. My current code: import os names = [] directory = "1/" with open("names.txt") as file: for line in file: names.append(line) print(names) for filename in os.listdir(directory): i = 0 print(filename) os.rename(directory + filename, directory + names[i] + '.pdf') i += 1 But I keep getting the error: Anyone know what's wrong? Thanks!
  15. So I've gotten a bit further, I've got past that error. But another one has come up: root@basicserver:/var/samba/DiscordDownloader# go run discord-image-downloader-go package discord-image-downloader-go: cannot find package "discord-image-downloader-go" in any of: /root/.go/src/discord-image-downloader-go (from $GOROOT) /root/work/src/discord-image-downloader-go (from $GOPATH) Anyone, pls!
×