Skip to content
This repository has been archived by the owner on Nov 30, 2022. It is now read-only.

Python Games #323

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
21,492 changes: 21,492 additions & 0 deletions A-Path-Finding-Visualization/get_pip.py

Large diffs are not rendered by default.

74 changes: 74 additions & 0 deletions A-Path-Finding-Visualization/install_requirements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import subprocess
import sys
import get_pip
import os
import importlib
import contextlib

def install(package):
'''
installs a package using pip

:param package: string
'''
subprocess.call([sys.executable, "-m", "pip", "install", package])


required = []
failed = []

# Try to open reqirements.txt file and read all required packages
try:
file = open("requirements.txt", "r")
file_lines = file.readlines()
required = [line.strip().lower() for line in file_lines]
file.close()
except FileNotFoundError:
print("[ERROR] No requiremnts.txt file found")


if len(required) > 0:
print("[INPUT] You are about to install", len(required), "packages, would you like to proceed (y/n):", end=" ")
ans = input()

if ans.lower() == "y":
for package in required:
try:
print("[LOG] Looking for", package)
with contextlib.redirect_stdout(None):
__import__(package)
print("[LOG]", package, "is already installed, skipping...")
except ImportError:
print("[LOG]", package, "not installed")

try:
print("[LOG] Trying to install", package, "via pip")
try:
import pip
except:
print("[EXCEPTION] Pip is not installed")
print("[LOG] Trying to install pip")
get_pip.main()
print("[LOG] Pip has been installed")

print("[LOG] Installing", package)
install(package)
with contextlib.redirect_stdout(None):
__import__(package)
print("[LOG]", package, "has been installed")
except Exception as e:
print("[ERROR] Could not install", package, "-", e)
failed.append(package)

else:
print("[STOP] Operation terminated by user")
else:
print("[LOG] No packages to install")

if len(failed) > 0:
print("[FAILED]", len(failed), "package(s) were not installed. Failed package install(s):", end=" ")
for x, package in enumerate(failed):
if x != len(failed) -1:
print(package, end=",")
else:
print(package)
244 changes: 244 additions & 0 deletions A-Path-Finding-Visualization/path_finding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@

try:
import pygame
import sys
import math
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import os
except:
import install_requirements # install packages

import pygame
import sys
import math
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import os

screen = pygame.display.set_mode((800, 800))

class spot:
def __init__(self, x, y):
self.i = x
self.j = y
self.f = 0
self.g = 0
self.h = 0
self.neighbors = []
self.previous = None
self.obs = False
self.closed = False
self.value = 1

def show(self, color, st):
if self.closed == False :
pygame.draw.rect(screen, color, (self.i * w, self.j * h, w, h), st)
pygame.display.update()

def path(self, color, st):
pygame.draw.rect(screen, color, (self.i * w, self.j * h, w, h), st)
pygame.display.update()

def addNeighbors(self, grid):
i = self.i
j = self.j
if i < cols-1 and grid[self.i + 1][j].obs == False:
self.neighbors.append(grid[self.i + 1][j])
if i > 0 and grid[self.i - 1][j].obs == False:
self.neighbors.append(grid[self.i - 1][j])
if j < row-1 and grid[self.i][j + 1].obs == False:
self.neighbors.append(grid[self.i][j + 1])
if j > 0 and grid[self.i][j - 1].obs == False:
self.neighbors.append(grid[self.i][j - 1])


cols = 50
grid = [0 for i in range(cols)]
row = 50
openSet = []
closedSet = []
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
grey = (220, 220, 220)
w = 800 / cols
h = 800 / row
cameFrom = []

# create 2d array
for i in range(cols):
grid[i] = [0 for i in range(row)]

# Create Spots
for i in range(cols):
for j in range(row):
grid[i][j] = spot(i, j)


# Set start and end node
start = grid[12][5]
end = grid[3][6]
# SHOW RECT
for i in range(cols):
for j in range(row):
grid[i][j].show((255, 255, 255), 1)

for i in range(0,row):
grid[0][i].show(grey, 0)
grid[0][i].obs = True
grid[cols-1][i].obs = True
grid[cols-1][i].show(grey, 0)
grid[i][row-1].show(grey, 0)
grid[i][0].show(grey, 0)
grid[i][0].obs = True
grid[i][row-1].obs = True

def onsubmit():
global start
global end
st = startBox.get().split(',')
ed = endBox.get().split(',')
start = grid[int(st[0])][int(st[1])]
end = grid[int(ed[0])][int(ed[1])]
window.quit()
window.destroy()

window = Tk()
label = Label(window, text='Start(x,y): ')
startBox = Entry(window)
label1 = Label(window, text='End(x,y): ')
endBox = Entry(window)
var = IntVar()
showPath = ttk.Checkbutton(window, text='Show Steps :', onvalue=1, offvalue=0, variable=var)

submit = Button(window, text='Submit', command=onsubmit)

showPath.grid(columnspan=2, row=2)
submit.grid(columnspan=2, row=3)
label1.grid(row=1, pady=3)
endBox.grid(row=1, column=1, pady=3)
startBox.grid(row=0, column=1, pady=3)
label.grid(row=0, pady=3)

window.update()
mainloop()

pygame.init()
openSet.append(start)

def mousePress(x):
t = x[0]
w = x[1]
g1 = t // (800 // cols)
g2 = w // (800 // row)
acess = grid[g1][g2]
if acess != start and acess != end:
if acess.obs == False:
acess.obs = True
acess.show((255, 255, 255), 0)

end.show((255, 8, 127), 0)
start.show((255, 8, 127), 0)

loop = True
while loop:
ev = pygame.event.get()

for event in ev:
if event.type == pygame.QUIT:
pygame.quit()
if pygame.mouse.get_pressed()[0]:
try:
pos = pygame.mouse.get_pos()
mousePress(pos)
except AttributeError:
pass
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
loop = False
break

for i in range(cols):
for j in range(row):
grid[i][j].addNeighbors(grid)

def heurisitic(n, e):
d = math.sqrt((n.i - e.i)**2 + (n.j - e.j)**2)
#d = abs(n.i - e.i) + abs(n.j - e.j)
return d


def main():
end.show((255, 8, 127), 0)
start.show((255, 8, 127), 0)
if len(openSet) > 0:
lowestIndex = 0
for i in range(len(openSet)):
if openSet[i].f < openSet[lowestIndex].f:
lowestIndex = i

current = openSet[lowestIndex]
if current == end:
print('done', current.f)
start.show((255,8,127),0)
temp = current.f
for i in range(round(current.f)):
current.closed = False
current.show((0,0,255), 0)
current = current.previous
end.show((255, 8, 127), 0)

Tk().wm_withdraw()
result = messagebox.askokcancel('Program Finished', ('The program finished, the shortest distance \n to the path is ' + str(temp) + ' blocks away, \n would you like to re run the program?'))
if result == True:
os.execl(sys.executable,sys.executable, *sys.argv)
else:
ag = True
while ag:
ev = pygame.event.get()
for event in ev:
if event.type == pygame.KEYDOWN:
ag = False
break
pygame.quit()

openSet.pop(lowestIndex)
closedSet.append(current)

neighbors = current.neighbors
for i in range(len(neighbors)):
neighbor = neighbors[i]
if neighbor not in closedSet:
tempG = current.g + current.value
if neighbor in openSet:
if neighbor.g > tempG:
neighbor.g = tempG
else:
neighbor.g = tempG
openSet.append(neighbor)

neighbor.h = heurisitic(neighbor, end)
neighbor.f = neighbor.g + neighbor.h

if neighbor.previous == None:
neighbor.previous = current
if var.get():
for i in range(len(openSet)):
openSet[i].show(green, 0)

for i in range(len(closedSet)):
if closedSet[i] != start:
closedSet[i].show(red, 0)
current.closed = True


while True:
ev = pygame.event.poll()
if ev.type == pygame.QUIT:
pygame.quit()
pygame.display.update()
main()

Loading