问题描述
我有python版本3.8和pygame版本2.0.0.dev12,我使用Windows 10 64位。
程序正常运行。
但是一个事件导致程序完全停止。当它停止时,即使单击X按钮也不会退出(您可以单击X按钮,但不会执行任何操作)。程序崩溃时甚至没有说“(不重新欺骗)”。 导致程序停止的事件是单击“尝试将程序窗口移到最前面”。这是通过单击任务栏上的图标,或使用ALT + TAB并选择程序窗口来完成的。
我使用Spyder运行我的代码,但是当我运行Jupyter Lab时也会发生同样的情况。
为什么会这样,我该如何解决?
要复制的所有代码和TXT文件在这里:https://github.com/STProgrammer/AStar
我没有在此处粘贴所有代码,因为它超出了此处的最大字符数限制。
但是当我单击以在Windows任务栏中打开windonw时,它会停止,或者有时即使我在屏幕截图中捕获的那点没有做任何事情,它也会停止。
我试图在AStar.py的最后一部分(从321行显示“ if astar.pygame”)进行一些更改,但是它们没有起作用。
我该如何解决?
但是下面只是AStar.py的主要代码:
from Graph import Graph
from Vertex import Vertex
from Edge import Edge
import pygame as pg
'''
The AStar class inherits the Graph class
'''
class AStar(Graph):
'''
#
# delay: seconds between each iteration when visualizing is turned on
# visual: Turns pygame visualization on/off
#
'''
def __init__(self,delay = 0.001,visual = True):
super().__init__()
self.pygame = visual
self.background = None
self.LIGHTGREY = (180,180,180)
self.DARKGREEN = (0,255,0)
self.PINK = (255,200,200)
self.GREEN=(200,200)
self.WHITE = (245,245,245)
self.BLACK=(0,0)
self.RED = (255,0)
self.BLUE = (0,255)
self.delay = delay
# walls define obstacles in grid,e.g. walls,Boxes etc,by defining each position in grid that is part of an obstacle
self.walls = []
'''
#
# Defines obstacles provided in removevertecies from the graph by removing all edges
# to vertecies that is defined as an obstacle
#
'''
def removeVertecies(self,removevertecies = []):
err_v = []
err_e = []
# Removing the vertecies
for r in removevertecies:
self.walls.append(self.vertecies[r])
self.vertecies.pop(r)
# Checking the edges ...
for v in self.vertecies:
vtex = self.vertecies[v]
for edge in vtex.adjecent:
vertex = edge.vertex
if vertex.name not in self.vertecies:
err_v.append(vtex)
err_e.append(edge)
for i in range(0,len(err_v)):
err_v[i].adjecent.remove(err_e[i])
return removevertecies
'''
#
# Read in the list of obstacles (defined by tag "remove"),the startnode from which traversal is defined,# and the targetnode
#
'''
def readLimitations(self,filename):
import pandas as pd
from collections import namedtuple
columnnames = ['item','valuelist']
df = pd.read_csv(filename,error_bad_lines=False,encoding='latin-1',warn_bad_lines=False,names=columnnames,header = None,sep = ':')
for i in range(0,3):
if df.iat[i,0] == 'startvertex':
startVertex = df.iat[i,1]
elif df.iat[i,0] == 'targetvertex':
targetVertex = df.iat[i,0] == 'remove':
removed = self.removeVertecies(df.iat[i,1].split(';'))
return startVertex,targetVertex,removed
'''
# Initialize pygame visualization,if visualization has been defined
# Creates a dynamic visual grid according to the number of columns and rows
# read/defined during initialization. The visual limitations are defined by 1000x1000 pixels
'''
def initPygame(self):
if self.pygame:
xmin = ymin = xmax = ymax = 0
for v in self.vertecies:
vertex = self.vertecies[v]
x,y = vertex.position()
if x < xmin:
xmin = x
elif x > xmax:
xmax = x
if y < ymin:
ymin = y
elif y > ymax:
ymax = y
pg.init()
w,h = 600,600
self.xBoxsize = int(w / ((xmax + 1) - xmin))
self.yBoxsize = int(w / ((ymax + 1) - ymin))
w = self.xBoxsize * ((int(w/self.xBoxsize)))
h = self.yBoxsize * ((int(h/self.yBoxsize)))
self.background = pg.display.set_mode((w,h))
background = self.background
self.clock = pg.time.Clock()
self.clock.tick()
for c in range (0,(int(w/self.xBoxsize)) + 1):
for l in range (0,(int(h/self.yBoxsize)) + 1):
pg.draw.rect(background,self.WHITE,(c * self.xBoxsize,l * self.yBoxsize,self.xBoxsize,self.yBoxsize))
pg.draw.line(background,self.BLACK,l * self.yBoxsize),(c * self.xBoxsize + self.xBoxsize,l * self.yBoxsize))
pg.draw.line(background,l * self.yBoxsize + self.yBoxsize))
pg.draw.line(background,l * self.yBoxsize + self.yBoxsize),l * self.yBoxsize + self.yBoxsize))
for wall in self.walls:
self.pygameState(wall,self.BLACK)
pg.display.flip()
'''
# Draw a Box,representing the current vertex in the position defined by the name of the vertex.
# The color-parameter defines the (R,G,B)-value of the Box
# If no visualization is used (self.pygame == False),no Box is visualized
'''
def pygameState(self,current,color):
import time
if self.pygame:
background = self.background
x,y = current.position()
pg.draw.rect(background,color,(x * self.xBoxsize,y * self.yBoxsize,self.yBoxsize))
pg.draw.line(background,y * self.yBoxsize),(x * self.xBoxsize + self.xBoxsize,y * self.yBoxsize))
pg.draw.line(background,y * self.yBoxsize + self.yBoxsize))
pg.draw.line(background,y * self.yBoxsize + self.yBoxsize),y * self.yBoxsize + self.yBoxsize))
if color not in [self.BLUE,self.RED,self.BLACK]:
time.sleep(self.delay)
pass
pg.display.flip()
'''
#
# Defining the heuristics used to calculate the estimated distance between the node being handled (startVertexName),# and the targetnode (targetVertexName)
# Please note that the name of the vertecies are passed,not the vertex itself. The name is used for lookup
# in the list of vertecies in the graph.
# Further,the name of the vertex has the Syntax: xNNyMM,where NN and MM are numerical and indicates column and row.
# E.g. x4y15 means column 4 of row 15.
# By identifying the column and row of a vertex,the estimated shorted distance between two vertecies may be
# calculated using the Manhatten distance
#
'''
def heuristics(self,startVertexName = None,targetVertexName = None):
if not startVertexName or not targetVertexName:
raise KeyError("VertexLookup need the names of the Vertecies addressed.")
if startVertexName not in self.vertecies:
raise KeyError("Node/Vertex defined as FROM-vertex is not present in graph")
if targetVertexName not in self.vertecies:
raise KeyError("Node/Vertex defined as TO-vertex is not present in graph")
xstart,ystart = self.vertecies[startVertexName].position()
xend,yend = self.vertecies[targetVertexName].position()
#
# Manhatten heuristics
#
dx = abs(xstart - xend)
dy = abs(ystart - yend)
D = 1
return D * (dx + dy)
'''
#
# The Dijkstra's algorithm has been adapted to support visualization as defined by the graph
# It has further been adopted to present a targetVetrx even though Dijkstra's has no use of
# it during execution. The tragetVertex is used only for visualization purposes.
'''
def Dijkstra(self,targetVertexName = None):
self.initPygame()
# Check to see that startvertex is in Graph
if startVertexName not in self.vertecies:
raise KeyError("Start node not present in graph")
# Reset visited and prevIoUs pointer before running algorithm
vertex = self.vertecies[startVertexName]
vertex.distance = distance = weight = 0
prevIoUs_node = None
startNode = self.vertecies[startVertexName]
toNode = self.vertecies[targetVertexName]
#
# Create priority queue,priority = current weight on edge ...
# No duplicate edges in queue allowed
#
edge = Edge(0,vertex)
from queue import PriorityQueue
priqueue = PriorityQueue()
# Defines enqueue/dequeue methods on priqueue
def enqueue(data):
priqueue.put(data)
def dequeue():
return priqueue.get()
enqueue(edge)
while not priqueue.empty():
# Get the element with lowest priority (i.e. weight on edge)
edge = dequeue()
eyeball = edge.vertex
self.pygameState(eyeball,self.GREEN)
self.pygameState(startNode,self.BLUE)
self.pygameState(toNode,self.RED)
# If not visited prevIoUsly,we need to define the distance
if not eyeball.kNown:
eyeball.distance = distance
eyeball.prevIoUs = prevIoUs_node
eyeball.kNown = True
# If the vertex pointed to by the edge has an adjecency list,we need to iterate on it
for adjecentedge in eyeball.adjecent:
if not adjecentedge.vertex.kNown:
adjecentedge.vertex.distance = eyeball.distance + adjecentedge.weight
adjecentedge.vertex.prevIoUs = eyeball
adjecentedge.vertex.kNown = True
enqueue(adjecentedge)
self.pygameState(adjecentedge.vertex,self.PINK)
else:
if adjecentedge.vertex.distance > eyeball.distance + adjecentedge.weight:
adjecentedge.vertex.distance = eyeball.distance + adjecentedge.weight
adjecentedge.vertex.prevIoUs = eyeball
enqueue(adjecentedge)
self.pygameState(eyeball,self.LIGHTGREY)
for n in self.getPath(startVertexName,targetVertexName):
self.pygameState(n,self.DARKGREEN)
return self.getPath(startVertexName,targetVertexName)
'''
###############################################################################
#
# def AStarSearch(self,targetVertexName = None)
#
# Implement your code below.
# Please note that no other parts of this code or provided code should be altered
#
###############################################################################
'''
def AStarSearch(self,targetVertexName = None):
pass
astar = AStar(delay = 0,visual = True)
astar.readFile('minigraf.txt')
startVertexName,targetVertexName,removed = astar.readLimitations('minigraf_xtras.txt')
#astar.readFile('astjernegraf.txt')
#startVertexName,removed = astar.readLimitations('xtras.txt')
#astar.readFile('biggraph.txt')
#startVertexName,removed = astar.readLimitations('biggraph_xtras.txt')
#astar.readFile('ASTarobligGraf.txt')
#startVertexName,removed = astar.readLimitations('ASTarobligGraf_xtras.txt')
astar.Dijkstra(startVertexName,targetVertexName)
#astar.AStarSearch(startVertexName,targetVertexName)
if astar.pygame:
from pygame.locals import *
while astar.pygame:
for events in pg.event.get():
if events.type == QUIT:
exit(0)
pg.quit()
else:
print(astar.getPathAsstring(startVertexName,targetVertexName))
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)