I wrote this code with turtle library. The problem is that when I run this code in IDLE,everything works fine until it gets to the input in the function 'putBall()' ,and the window become 'not responding'.
I tried several suggestions from google like 'turtle.done' in end of code or 'turtle.done' in the end of each one of the functions,but in seems do nothing in both cases.
I want to add that I tried this code in online service 'Trinket' and it work fine.
import turtle
def initialize_pen_screen():
s=turtle.getscreen()
s.setup(600,600)
t = turtle.Turtle()
ballOne = turtle.Turtle()
ballOne.shape('turtle')
ballOne.fillcolor("red")
ballOne.pencolor("red")
ballTwo = turtle.Turtle()
ballTwo.shape('turtle')
ballTwo.fillcolor("blue")
ballTwo.pencolor("blue")
t.shape("turtle")
s.bgcolor("gray")
return [t,ballOne,ballTwo]
def initialize_pen_screen_saviour():
t = turtle.Turtle()
ballOne = turtle.Turtle()
ballOne.shape('turtle')
ballOne.fillcolor("red")
ballOne.pencolor("red")
ballTwo = turtle.Turtle()
ballTwo.shape('turtle')
ballTwo.fillcolor("blue")
ballTwo.pencolor("blue")
t.shape("turtle")
return [t,ballOne,ballTwo]
def initialize_first(t,ballOne,ballTwo):
t.rt(180)
t.penup()
t.fd(150)
t.lt(90)
t.pensize(10)
ballOne.lt(90)
ballOne.penup()
ballOne.fd(90)
ballTwo.lt(90)
ballTwo.penup()
ballTwo.fd(150)
ballOne.rt(90)
ballTwo.rt(90)
#draw line that goes down
def stamp_up(t):
t.pendown()
t.stamp()
t.fd(250) #depends how long column
#print(t.pos(),'UP')
t.lt(90)
t.penup()
#draw line that goes up
def stamp_down(t):
t.fd(70)
#print(t.pos(),'Down')
t.lt(90)
t.pendown()
t.stamp()
t.fd(250) #depends how long column
t.rt(90)
t.penup()
t.fd(70)
t.rt(90)
#draw ball and save coordinate of reserved position in column
def move_ball(chosenBall,x,y):
chosenBall.goto(x+20,y+20)
chosenBall.fd(15)
chosenBall.dot(50)
newClosedPos=[x,y+50]
chosenBall.goto(0,150)
return newClosedPos
#put ball in table,and save another reserved position in column
def putBall(currentMove):
print("which column to put your ball?")
column=input()
if(column=='1'):
x=closedColumnOne[len(closedColumnOne)-1][0]
y=closedColumnOne[len(closedColumnOne)-1][1]
newClose=move_ball(currentMove,x,y)
closedColumnOne.append(newClose)
elif(column=='2'):
x=closedColumnTwo[len(closedColumnTwo)-1][0]
y=closedColumnTwo[len(closedColumnTwo)-1][1]
newClose=move_ball(currentMove,x,y)
closedColumnTwo.append(newClose)
elif(column=='3'):
x=closedColumnThree[len(closedColumnThree)-1][0]
y=closedColumnThree[len(closedColumnThree)-1][1]
newClose=move_ball(currentMove,x,y)
closedColumnThree.append(newClose)
elif(column=='4'):
x=closedColumnFour[len(closedColumnFour)-1][0]
y=closedColumnFour[len(closedColumnFour)-1][1]
newClose=move_ball(currentMove,x,y)
closedColumnFour.append(newClose)
elif(column=='5'):
x=closedColumnFive[len(closedColumnFive)-1][0]
y=closedColumnFive[len(closedColumnFive)-1][1]
newClose=move_ball(currentMove,x,y)
closedColumnFive.append(newClose)
return column
#tell state of world after put ball in table
def afterPutBall(SelectedColumn,columnBalls,tableSize,tableBall):
for k in range(0,tableSize):
for i in range(0,tableSize):
if(int(SelectedColumn)==k+1 and columnBalls[k][i]==0):
columnBalls[k][i]=tableBall
break
else:
continue
break
return columnBalls
#check if we in a win state
def checkWin(tableSize,columnBalls):
for k in range(0,tableSize-1):
for i in range(0,tableSize-1):
flagRow=1
flagColumn=1
flagDiagonalRight=1
flagDiagonalLeft=1
for j in range(0,tableSize-1):
#row win
if(columnBalls[j][i]==columnBalls[j+1][i] and columnBalls[j][i]!=0):
flagRow+=1
elif(flagRow!=0):
flagRow=1
#column win
if(columnBalls[i][j]==columnBalls[i][j+1] and columnBalls[i][j]!=0):
flagColumn+=1
#print(flagColumn)
elif(flagColumn!=0):
flagColumn=1
#diagonal right
if(i+j+1<=tableSize-1 and i+j<=tableSize-1 and j+k<=tableSize-1 and j+k+1<=tableSize-1): #end table
if(columnBalls[j+k][i+j]==columnBalls[j+k+1][i+j+1] and columnBalls[j+k][i+j]!=0):
flagDiagonalRight+=1
elif(flagDiagonalRight!=0):
flagDiagonalRight=1
#diagonal left
if(tableSize-j-i-1>=0 and tableSize-j-i-2>=0 and j+k<=tableSize-1 and j+k+1<=tableSize-1): #end table
if(columnBalls[j+k][tableSize-j-i-1]==columnBalls[j+k+1][tableSize-j-i-2] and columnBalls[j+k][tableSize-j-i-1]!=0):
flagDiagonalLeft+=1
elif(flagDiagonalLeft!=0):
flagDiagonalLeft=1
if flagRow==4 or flagColumn==4 or flagDiagonalLeft==4 or flagDiagonalRight==4:
return True
return False
def score_board():
score=turtle.Turtle()
score.ht()
score.color("green")
#score board
turtle.pensize(5)
turtle.speed(6)
turtle.penup()
turtle.goto(-250,150)
turtle.pendown()
turtle.rt(90)
for i in range(0,2):
turtle.fd(100)
turtle.lt(90)
turtle.fd(130)
turtle.lt(90)
turtle.fd(100)
turtle.lt(90)
turtle.fd(150-i*20)
turtle.lt(90)
turtle.penup()
turtle.ht()
#turtle.setposition(150,100)
#score write
score.speed('fastest')
score.penup()
score.goto(-250,150)
score.rt(90)
score.fd(50)
score.lt(90)
score.fd(35)
return score
def write_score(score,redPoints,bluePoints):
score.clear()
score.write(str(redPoints)+'-'+str(bluePoints),move=False ,font=("Verdana",
18, "normal"), align="left")
#build table
def build_table(tableSize,table,opponentOne,opponentTwo):
table.speed(6)
initialize_first(table,opponentOne,opponentTwo)
size_iter=int((tableSize-1)/2)
for i in range(0,size_iter+1):
stamp_up(table)
stamp_down(table)
if(tableSize%2==0): #even size table
stamp_up(table)
table.goto(0,250)
table.lt(90)
#tableSize=(2*(i+1)-1)
if 'main':
playAgain='yes'
s=turtle.getscreen()
s.setup(1000,1000)
s.bgcolor("gray")
score=score_board()
redPoints=0
bluePoints=0
while(playAgain=='yes' or playAgain=='Yes'):
tools=initialize_pen_screen_saviour()
table=tools[0]
opponentOne=tools[1]
opponentTwo=tools[2]
closedColumnOne=[[-150.0, -250.0]]
closedColumnTwo=[[-80.0, -250.0]]
closedColumnThree=[[-10.0, -250.0]]
closedColumnFour=[[60.0, -250.0]]
closedColumnFive=[[130.0, -250.0]]
tableSize=8
build_table(tableSize,table,opponentOne,opponentTwo)
#initilize table state balls
columnBalls=[]
for i in range(0,tableSize):
columnBall=[0]*tableSize
columnBalls.append(columnBall)
print(columnBalls)
myBall='A'
playAgain='yes'
#max moves:25
for i in range(0,25):
win=False
print("Player "+myBall+" play now")
if(myBall=='A'):
currentMove=opponentOne
myBall='B'
tableBall='A'
else:
currentMove=opponentTwo
myBall='A'
tableBall='B'
SelectedColumn=putBall(currentMove)
columnBalls=afterPutBall(SelectedColumn,columnBalls,tableSize,tableBall)
print(columnBalls)
win=checkWin(tableSize,columnBalls)
if(win):
#update score player blue
if(tableBall=='B'):
write_score(score,redPoints,bluePoints+1)
bluePoints+=1
#update score player red
else:
write_score(score,redPoints+1,bluePoints)
redPoints+=1
print('player '+tableBall+' WIN!!')
print('Do you want to play again?')
playAgain=input()
if(playAgain=='no' or playAgain=='No'):
break
elif(playAgain=='yes' or playAgain=='Yes'):
table.reset()
opponentOne.reset()
opponentTwo.reset()
break
#t.reset()
#t.clear()
Please read https://stackoverflow.com/help/minimal-reproducible-example.
Lines 80-81 of your code
print("which column to put your ball?")
column=input('')
print a prompt to the interactive shell and pause the turtle screen while the turtle code waits for a response entered in the separate shell or terminal window. (column = input('which column' would do the same.) To enter a column, the user must click on the window with the 'which column' prompt. One you do so, entering numbers works fine.
A difference between IDLE and other ways from running a Python module is that IDLE sends your code to a separate process, different from the IDLE UI process, for execution. I believe that this is why clicking on the turtle window gives you the paused message that does not appear when running your code otherwise. I would have to do more experiements to determine whether this is true for all turtle programs that seek input from the terminal/shell.
In any case, it is not normal for GUI programs to request input from the terminal/shell. Turtle provides textinput and numinput methods and function. Try using one of them.
I encounter the error message when doing DirectCollocation with collision geometry:
RuntimeError: InputPort::Eval(): required InputPort[0] (geometry_query) of System ::drake/multibody/MultibodyPlant#0000000003550740 (MultibodyPlant<drake::AutoDiffXd>) is not connected
Based on the previous question, I have added both connections as follows, but still not fix the bug.
builder.Connect(plant.get_geometry_poses_output_port(),
scene_graph.get_source_pose_port(plant.get_source_id()))
builder.Connect(scene_graph.get_query_output_port(),
plant.get_geometry_query_input_port())
This is my code skeleton:
builder = DiagramBuilder()
scene_graph = builder.AddSystem(SceneGraph())
# Make and add the model
tmp = make_acrobot_plant(params, finalize, scene_graph)
plant = builder.AddSystem(tmp)
plant.Finalize()
# https://drake.mit.edu/doxygen_cxx/classdrake_1_1multibody_1_1_multibody_plant.html
builder.Connect(plant.get_geometry_poses_output_port(),
scene_graph.get_source_pose_port(plant.get_source_id()))
builder.Connect(scene_graph.get_query_output_port(),
plant.get_geometry_query_input_port())
num_time_samples = 40
dircol = DirectCollocation(
plant,
context,
num_time_samples=num_time_samples,
minimum_timestep=0.01,
maximum_timestep=0.05,
input_port_index=plant.get_actuation_input_port().get_index())
dircol.AddEqualTimeIntervalsConstraints()
u = dircol.input()
dircol.AddRunningCost(Ru * u.dot(u))
dircol.SetInitialTrajectory(traj_init_u, traj_init_x)
result = Solve(dircol)
assert result.is_success()
# Connect
# Simulate u
controls = builder.AddSystem(TrajectorySource(u_trajectory))
builder.Connect(
controls.get_output_port(0), plant.get_actuation_input_port())
'''
# Simulate x
source = builder.AddSystem(TrajectorySource(x_trajectory))
pos_to_pose = builder.AddSystem(
MultibodyPositionToGeometryPose(plant, input_multibody_state=True))
builder.Connect(source.get_output_port(0), pos_to_pose.get_input_port())
builder.Connect(pos_to_pose.get_output_port(),
scene_graph.get_source_pose_port(plant.get_source_id()))
'''
# ...
# Visualization:
builder.Connect(scene_graph.get_pose_bundle_output_port(),
planar_scene_graph_vis.get_input_port(0))
diagram = builder.Build()
You are close, but you have only passed the plant into DirectCollocation. You need to pass the diagram with plant+scenegraph into DirectCollocation. (And you will also need to assume_non_continuous_states_are_fixed=true to ignore the SceneGraph's abstract state).
I've run into an issue with the TabularAdapter in the TraitsUI package...
I've been trying to figure this out on my own for much too long now, so I wanted to ask the experts here for some friendly advise :)
I'm going to add a piece of my program that illustrates my problem(s), and I'm hoping someone can look it over and say 'Ah Ha!...Here's your problem' (my fingers are crossed).
Basically, I can use the TabularAdapter to produce a table editor into an array of dtypes, and it works just fine except:
1) whenever I change the # of elements (identified as 'Number of fractures:'), the array gets resized, but the table doesn't reflect the change until after I click on one of the elements. What I'd like to happen is that the # of rows (fractures) changes after I release the # of fractures slider. Is this doable?
2) The second issue I have is that if the array gets resized before it's displayed by .configure_traits() (by the notifier when Number_of_fractures gets modified), I can shrink the size of the array, but I can't increase it over the new size.
2b) I thought I'd found a way to have the table editor display the full array even when it's increased over the 5 set in the code (just before calling .trait_configure()), but I was fooled :( I tried adding another Group() in front of the vertical_fracture_group so the table wasn't the first thing to display. This more closely emulates my entire program. When I did this, I was locked into the new smaller size of the array, and I could no longer increase its size to my maximum of 15. I'm modifying the code to reflect this issue.
Here's my sample code:
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import zeros, dtype
from traits.api import HasTraits, Range
from traitsui.api import View, Group, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
vertical_frac_array = zeros((max_cracks), dtype=vertical_frac_dtype)
vertical_fracture_group = Group(
Item(name = 'vertical_frac_array',
show_label = False,
editor = TabularEditor(adapter = VertFractureAdapter()),
width = 0.5,
height = 0.5,
)
)
#-- THIS is the actual 'View' that gets put on the screen
view = View(
#Note: When as this group 'displays' before the one with the Table, I'm 'locked' into my new maximum table display size of 8 (not my original/desired maximum of 15)
Group(
Item( name = 'Number_Of_Fractures'),
),
#Note: If I place this Group() first, my table is free to grow to it's maximum of 15
Group(
Item( name = 'Number_Of_Fractures'),
vertical_fracture_group,
),
width = 0.60,
height = 0.50,
title = '****** Setup',
resizable=True,
)
#-- Traits Event Handlers --------------------------------------------------
def _Number_Of_Fractures_changed(self):
""" Handles resizing arrays if/when the number of Fractures is changed"""
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
#if not self.user_StartingUp:
self.vertical_frac_array.resize(self.Number_Of_Fractures, refcheck=False)
for crk in range(self.Number_Of_Fractures):
self.vertical_frac_array[crk]['Fracture'] = crk+1
self.vertical_frac_array[crk]['x'] = crk
self.vertical_frac_array[crk]['y'] = crk
self.vertical_frac_array[crk]['z'] = crk
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
fileDialog.configure_traits()
fileDialog.Number_Of_Fractures = 8
In my discussion with Chris below, he made some suggestions that so far haven't worked for me :( Following is my 'current' version of this test code so Chris (or anyone else who wishes to chime in) can see if I'm making some glaring error.
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import zeros, dtype
from traits.api import HasTraits, Range, Array, List
from traitsui.api import View, Group, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
even_bg_color = 0xf4f4f4 # very light gray
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
dummy = Range(1, max_cracks)
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
vertical_frac_array = Array(dtype=vertical_frac_dtype)
vertical_fracture_group = Group(
Item(name = 'vertical_frac_array',
show_label = False,
editor = TabularEditor(adapter = VertFractureAdapter()),
width = 0.5,
height = 0.5,
)
)
#-- THIS is the actual 'View' that gets put on the screen
view = View(
Group(
Item( name = 'dummy'),
),
Group(
Item( name = 'Number_Of_Fractures'),
vertical_fracture_group,
),
width = 0.60,
height = 0.50,
title = '****** Setup',
resizable=True,
)
#-- Traits Event Handlers --------------------------------------------------
def _Number_Of_Fractures_changed(self, old, new):
""" Handles resizing arrays if/when the number of Fractures is changed"""
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
vfa = self.vertical_frac_array
vfa.resize(self.Number_Of_Fractures, refcheck=False)
for crk in range(self.Number_Of_Fractures):
vfa[crk]['Fracture'] = crk+1
vfa[crk]['x'] = crk
vfa[crk]['y'] = crk
vfa[crk]['z'] = crk
self.vertical_frac_array = vfa
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
# put the actual dialog up...if I put it up 'first' and then resize the array, I seem to get my full range back :)
fileDialog.configure_traits()
#fileDialog.Number_Of_Fractures = 8
There are two details of the code that are causing the problems you describe. First, vertical_frac_array is not a trait, so the tabular editor cannot monitor it for changes. Hence, the table only refreshes when you manually interact with it. Second, traits does not monitor the contents of an array for changes, but rather the identity of the array. So, resizing and assigning values into the array will not be detected.
One way to fix this is to first make vertical_frac_array and Array trait. E.g. vertical_frac_array = Array(dtype=vertical_frac_dtype). Then, inside of _Number_Of_Fractures_changed, do not resize the vertical_frac_array and modify it in-place. Instead, copy vertical_frac_array, resize it, modify the contents, and then reassign the manipulated copy back to vertical_frac_array. This way the table will see that the identity of the array has changed and will refresh the view.
Another option is to make vertical_frac_array a List instead of an Array. This avoids the copy-and-reassign trick above because traits does monitor the content of lists.
Edit
My solution is below. Instead of resizing the vertical_frac_array whenever Number_Of_Fractures changes, I instead recreate the array. I also provide a default value for vertical_frac_array via the _vertical_frac_array_default method. (I removed from unnecessary code in the view as well.)
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import dtype, zeros
from traits.api import HasTraits, Range, Array
from traitsui.api import View, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
vertical_frac_array = Array(dtype=vertical_frac_dtype)
view = View(
Item('Number_Of_Fractures'),
Item(
'vertical_frac_array',
show_label=False,
editor=TabularEditor(
adapter=VertFractureAdapter(),
),
width=0.5,
height=0.5,
),
width=0.60,
height=0.50,
title='****** Setup',
resizable=True,
)
#-- Traits Defaults -------------------------------------------------------
def _vertical_frac_array_default(self):
""" Creates the default value of the `vertical_frac_array`. """
return self._calculate_frac_array()
#-- Traits Event Handlers -------------------------------------------------
def _Number_Of_Fractures_changed(self):
""" Update `vertical_frac_array` when `Number_Of_Fractures` changes """
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
#if not self.user_StartingUp:
self.vertical_frac_array = self._calculate_frac_array()
#-- Private Interface -----------------------------------------------------
def _calculate_frac_array(self):
arr = zeros(self.Number_Of_Fractures, dtype=vertical_frac_dtype)
for crk in range(self.Number_Of_Fractures):
arr[crk]['Fracture'] = crk+1
arr[crk]['x'] = crk
arr[crk]['y'] = crk
arr[crk]['z'] = crk
return arr
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
fileDialog.configure_traits()
My game engine pushes a value on to the lua stack as a parameter to a function and then invokes it using lua_pcall. The lua code will run and call additional lua functions. Eventually this lua code will invoke a C function. Is it possible for this function to retrieve the value that was originally pushed on to the stack?
Its like this:
<engine function A>
pushes parameter value X on to stack for lua
<lua func>
<lua func>
<lua func>
<engine function B>
can I extract the values X that was pushed by function A here?
Yes, with a combination of getinfo, getlocal and getupvalue you can get all that information (you can even change those values using set* functions).
Here is a fragment from MobDebug that returns stack information along with a table of locals and upvalues at each level. The variables at each level will be indexed in the same order they appear in the code (starting from parameters). For each get* function you can use their C equivalents (lua_getinfo, lua_getlocal, and lua_getupvalue), but the logic should be exactly the same.
local function stack(start)
local function vars(f)
local func = debug.getinfo(f, "f").func
local i = 1
local locals = {}
while true do
local name, value = debug.getlocal(f, i)
if not name then break end
if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, tostring(value)} end
i = i + 1
end
i = 1
local ups = {}
while func and true do -- check for func as it may be nil for tail calls
local name, value = debug.getupvalue(func, i)
if not name then break end
ups[name] = {value, tostring(value)}
i = i + 1
end
return locals, ups
end
local stack = {}
for i = (start or 0), 100 do
local source = debug.getinfo(i, "Snl")
if not source then break end
table.insert(stack, {
{source.name, source.source, source.linedefined,
source.currentline, source.what, source.namewhat, source.short_src},
vars(i+1)})
if source.what == 'main' then break end
end
return stack
end