i'm trying to make an brick destroyer game on python with TKinter for my school project, it's barely finished but i have a problem when it's about to break some bricks. It says that the list index is out of range and i don't know how can i make this.
import tkinter
import time
from tkinter import *
fen = Tk()
fen.title("Casse brique")
bou1 = Button(fen, text="Quitter", command=fen.destroy)
can1 = Canvas(fen,bg="Black" ,height=900 ,width=1300)
x1 = 490
y1 = 750
def avance(gd, hb):
global x1,y1
x1,y1 = (x1 + gd) % 1000, (y1+hb) % 1000
can1.coords(bar,x1,y1,x1+300,y1+30)
def depl_droit(event=None):
avance(20,0)
def depl_gauche(event=None):
avance(-20,0)
can1.bind_all("<Right>",depl_droit)
can1.bind_all("<Left>",depl_gauche)
can1.pack()
bou1.pack(padx=5, pady=5)
a = 490
b = 750
c = 790
d = 780
bar = can1.create_rectangle(a,b,c,d, fill='white')
def start():
start_button.config(state=DISABLED)
Balle = can1.create_rectangle(405, 405, 435, 435, fill="Blue")#x0 y0 x2 y2
brique1 = can1.create_rectangle(50,100,250,180, fill='white')#x0 y0 x2 y2
X_Axis_Speed = 5
Y_Axis_Speed = 5
while True:
can1.move(Balle,X_Axis_Speed,Y_Axis_Speed)
pos_balle = can1.coords(Balle)
if pos_balle[2]>1300 or pos_balle[0]<=0: #droite --- gauche
X_Axis_Speed = -X_Axis_Speed
if pos_balle[1]<=0: # top
Y_Axis_Speed = -Y_Axis_Speed
if (can1.coords(Balle)[3]==can1.coords(bar)[1]) and can1.coords(Balle)[0]<can1.coords(bar)[2] and can1.coords(Balle)[2]>can1.coords(bar)[0]: #barre
Y_Axis_Speed = -Y_Axis_Speed
if pos_balle[3]==900: #bot
can1.delete(Balle)
start_button.config(state=NORMAL)
lose = Toplevel(fen)
lose.geometry('150x150')
rt = Button(lose,text="Réessayer",command=lose.destroy)
label = Label(lose, text="Tu as perdu ! réessaye")
label.pack()
rt.pack()
return
if (pos_balle[0]==can1.coords(brique1)[2]) and pos_balle[3]<can1.coords(brique1)[3]:
can1.delete(brique1)
fen.update()
time.sleep(0.01)
start_button = Button(fen,text="Démarrer", command=start)
start_button.pack()
fen.mainloop()
Thanks in advance ^^ (Sorry for the variable name i'm french and my teacher will think that i find on internet if i wrote it in english)
I modified your line 58 so I could break when the error happens. The pos_balle list was sufficiently long. The other list was returned from a function call so I added the var 'x' to capture it. It is an empty list. This is not your root problem and I'm not familiar with using canvases so that's as far as I went. I wanted to share with you to show you a little of debug techiniques and maybe this will point you in the right direction. Good luck.
try:
x = can1.coords(brique1)
if (pos_balle[0]==can1.coords(brique1)[2]) and pos_balle[3]<can1.coords(brique1)[3]:
can1.delete(brique1)
except Exception as e:
print(e)
pass
Related
I create empty list and add name of detected objects to in it.
the output to new list every loop added one object and output it directly without waiting to finish adding
I just need the output all objects as list output and disappear rest outputs
this my code:
import rospy
import numpy
import tf
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs import point_cloud2 as pc2
from sensor_msgs.msg import Image, PointCloud2
from dodo_detector.detection import SingleShotDetector
from dodo_detector_ros.msg import DetectedObject, DetectedObjectArray
import math
class Detector:
def __init__(self):
self._detector = SingleShotDetector('frozen_inference_graph.pb', 'mscoco_label_map.pbtxt', confidence=0.5)
self._global_frame = rospy.get_param('~global_frame', None)
self._tf_listener = tf.TransformListener()
self._bridge = CvBridge()
rospy.Subscriber("/camera/rgb/image_color", Image, self.image_callback)
rospy.Subscriber('/camera/depth/points', PointCloud2, self.pc_callback)
self._current_image = None
self._current_pc = None
self._imagepub = rospy.Publisher('~labeled_image', Image, queue_size=10)
self._publishers = {None: (None, rospy.Publisher('~detected', DetectedObjectArray, queue_size=10))}
self._tfpub = tf.TransformBroadcaster()
rospy.loginfo('Ready to detect!')
def image_callback(self, image):
"""Image callback"""
self._current_image = image
def pc_callback(self, pc):
"""Point cloud callback"""
self._current_pc = pc
def run(self):
while not rospy.is_shutdown():
if self._current_image is not None:
try:
if self._global_frame is not None:
(trans, _) = self._tf_listener.lookupTransform('/' + self._global_frame, '/camera_link', rospy.Time(0))
scene = self._bridge.imgmsg_to_cv2(self._current_image, 'rgb8')
marked_image, objects = self._detector.from_image(scene) # detect objects
self._imagepub.publish(self._bridge.cv2_to_imgmsg(marked_image, 'rgb8')) # publish detection results
msgs = {}
for key in self._publishers:
msgs[key] = DetectedObjectArray()
my_tf_id = []
my_dis =[]
for obj_class in objects:
rospy.logdebug('Found ' + str(len(objects[obj_class])) + ' object(s) of type ' + obj_class)
for obj_type_index, coordinates in enumerate(objects[obj_class]):
#
rospy.logdebug('...' + obj_class + ' ' + str(obj_type_index) + ' at ' + str(coordinates))
ymin, xmin, ymax, xmax = coordinates
y_center = ymax - ((ymax - ymin) / 2)
x_center = xmax - ((xmax - xmin) / 2)
detected_object = DetectedObject()
detected_object.type.data = obj_class
detected_object.image_x.data = xmin
detected_object.image_y.data = ymin
detected_object.image_width.data = xmax - xmin
detected_object.image_height.data = ymax - ymin
publish_tf = False
if self._current_pc is None:
rospy.loginfo('No point cloud information available to track current object in scene')
else:
pc_list = list(pc2.read_points(self._current_pc, skip_nans=True, field_names=('x', 'y', 'z'), uvs=[(x_center, y_center)]))
if len(pc_list) > 0:
publish_tf = True
tf_id = obj_class + '_' + str(obj_type_index) #object_number
my_tf_id.append(tf_id)
print my_tf_id
detected_object.tf_id.data = tf_id
point_x, point_y, point_z = pc_list[0] #point_z = x, point_x = y
if publish_tf:
object_tf = [point_z, -point_x, -point_y]
frame = 'cam_asus_link'
if self._global_frame is not None:
object_tf = numpy.array(trans) + object_tf
frame = self._global_frame
self._tfpub.sendTransform((object_tf), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), tf_id, frame)
except CvBridgeError as e:
print(e)
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException) as e:
print(e)
if __name__ == '__main__':
rospy.init_node('dodo_detector_ros', log_level=rospy.INFO)
try:
Detector().run()
except KeyboardInterrupt:
rospy.loginfo('Shutting down')
I used line 120
print my_tf_id
output:
[u'person_0']
[u'person_0', u'chair_0']
[u'person_0', u'chair_0', u'chair_1']
[u'person_0', u'chair_0', u'chair_1', u'book_0']
[u'person_0', u'chair_0', u'chair_1', u'book_0', u'book_1']
I just need this output:
[u'person_0', u'chair_0', u'chair_1', u'book_0', u'book_1']
and disappear those outputs:
[u'person_0']
[u'person_0', u'chair_0']
[u'person_0', u'chair_0', u'chair_1']
[u'person_0', u'chair_0', u'chair_1', u'book_0']
please help me
thank you in advance or some suggestions
Just to reiterate your question, you are creating a list on the fly and only want to display the last element you are adding. In general when asking a question like this, please create a simple example relevant to your question. No point adding complications from ROS, subcribers and callbacks etc.
To your questions, here are a couple ways to handle this:
Print your reponse only after you finish your loop, this will print everything just once.
Print just the last element you added, tf_id in your case. If you want it on the same line you can use print statement as: print(tf_id, end='', flush=True)
You I have been trying to run this script but I keep getting an indentation error at the end
of the backprop(x,y) function. I would really appreciate ANY help!!
import cPickle
import gzip
def load_data():
f = gzip.open('mnist.pkl.gz', 'rb')
training_data, validation_data, test_data = cPickle.load(f)
f.close()
return (training_data, validation_data, test_data)
import numpy as np
class Network(object):
def __init__(self, layers):
self.layers = layers
self.biases = [np.random.randn(y,1) for y
in layers[1:]]
self.weights = [np.transpose(np.random.randn(x,y))
for x,y
in zip(layers[:-1],layers[1:])]
self.num_layers = len(layers)
def backprop(self, x, y):
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = self.cost_derivative(activations[-1], y) * \
sigmoid_prime(zs[-1])#set first delta
nabla_b[-1] = delta#set last dC/db to delta vector
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
#calculate nabla_b, nabla_w for the rest of the layers
for l in xrange(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
#this is where python says there is an indent error!
return (nabla_b, nabla_w)
The problem was fixed by selecting the "edit" drop-down menu of Notepad++, choosing Blank Operations, and finally, clicking 'TAB to spaces'; obviously, this should be done after selecting the portion of code that's triggering the error.
I have this 7 quasi-lorentzian curves which are fitted to my data.
and I would like to join them, to make one connected curved line. Do You have any ideas how to do this? I've read about ComposingModel at lmfit documentation, but it's not clear how to do this.
Here is a sample of my code of two fitted curves.
for dataset in [Bxfft]:
dataset = np.asarray(dataset)
freqs, psd = signal.welch(dataset, fs=266336/300, window='hamming', nperseg=16192, scaling='spectrum')
plt.semilogy(freqs[0:-7000], psd[0:-7000]/dataset.size**0, color='r', label='Bx')
x = freqs[100:-7900]
y = psd[100:-7900]
# 8 Hz
model = Model(lorentzian)
params = model.make_params(amp=6, cen=5, sig=1, e=0)
result = model.fit(y, params, x=x)
final_fit = result.best_fit
print "8 Hz mode"
print(result.fit_report(min_correl=0.25))
plt.plot(x, final_fit, 'k-', linewidth=2)
# 14 Hz
x2 = freqs[220:-7780]
y2 = psd[220:-7780]
model2 = Model(lorentzian)
pars2 = model2.make_params(amp=6, cen=10, sig=3, e=0)
pars2['amp'].value = 6
result2 = model2.fit(y2, pars2, x=x2)
final_fit2 = result2.best_fit
print "14 Hz mode"
print(result2.fit_report(min_correl=0.25))
plt.plot(x2, final_fit2, 'k-', linewidth=2)
UPDATE!!!
I've used some hints from user #MNewville, who posted an answer and using his code I got this:
So my code is similar to his, but extended with each peak. What I'm struggling now is replacing ready LorentzModel with my own.
The problem is when I do this, the code gives me an error like this.
C:\Python27\lib\site-packages\lmfit\printfuncs.py:153: RuntimeWarning:
invalid value encountered in double_scalars [[Model]] spercent =
'({0:.2%})'.format(abs(par.stderr/par.value))
About my own model:
def lorentzian(x, amp, cen, sig, e):
return (amp*(1-e)) / ((pow((1.0 * x - cen), 2)) + (pow(sig, 2)))
peak1 = Model(lorentzian, prefix='p1_')
peak2 = Model(lorentzian, prefix='p2_')
peak3 = Model(lorentzian, prefix='p3_')
# make composite by adding (or multiplying, etc) components
model = peak1 + peak2 + peak3
# make parameters for the full model, setting initial values
# using the prefixes
params = model.make_params(p1_amp=6, p1_cen=8, p1_sig=1, p1_e=0,
p2_ampe=16, p2_cen=14, p2_sig=3, p2_e=0,
p3_amp=16, p3_cen=21, p3_sig=3, p3_e=0,)
rest of the code is similar like at #MNewville
[![enter image description here][3]][3]
A composite model for 3 Lorentzians would look like this:
from lmfit import Model, LorentzianModel
peak1 = LorentzianModel(prefix='p1_')
peak2 = LorentzianModel(prefix='p2_')
peak3 = LorentzianModel(prefix='p3_')
# make composite by adding (or multiplying, etc) components
model = peak1 + peaks2 + peak3
# make parameters for the full model, setting initial values
# using the prefixes
params = model.make_params(p1_amplitude=10, p1_center=8, p1_sigma=3,
p2_amplitude=10, p2_center=15, p2_sigma=3,
p3_amplitude=10, p3_center=20, p3_sigma=3)
# perhaps set bounds to prevent peaks from swapping or crazy values
params['p1_amplitude'].min = 0
params['p2_amplitude'].min = 0
params['p3_amplitude'].min = 0
params['p1_sigma'].min = 0
params['p2_sigma'].min = 0
params['p3_sigma'].min = 0
params['p1_center'].min = 2
params['p1_center'].max = 11
params['p2_center'].min = 10
params['p2_center'].max = 18
params['p3_center'].min = 17
params['p3_center'].max = 25
# then do a fit over the full data range
result = model.fit(y, params, x=x)
I think the key parts you were missing were: a) just add models together, and b) use prefix to avoid name collisions of parameters.
I hope that is enough to get you started...
Trying to build a simple game using turtle graphics and Python.
I created enemies and put them in the while loop so that whenever they touch the boundaries on either sides they move down by 40 units. I put the value of y co-ordinate in a variable u. But when I run the code it says:
nameError: 'u' not defined
Help!!
#!/usr/bin/python
import turtle
import os
#screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("spaceinvaders")
#boarder
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
#player
player = turtle.Turtle()
player.color("blue")
player.shape("triangle")
player.penup()
player.speed(0)
player.setposition(0,-250)
player.setheading(90)
playerspeed = 15
#enemy
enemy = turtle.Turtle()
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.speed(0)
enemy.setposition(-200,250)
enemyspeed = 2
#move
def move_left():
x = player.xcor()
x -= playerspeed
if x < -280:
x = - 280
player.setx(x)
def move_right():
x = player.xcor()
x += playerspeed
if x > 280:
x = +280
player.setx(x)
#key bindings
turtle.listen()
turtle.onkey(move_left,"Left")
turtle.onkey(move_right,"Right")
#mainloop
while True:
#enemy moves
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
if enemy.xcor() < -280:
u = enemy.ycor()
u -= 40
enemyspeed *= -1
enemy.sety(u)
if enemy.xcor() > 280:
u = enemy.ycor()
u -= 40
enemyspeed *= -1
enemy.sety(u)
delay = raw_input("press enter to finish")
Even with the incorrect loop indentation that #downshift noted, you shouldn't have gotten the error you quoted as u is set immediately before being used.
The main problem I see with your code design is your use of while True: which should not occur in an event driven program. Rather, the enemy's motion should be handled via a timer event and program control turned over to mainloop() so that other events can fire correctly. I've reworked your program along those lines below and made some style and optimizaion tweaks:
import turtle
# player motion event handlers
def move_left():
turtle.onkey(None, 'Left') # avoid overlapping events
player.setx(max(-280, player.xcor() - playerspeed))
turtle.onkey(move_left, 'Left')
def move_right():
turtle.onkey(None, 'Right')
player.setx(min(280, player.xcor() + playerspeed))
turtle.onkey(move_right, 'Right')
# enemy motion timer event handler
def move_enemy():
global enemyspeed
# enemy moves
enemy.forward(enemyspeed)
x = enemy.xcor()
if x < -280 or x > 280:
enemy.sety(enemy.ycor() - 40)
enemyspeed *= -1
wn.ontimer(move_enemy, 10)
# screen
wn = turtle.Screen()
wn.bgcolor('black')
wn.title('spaceinvaders')
# border
STAMP_SIZE = 20
border_pen = turtle.Turtle('square', visible=False)
border_pen.shapesize(600 / STAMP_SIZE, 600 / STAMP_SIZE, 3)
border_pen.pencolor('white')
border_pen.stamp()
# player
player = turtle.Turtle('triangle', visible=False)
player.color('blue')
player.speed('fastest')
player.penup()
player.setheading(90)
player.setposition(0, -250)
player.showturtle()
playerspeed = 15
# enemy
enemy = turtle.Turtle('circle', visible=False)
enemy.color('red')
enemy.speed('fastest')
enemy.penup()
enemy.setposition(-200, 250)
enemy.showturtle()
enemyspeed = 2
# key bindings
turtle.onkey(move_left, 'Left')
turtle.onkey(move_right, 'Right')
turtle.listen()
wn.ontimer(move_enemy, 100)
turtle.mainloop() # for Python 3 use wn.mainloop()
This should hopefully smooth your path to adding more functionality to your game.
Hi I installed pyinstaller and pywin32 64 bit version to get an .exe.
I did get a .exe built, but when I double click on it, it just flashes on the screen and closes. I used this as a setup.py
from distutils.core import setup
import py2exe
setup(console=['BP.py'])
The script BP.py asks the user to input some values and make some plots.
Any ideas?
Thanks
Below is the code
Code for BP.py is below
##
##BP.py
import matplotlib.pyplot as plt
import numpy as np
# A function to plot the lines
def plot_lines(x,y,colors,j):
ax = plt.subplot(2,2,j)
for i in range(len(colors)):
plt.plot(x,y[i],colors[i])
def plot_setup():
fig = plt.figure()
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
def Max_avg(row,col,x,colors,ao1,ao2,j,a_list):
for a in a_list:
i = 0
y_a1 = np.zeros((row,col))
y_a2 = np.zeros((row,col))
y = np.zeros((row,col))
for ao1_v,ao2_v in zip(ao1,ao2):
y_a1[i] = 3*x**2
y_a2[i] = 5*x
y[i] = np.add(y_a1[i],y_a2[i])
i = i+1
plot_lines(x,y,colors,j)`enter code here`
j = j+1
def main():
x1 = -10
x2 = 10
numpts = 100
x = np.linspace(x1,x2,numpts,endpoint=True)
col = len(x)
# a_list = [-1.7,-5]
print "Please enter a list of coefficients seperated by a white space."
string_input = raw_input()
a_list = string_input.split()
a_list = [int(a) for a in a_list]
ao1 = (-5.0,2.0)
ao2 = (1.0,10.0)
col_plt = 2
colors = ['b','g']
j = 1
plot_setup()
Max_avg(2,col,x,colors,ao1,ao2,j,a_list)
plt.show()
if __name__ == "__main__":
main()