Related
I got the error mentioned before in the line 51 of the following code:
import csv
import math
from datetime import datetime
with open('BBDD1') as csv_file:
csv_reader1 = csv.reader(csv_file, delimiter=',')
with open('BBDD2') as csv_file:
csv_reader2 = csv.reader(csv_file, delimiter=',')
contador1=0
contador2=0
cont=0
bbdd1=[]
bbdd2=[]
d=float(input("Ingrese la distancia en metros entre el evento sísmico y la tronadura: "))
for fila1 in csv_reader1:
if fila1 != []:
bbdd1.append(fila1)
for fila2 in csv_reader2:
if fila2 != []:
bbdd2.append(fila2)
#for i in range(50):
#print(i)
#print(len(bbdd1))
#print(float(bbdd1[3][6].replace(",",".")))
i=0
for i in range(len(bbdd1)):
for j in range(len(bbdd2)):
#print(bbdd1[fila1][fila2])
#print(bbdd1[fila1][6])
#print(fila1)
cont+=1
print(i)
print(j)
distancia=((float(bbdd1[i+1][6].replace(",","."))-float(bbdd2[j+1][3]))**2 + (float(bbdd1[i+1][7].replace(",","."))-float(bbdd2[j+1][4]))**2 + (float(bbdd1[i+1][8].replace(",","."))-float(bbdd2[j+1][5]))**2)**0.5
if distancia <d:
print("La distancia es: ", distancia)
print("El evento " + str(bbdd2[j+1][0]) + " está relacionado con la tronadura " + str(bbdd1[i+1][0]))
print("Los números de eventos sísmicos relacionados a las tronaduras con una distancia entre ambas de " + str(d) + " m es de " + str(cont))
I was trying to relation the following 2 database:
bbdd1:
N° Quemada,Fecha,Hora,PK,Avance,Acumulado,Norte,Este,Corte,Fecha y hora,Date time
1,24-09-2019,TB 08:04,"7309,12","3,82","3,82","-468,965","-563,220","1671,935",24-09-2019 08:04,2019-09-24 08:04:00
2,06-10-2019,TA 16:41,"7311,48","2,36","6,18","-467,728","-561,210","1676,133",06-10-2019 16:41,2019-10-06 16:41:00
.
.
.
bbdd2:
Index,Event Date,EventTimeInDay,LocX [m],LocY [m],LocZ [m],Local Magnitude,Log Potency [log m^3],Log Energy [log J],Log(EnergyS/EnergyP),TriggerCount,Fecha y hora,Date time
1,2021/02/16,21:35:03,-502.5,-415.0,1660.8,-1.0,-2.88,-0.61,1.80,8,2021/02/16 21:35:03,2021-02-16 21:35:03
2,2021/03/14,01:20:59,-478.6,-414.9,1690.9,-1.3,-3.37,0.34,1.28,6,2021/03/14 01:20:59,2021-03-14 01:20:59
.
.
.
(There are many more rows, 56 rows in bbdd1 and 3447 rows in bbdd2). The problem is the double "for" because the "i" variable of the first "for" never changes, it gets stuck in i=0 and it should change to i=56 from i=0 with steps of 1.
Pls help, whenever i try to call the function grabacion, this error occurs:
error: horizontal dimensions mismatch (32768x32768 vs 1x1)
i really dont know anything about Octave, my teacher sent me this code and its not working, and he wont help at all. i need to get the energy density and frecuency spectra of an audio
function grabacion(fmax,Amax)
%
[x, rate] = audioread('prueba.wav');
%
%fs=44100; % frecuencia de muestreo [muestras/segundo]
%ts=1/rate; % tiempo de muestreo [segundos/muestras]
nsample = size(x, 1); % [muestras]
nsample = pow2(nextpow2(nsample));
x=[x;zeros(nsample - length(x)),1]; %genera un tamaño potencia de 2
%
%eje de frecuencias
dur = nsample / rate; %duraci\'on [seg]
fs = 1 / rate; %tasa de muestreo [seg]
t = 0:fs:dur; %eje de tiempo [seg]
tam = length(t);
f = (rate/2) * (1:tam/2) / (tam/2); %eje frecuencia [Hz]
N_min = round(nsample * 20 / rate) + 1;
N_max = round(nsample * fmax / rate) + 1;
f = f(N_min:N_max);
%
x = x .* hanning(length(x));
fftx = abs(fft(x));
fftx = fftx(N_min:N_max);
l = N_max - N_min + 1;
fft_x = 20 * log10(fftx); %unidad en dB
%
% Espectro de densidad de energÃa
figure;
subplot(2,1,1)
plot(f, fft_x', 'linewidth', 2);
set(gca, 'linewidth', 2, 'fontsize', 14);
axis([20 fmax 0 Amax]);
title(['Densidad Espectral de EnergÃa'] );
xlabel(['Frecuencia [Hz]']);
ylabel(['Amplitud [dB]']);
grid;
%size(t)
nx=size(x,1);
subplot(2,1,2)
plot(t(1:nx),x', 'linewidth', 2);
set(gca, 'linewidth', 2, 'fontsize', 14);
%axis([20 fmax 0 Amax]);
title(['función en el tiempo [seg]',] );
xlabel(['Tiempo [seg]']);
ylabel(['Amplitud [V]']);
grid;
endfunction
I'm trying to implement an artificial neural network that I just trained using this code.
import numpy as np
import os
training_path = 'Imagenes/train'
training_names = os.listdir(training_path)
image_paths = []
image_classes = []
class_id = 0
def imglist(path):
return [os.path.join(path,f) for f in os.listdir(path)]
for training_name in training_names:
dir = os.path.join(training_path, training_name)
class_path = imglist(dir)
image_paths += class_path
image_classes += [class_id]*len(class_path)
class_id+=1
des_list = []
sift = cv2.xfeatures2d.SIFT_create(100)
for image_path in image_paths:
im = cv2.imread(image_path, 0)
kp, des = sift.detectAndCompute(im, None)
des_list.append((image_path, des))
descriptors = des_list[0][1]
for image_path, descriptor in des_list[1:]:
descriptors = np.vstack((descriptors,descriptor))
descriptors_float = descriptors.astype(float)
from scipy.cluster.vq import kmeans, vq
k = 1000
voc, variance = kmeans(descriptors_float, k, 1)
im_features = np.zeros((len(image_paths), k), "float32")
for i in range(len(image_paths)):
words, distance = vq(des_list[i][1], voc)
for w in words:
im_features[i][w] += 1
nbr_ocurrences = np.sum((im_features > 0) * 1, axis = 0)
idf = np.array(np.log((1.0*len(image_paths)+1) / (1.0*nbr_ocurrences + 1)), 'float32')
from sklearn.preprocessing import StandardScaler
stdSlr = StandardScaler().fit(im_features)
im_features = stdSlr.transform(im_features)
print(np.shape(im_features))
print(np.shape(image_classes))
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(50,50), max_iter=5000, alpha=0.001,
solver='sgd', verbose=10, random_state=21,tol=0.000000001)
clf.fit(im_features, np.array(image_classes))
from sklearn.externals import joblib
joblib.dump((clf, training_names, stdSlr, k, voc), 'sift.pkl', compress = 3)
Well basically that's it and what I'm trying to implement is this
import cv2
import numpy as np
from sklearn.externals import joblib
#Cargando parámetros del modelo, clases y desviaciones estandar par normalizar, además de los clusters
clf, class_names, stdSlr, k, voc = joblib.load('sift.pkl')
#Creando SIFT
sift = cv2.xfeatures2d.SIFT_create(100)
#Objeto de video
video = cv2.VideoCapture('video2.mp4')
fgbg = cv2.createBackgroundSubtractorMOG2()
#Ciclo infinito
while True:
#Leer siguiente cuadro
ret, frame = video.read()
#Si hay siguiente cuadro, ret es TRUE de lo contrario es false y se rompe el ciclo
if ret:
porcentaje_escala = 100 # percent of original size
width = int(frame.shape[1] * porcentaje_escala / 100)
height = int(frame.shape[0] * porcentaje_escala / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
#Mostramos el cuadro leído
cv2.imshow('Video Original', frame)
#Convertimos el cuadro a escala de grises para procesarlo
frame_gris = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Escala de Grises',frame_gris)
#Aplicamos MOG acá
fgmask = fgbg.apply(frame_gris)
#Le hacemos thresholding para eliminar las sombras que el MOG2 deja en gris
ret,fgmask = cv2.threshold(fgmask,250,255,cv2.THRESH_BINARY)
#Aplicamos un pequeño filtro para quitarle ruido a la máscara
fgmask = cv2.GaussianBlur(fgmask,(3,3),0)
#Ahora vamos a dilatar y erosionar un poco la máscara para poder darle un espacio blanco al objeto
#no que detecte la forma sino sólo su espacio
kernel = np.ones((8,8),np.uint8)
fgmask = cv2.dilate(fgmask,kernel,iterations = 1)
fgmask = cv2.erode(fgmask,kernel,iterations = 1)
cv2.imshow('Mascara de MOG2',fgmask)
#Ahora hacemos el AND bit a bit de la máscara y la imagen original
res = cv2.bitwise_and(frame,frame,mask = fgmask)
cv2.imshow('resultado',res)
#Hallamos los componentes que comparten bits blancos en la imagen
contours, hierarchy = cv2.findContours(fgmask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2:]
#Se dibuja cada contorno si su alto y ancho es mayor a 20 pixeles
ROI=[]
for c in contours:
x,y,w,h = cv2.boundingRect(c)
if((w>20) and (h>20)):
ROI.append(frame[x:x+w,y:y+h])
ROI_Valida=[]
for i in range(len(ROI)):
if(np.shape(ROI[i])[0] > 0):
ROI_Valida.append(ROI[i])
for i in range(len(ROI_Valida)):
kp, des = sift.detectAndCompute(ROI_Valida[i], None)
test_features = np.zeros(k, "float32")
from scipy.cluster.vq import vq
words, distance = vq(des, voc)
for w in words:
test_features[w] += 1
Mostramos la imagen final
if cv2.waitKey(1) & 0xFF == ord('q'):
break;
else:
break;
However in this line in the implementation
words, distance = vq(des, voc)
I'm getting the next error
Traceback (most recent call last):File "C:\Universidad\Trabajo de Grado\Pruebas\p2.py", line 60, in words, distance = vq(des, voc)
File "C:\Python36\lib\site-packages\scipy\cluster\vq.py", line 201, in vq obs = _asarray_validated(obs, check_finite=check_finite)
File "C:\Python36\lib\site-packages\scipy_lib_util.py", line 249, in _asarray_validated raise ValueError('object arrays are not supported')
ValueError: object arrays are not supported
Which doesn't make sense to me as it's the same line used in training with a set of matrix.
I'd appreciate any help.
I want to open a file to edit what's inside with but i get this error
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/LittleSmashBros/Editeur de niveau.py", line 95, in <module>
fichier = open("niveau1.txt",)
TypeError: Required argument 'flags' (pos 2) not found
This is not my first time coding something but I am pretty new to this. My textfile is in the right file, it worked before. It stopped working when I added the function fichier_temp. If you could find what's the problem and explain how to solve it. This is my code, sorry for the variable name, I am French.
from tkinter import *
from os import *
fenetre = Tk()
fenetre.title("LittleSmashBros")
fenetre.geometry("1110x720")
bgImage = PhotoImage(file="Greenbg.png")
fond = Canvas(fenetre,width=1110,height=720)
fond.place(x=-2,y=-2)
fond.create_image(0,0,image=bgImage,anchor="nw")
fond.create_rectangle(1080,0,1111,720,fill="black")
#Stocke les images dans des variables
platGauche = PhotoImage(file="platGauche.png")
platMilieu = PhotoImage(file="platMilieu.png")
platDroite = PhotoImage(file="platDroite.png")
#Bouton qui définissent le bloc choisi
typeBloc = "V"
couleurB = "black"
def changeBloc(bloc): typeBloc = bloc
def boutonEnfonce(bouton) :
bloc1.config(bg=couleurB)
bloc2.config(bg=couleurB)
bloc3.config(bg=couleurB)
bouton.config(bg="white")
bloc1 = Button(fenetre,image=platGauche,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("G"),boutonEnfonce(bloc1)])
bloc2 = Button(fenetre,image=platMilieu,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("M"),boutonEnfonce(bloc2)])
bloc3 = Button(fenetre,image=platDroite,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("D"),boutonEnfonce(bloc3)])
bloc1.place(x=1082,y=10)
bloc2.place(x=1082,y=41)
bloc3.place(x=1082,y=72)
#Prend les coordonnées de la souris et donne sa position sur la grille
def cordsouris(cord):
global x0,y0
x0 = cord.x
y0 = cord.y
x1 = 0
x2 = 22
y1 = 0
y2 = 22
testx = False
testy = False
colonne = 0
ligne = 0
while testx == False:
if x1 < x0 < x2:
testx = True
colonne = colonne + 1
else:
colonne = colonne + 1
x1 = x1+21
x2 = x2+21
print(colonne)
while testy == False:
if y1 < y0 < y2:
testy = True
ligne = ligne + 1
else:
ligne = ligne + 1
y1 = y1+21
y2 = y2+21
print(ligne)
return (colonne,ligne)
#Créé la ligne a remplacer
def remplace_str_index(ligne,place,remplacement):
texte = fichier.readline(ligne)
return '%s%s%s'%(texte[:place],remplacement,texte[place+1:])
#Copie l'ancien fichier dans un nouveau avec la modification
def fichier_temp():
fichier = open("niveau1.txt")
colonne,ligne = cordsouris()
with open("temp.txt","w")as temp:
nb = 0
for rang in fichier:
nb = nb+1
if nb==ligne: text = remplace_str_index(ligne,colonne-1,typeBloc)
else : text = rang
temp.write(text)
print(rang)
print(text)
fichier.close()
os.remove("niveau1.txt")
os.rename("temp.txt","niveau1.txt")
#Détecte le click et effectue le changement de bloc
fond.bind("<Button 1>",fichier_temp)
#Place l'image en fonction du fichier texte
fichier = open("niveau1.txt",)
x=0
y=0
for rang in fichier:
for caractere in rang:
if caractere=="S":
fond.delete(fond.find_closest(x,y))
if caractere=="G":
fond.create_image(x,y,image=platGauche,anchor="nw")
if caractere=="M":
fond.create_image(x,y,image=platMilieu,anchor="nw")
if caractere=="D":
fond.create_image(x,y,image=platDroite,anchor="nw")
x = x+21
x = 0
y = y+21
fichier.close()
fenetre.mainloop()
This is exactly why you should never use from X import *.
from os import * overridden the builtin open in Python with os.open (which, unlike the builtin open, does not have a mode).
Either remove the star import or provide a flag like you have in the other places you used os.open.
You need to provide the file open mode
open("niveau1.txt", "r")
This is the problem:
from os import *
It also imports os.open which now overrides the builting open.
If you only import the parts you need from os it will work fine.
This question already has answers here:
Is it possible to implement gradual movement of an object to given coordinates in Pygame?
(1 answer)
How to make a circle move diagonally from corner to corner in pygame
(1 answer)
Pygame Enemys Wont Move Down - Tower Defense Game
(3 answers)
Closed 1 year ago.
I've been struggling with a code I found in the web and I tinkered with it. My goal was to make two ways of finding a path to a certain point to win against human user with an 'AI' in a tron game. But I've found you instantaneously die no matter what you do! After days of searching for clues with PyGame library or trying to see what happens, I still can't figure out what's wrong.
The algorithm is something like this:
pathTarget = new Queue();
fillPath(pathTarget);
// use pathTarget to move with `move()`
It either fills it up with A* search or BFS but I think it traverses all the nodes instantaneously, though I can't find the bug. I'd appreciate if you could point me in the right direction? The code is here in a friend's repo since I did not know what github is until today. Thanks in advance.
EDIT: As requested, the code is here too:
import pygame, time, collections, random, heapq
pygame.init()
BLACK = (0, 0, 0) # colores para usar en la ventana
P1_COLOUR = (0, 255, 255) # color de traza del jugador 1
P2_COLOUR = (255, 0, 255) # color de traza del jugador 2
moves = {'up':(0, -2), 'down':(0, 2), 'left':(0, -2), 'right':(0, 2)} # diccionario utilitario
# distancia manhattan entre dos nodos
def manhattan(nodeL, nodeR):
return abs(nodeL[0] - nodeR[0]) + abs(nodeL[1] - nodeR[1])
class Queue: # Clase para acceder facilmente a collections.deque
def __init__(self):
self.elements = collections.deque() # nuevo deque (double ended queue)
def empty(self):
return len(self.elements) == 0 # checar si está vacío
def push(self, x): # encolar elemento x
self.elements.append(x)
def pop(self): # remover y devolver el elemento en el frente
return self.elements.popleft()
def last(self): # ver el último nodo en la fila
node = self.elements.pop() # lo sacamos
self.elements.append(node) # lo metemos de vuelta
return node # lo devolvemos
# Clase Cola de Prioridad (usa heap de Python)
class PriorityQueue:
# Constructor
def __init__(self):
self.elements = []
# Checa si esta vacía
def empty(self):
return len(self.elements) == 0
# Inserta elemento item con prioridad priority
def push(self, item, priority):
heapq.heappush(self.elements, (priority, item))
# regresa el elemento prioritario
def pop(self):
return heapq.heappop(self.elements)[1]
# Clase jugador
class Player:
# Constructor
def __init__(self, direction, isHuman=False):
self.direction = direction # direccion como una tupla
self.isHuman = isHuman # si es humano o AI
if self.isHuman: # Si es humano lo construimos diferente
self.x = 50 # con cierta posición
self.y = height // 2
self.colour = P1_COLOUR # Y cierto color
else: # de otro modo es IA y va en otro lado
self.x = width - 50
self.y = height // 2
self.colour = P2_COLOUR # Con otro color
self.xTarget = 50 # además de valores especiales para seguir su objetivo y crear un camino
self.yTarget = height // 2
self.pathTarget = Queue() # como el camino a seguir para derrotar al humano
self.difficulty = 2 # random.randint(1, 2) # dificultad a usar
self.speed = 1 # velocidad del jugador
self.boost = False # si tiene nitro
self.start_boost = time.time() # para controlar la medida del nitro
self.boosts = 3 # cantidad de nitros
self.rect = pygame.Rect(self.x - 1, self.y - 1, 2, 2) # rectangulo del jugador
# metodo para dibujar
def __draw__(self):
self.rect = pygame.Rect(self.x - 1, self.y - 1, 2, 2) # redefine el rectangulo
pygame.draw.rect(screen, self.colour, self.rect, 0) # dibuja al jugador en la pantalla
# actualizar objetivo y camino, IA nada mas
def updateTarget(self):
self.xTarget, self.yTarget = p2.x, p2.y # actualiza los objetivos
# Este punto se supone que es un buen punto para "matar" al enemigo
if p2.direction == moves['left']:
self.yTarget -= 2
elif p2.direction == moves['right']:
self.yTarget += 2
elif p2.direction == moves['up']:
self.xTarget += 2
elif p2.direction == moves['down']:
self.xTarget -= 2
# Uso de la IA buscando caminos
if not self.pathTarget.empty():
self.pathTarget.push((self.xTarget, self.yTarget))
else:
if self.difficulty == 1:
self.bfs()
else:
self.aSearch()
# metodo para revisar la direccion de un nodo respecto a otro
def checkDir(self, target):
if self.x < target[0]:
return moves['right']
if self.x > target[0]:
return moves['left']
if self.y < target[1]:
return moves['down']
if self.y > target[1]:
return moves['up']
# metodo mover para evitar el privado '__move__', como una 'API' para la IA
def move(self):
if self.isHuman: # Si es humano que siga normal
past = (self.x, self.y)
self.__move__() # nos movemos normal
usedBoard[past[0]][past[1]] = True
else: # si es IA
if not self.pathTarget.empty(): # mientras haya direcciones a seguir en el camino
self.direction = self.checkDir(self.pathTarget.pop()) # sigamoslas
self.updateTarget() # actualiza las direcciones y la cola
# importante! primero calculamos la direccion y luego marcamos el nodo como usado
past = (self.x, self.y)
self.__move__() # nos movemos normal
usedBoard[past[0]][past[1]] = True
# Movimiento
def __move__(self):
if not self.boost: # Si no hay nitro
self.x += self.direction[0]
self.y += self.direction[1]
else: # si lo hay
self.x += self.direction[0] * 2
self.y += self.direction[1] * 2
# Nitro
def __boost__(self):
if self.boosts > 0: # si tenemos nitro
self.boosts -= 1 # quitamos
self.boost = True # activamos
self.start_boost = time.time() # y a correr! (0.5s)
# calcular los vecinos de un nodo dado un tablero prueba
def computeNeighbors(self, coords, testBoard):
neighbors = [] # vacía por las dudas
# Si x > 0 y está vacío el tablero, vamos a la izquierda
if coords[0] > 1:
if not usedBoard[coords[0] - 2][coords[1]] and not testBoard[coords[0] - 2][coords[1]]:
neighbors.append( (coords[0] - 2, coords[1]) )
# Si y > 62 y está vacío el tablero, vamos arriba
if coords[1] > 1:
if not usedBoard[coords[0]][coords[1] - 2] and not testBoard[coords[0]][coords[1] - 2]:
neighbors.append( (coords[0], coords[1] - 2) )
# Si x < width y está vacío el tablero, vamos a la derecha
if coords[0] < width - 4:
if not usedBoard[coords[0] + 2][coords[1]] and not testBoard[coords[0] + 2][coords[1]]:
neighbors.append( (coords[0] + 2, coords[1]) )
# Si y < height y está vacío el tablero, vamos abajo
if coords[1] < height - 4 - offset:
if not usedBoard[coords[0]][coords[1] + 2] and not testBoard[coords[0]][coords[1] + 2]:
neighbors.append( (coords[0], coords[1] + 2) )
return neighbors
# Busqueda de camino con A*
def aSearch(self):
testBoard = usedBoard # tablero de prueba para inundar
neighbors = PriorityQueue() # Creamos un heap o cola de prioridad
neighbors.push((self.x, self.y), 0) # metemos nuestro nodo inicial
pathGenerated = {} # Camino creado
costUpTo = {} # Costo generado
pathGenerated[(self.x, self.y)] = None # Inicializamos el camino
costUpTo[(self.x, self.y)] = 0 # y los costos
while not neighbors.empty(): # Mientras haya vecinos
current = neighbors.pop() # obtenemos el mejor vecino
testBoard[current[0]][current[1]] = True # lo marcamos usado
if current == (self.xTarget, self.yTarget): # si es el objetivo nos salimos
break
frontier = self.computeNeighbors(current, testBoard) # Si no, le sacamos los vecinos
if frontier: # si no está vacía
for node in frontier: # Y para cada uno
newCost = costUpTo[current] + 1 # Costo de viajar al siguiente es 1
if node not in costUpTo or newCost < costUpTo[node]: # si el nodo no ha sido visitado o el costo es menor
costUpTo[node] = newCost # vamos a recorrerlo y añadirlo
priority = newCost + manhattan(node, (self.xTarget, self.yTarget)) # creamos su prioridad
neighbors.push(node, priority) # lo metemos en el heap
pathGenerated[node] = current # y en el camino
for key in pathGenerated: # metemos el camino
self.pathTarget.push(key) # para que lo visitemos
# Busqueda de camino con BFS
def bfs(self): # calcula el camino a seguir
testBoard = usedBoard # creamos el tablero de prueba para inundar
neighbors = Queue() # cola de nodos a visitar
neighbors.push((self.x, self.y)) # metemos el nodo actual
while not neighbors.empty(): # mientras haya nodos por inundar
current = neighbors.pop() # obtenemos el nodo de la cola
self.pathTarget.push(current)
# Si llegamos al objetivo, terminar y salir
if current[0] == self.xTarget and current[1] == self.yTarget:
break
testBoard[current[0]][current[1]] = True # Marcar como usado
frontier = self.computeNeighbors(current, testBoard) # Obtener vecinos del nodo actual
if frontier: # actualizar la cola
for node in frontier:
neighbors.push(node)
# para crear un nuevo juego
def new_game():
new_p1 = Player((-2, 0)) # IA de dificultad aleatoria
new_p2 = Player((2, 0), True) # Jugador
return new_p1, new_p2
width, height = 600, 660 # dimensiones de la ventana
offset = height - width # espacio vertical extra
usedBoard = [[False] * width for _ in range(height-offset)] # para uso con la BFS y la A*
screen = pygame.display.set_mode((width, height)) # crea la ventana
pygame.display.set_caption("Tron") # coloca el titulo del juego
font = pygame.font.Font(None, 72) # cambiamos el tamaño de la fuente
clock = pygame.time.Clock() # para regular los FPS
check_time = time.time() # para revisar colisiones en tiempo y forma
objects = list() # lista de todosl os jugadores
path = list() # lista de todos los caminos ya recorridos
p1 = Player((-2, 0)) # crea IA
p2 = Player((2, 0), True) # crea al jugador
objects.append(p1) # metemos la IA
path.append((p1.rect, '1')) # metemos su objeto en el camino
objects.append(p2) # ahora ocn el jugador
path.append((p2.rect, '2'))
player_score = [0, 0] # puntuaciones
wall_rects = [pygame.Rect([0, offset, 15, height]) , pygame.Rect([0, offset, width, 15]),\
pygame.Rect([width - 15, offset, 15, height]),\
pygame.Rect([0, height - 15, width, 15])] # los muros de fuera de la ventana
# variables de uso
done = False
new = False
while not done:
for event in pygame.event.get(): # obtener todos los eventos ocurridos
if event.type == pygame.QUIT: # cerrar el juego
done = True
elif event.type == pygame.KEYDOWN: # tecla presionada
# Movimientos del jugador
# >Flechas para moverse
# >Nitro con shift derecho
# Esta parte se puede activar para 2 jugadores, solo se descomenta y juega con WASD y TAB
# if event.key == pygame.K_w and objects[0].direction != (0, 2):
# objects[0].direction = (0, -2)
# elif event.key == pygame.K_s and objects[0].direction != (0, -2):
# objects[0].direction = (0, 2)
# elif event.key == pygame.K_a and objects[0].direction != (2, 0):
# objects[0].direction = (-2, 0)
# elif event.key == pygame.K_d and objects[0].direction != (-2, 0):
# objects[0].direction = (2, 0)
# elif event.key == pygame.K_TAB:
# objects[0].__boost__()
# Aquí comienzan los movimientos del jugador
if event.key == pygame.K_UP and objects[1].direction != (0, 2):
objects[1].direction = (0, -2)
elif event.key == pygame.K_DOWN and objects[1].direction != (0, -2):
objects[1].direction = (0, 2)
elif event.key == pygame.K_LEFT and objects[1].direction != (2, 0):
objects[1].direction = (-2, 0)
elif event.key == pygame.K_RIGHT and objects[1].direction != (-2, 0):
objects[1].direction = (2, 0)
elif event.key == pygame.K_RSHIFT:
objects[1].__boost__()
screen.fill(BLACK) # limpia la pantalla
for r in wall_rects: # para cada rectangulo
pygame.draw.rect(screen, (42, 42, 42), r, 0) # dibuja los muros
for obj in objects:
if time.time() - obj.start_boost >= 0.5: # limita el nitro a 0.5s
obj.boost = False
# Revisar colisiones
if (obj.rect, '1') in path or (obj.rect, '2') in path or obj.rect.collidelist(wall_rects) > -1: # choco con el camino o muro
# previene chocar consigo mismo
if (time.time() - check_time) >= 0.1:
check_time = time.time()
#puntuaciones
if obj.colour == P1_COLOUR:
player_score[1] += 1
else:
player_score[0] += 1
usedBoard = [[False] * width for _ in range(height-offset)] # para uso con la BFS y la A*
new = True
new_p1, new_p2 = new_game()
objects = [new_p1, new_p2]
path = [(p1.rect, '1'), (p2.rect, '2')]
break
else: # sin atravesar
path.append((obj.rect, '1')) if obj.colour == P1_COLOUR else path.append((obj.rect, '2'))
obj.__draw__()
obj.move()
for r in path:
if new is True: # vacía el camino, evita glitches
path = []
new = False
break
if r[1] == '1':
pygame.draw.rect(screen, P1_COLOUR, r[0], 0)
else:
pygame.draw.rect(screen, P2_COLOUR, r[0], 0)
# muestra las puntuaciones
score_text = font.render('{0} : {1}'.format(player_score[0], player_score[1]), 1, (255, 153, 51))
score_text_pos = score_text.get_rect()
score_text_pos.centerx = width // 2
score_text_pos.centery = offset // 2
screen.blit(score_text, score_text_pos)
pygame.display.flip() # voltea el display
clock.tick(60) # regula los FPS
pygame.quit()