collision of two boxes:VIZARD:PYTHON - python

I used the collision of boxes that are placed in enviornment having two tables. I used the mouse cursor to grab the objects and placed in the other table. But i am facing one problem in case of collision detection between the objects. I used the proximity sensor for the objects and mouse when they are collided with each other ( minimum distance) then mouse picks/links that object. I am using the same sensor for collision also, some physics idea that are given in the documentation of vizard bt boxes are collided to each other but due to the gravity they are flying. i put the density as it is given in the documentation bt i does not works. Then idecided to move from this logic and try something else i tried to form the two proximity one for boxex collision and one between boxes and mouse but boxes are flying. I used the similar concept with crates that is define by vizard it work there bt not in the blocks. Please give some idea to resolve this problem. Here i am attaching thre function - one for hand , other for linking mouse and block and in last placing of blocks. In enviornment i already used the collide palne and collission for table also. So for collision what methodss i should go for because when i am working on same proximity sensors it will not works. All objects are placed in origin in vizard and then manually set the positions for plaing on table.`
global hand
hand = viz.addChild( 'marker.wrl' )
#hand.collidebox()
#xa,ya,za=hand.getPosition()
#hand.collideBox()
hand.enable(viz.COLLIDE_NOTIFY)
#hand.density=0.0000001
#viz.phys.setGravity([0,-1,0])
#vizact.onkeydown(' ', viz.phys.enable)
hand.setPosition( [-7.5, 1.2, -10] )
hand.setEuler(0,0,0)
hand.setScale(0.3,0.3,0.3)
ViewLink = viz.link(hand,viz.MainView)
viz.link(hand,device)
ViewLink.preEuler( [0,25 ,0] )
ViewLink.preTrans( [0,0.2,-0.5] )
def p_ball(e):
# print 'hit'
# global sound1
# sound1.play()
global bn
# grab = 1
# ball.addAction(blast
# b[z].addAction(blast)
for i in range(len(b)):
#global xh,zh
xh,yh,zh=hand.getPosition()
# zh= (zh)
# print 'abcd'
xb,yb,zb=b[i].getPosition()
zb= (abs(zb))
zh= (abs(zh))
xb= (abs(xb))
xh= (abs(xh))
#print zh,zb
if (abs(zh-zb)<.4 and abs(xh-xb)<.4):
# b[i].addAction(blast)
# b[i].visible(viz.OFF)
# b[i].visible(viz.ON)
global link
if bn==100:
link = None
link = viz.grab( hand, b[i] )
#tool.grabAndHold()
if link == True:
global Block1
Pos=Block1.getPosition(MODE=VIZ.REL_GLOBAL)
# else:
# print 'aaaaaa'
bn=i
#UpdateMovement()
#UpdateMovement()
global k
k=k+1
tbox2.message(str(k))
/i tried something here but it wont work. here i am using the proximity sensor for the collision of boxes.
xb11,yb11,zb11=b[0].getPosition() ####### proximity POSITION 1
print xb11,yb11,zb11
xb1= (abs(xb11))
zb1= (abs(zb11))
print xb1,zb1
xb22,yb22,zb22=b[1].getPosition() ` ` ####### proximity POSITION 2
print xb22,yb22,zb22
xb2= (abs(xb22))
zb2= (abs(zb22))
print xb2,zb2
xb33,yb33,zb33=b[2].getPosition() ` ` ####### proximity POSITION 3
print xb33,yb33,zb33
xb3= (abs(xb33))
zb3= (abs(zb33))
print xb3,zb3
#
# if ((zb1-zb2)<1.5 or (zb1-zb3)<1.5 or (xb1-xb2)<1.5
or (xb1-xb3)<1.5):
#
# print 'Ashish'
# global tbox22
# tbox22=viz.addTextbox()
# tbox22.setPosition(0.11,0.1,0.1)
# global touch11
# touch11='OBSTACLE-ERROR'
# tbox22.message(str(touch11))
#
# Block1.setPosition([-7.5,1.1,-2.9]) ` ####### POSITION OF THE BALLOON`
# Block2.setPosition([-7.5,1.1,-1.9]) ` ####### POSITION OF THE BALLOON`
#
# #Block0.setPosition(xb11-1,yb11,zb11-1) ` ####### POSITION OF THE BALLOON`
#
#
# elif ((zb2-zb1)<.5 or (zb2-zb3)<.5 or (xb2-xb1)<.5
or (xb2-xb3)<.5):
#
# print 'Ashish'
# global tbox22
# tbox22=viz.addTextbox()
#
# tbox22.setPosition(0.11,0.1,0.1)
# global touch11
# touch11='OBSTACLE-ERROR'
# tbox22.message(str(touch11))
#
# Block0.setPosition([-7.5,1.11,-3.7]) ` ####### POSITION OF THE BALLOON`
# Block2.setPosition([-7.5,1.1,-1.9]) ` ####### POSITION OF THE BALLOON`
#
# #Block1.setPosition(xb22-1,yb22,zb22-1) ` ####### POSITION OF THE BALLOON`
#
#
# elif ((zb3-zb1)<.5 or (zb3-zb2)<.5 or (xb3-xb1)<.5
or (xb3-xb2)<.5):`
#
# print 'Ashish'
# global tbox22
# tbox22=viz.addTextbox()
#
# tbox22.setPosition(0.11,0.03,0.1)
# global touch11
# touch11='OBSTACLE-ERROR'
# tbox22.message(str(touch11))
#
`# Block0.setPosition([-7.5,1.11,-3.7])` `
`# Block1.setPosition([-7.5,1.1,-2.9])` `
# #Block2.setPosition(xb33-1,yb33,zb33-1)
#abc()
fb()
/code for blocks i put the collision with the blocks same i put with plane /and tables while with ground plane then gravity pulls the object /downwards so i collision i used with the tables to`put the blocks on the /table
def put_balloons(manager_b,b,b_y,b2):
# import vizshape
# aa=vizshape.addCube()
# aa.setPosition(-7.5,1.1,2.4)
# kk=aa.collideBox()
# kk.density=100000
/BLOCK 1---------- TABLE 1
global Block0
Block0=viz.addChild('b2.osgb')
#crate = viz.addChild('crate.osgb',pos=[-7.38,1.2,-3.9])
#crate.visible(viz.OFF)
#crate.collideBox(density=50000000000)
#crate.alpha(0.3)
Block0.setPosition(-7.5,1.1,-3.7)
Block0.setEuler(90,0,0)
Block0.setScale(.3,.3,.3)
bs=vizproximity.addBoundingBoxSensor(Block0)
manager_b.addSensor(bs)
b.append(Block0)
#Block0.collideBox()
Block0.disable(viz.DYNAMICS)
# global link
# ss=viz.link(crate,Block0)
# ss.preTrans( [-0.17,-0.1,-.1 ])
# Block0.enable(viz.RENDERING)
/BLOCK 2---------- TABLE 1
global Block1
Block1=viz.addChild('b7.osgb')
#crate = viz.addChild('crate.osgb',pos=[-7.38,1.2,-3])
#crate.visible(viz.OFF)
#crate.collideBox(density=50000000000)
#crate.alpha(0.3)
Block1.setPosition(-7.5,1.1,-2.9)
Block1.setEuler(90,0,0)
Block1.setScale(.3,.3,.3)
bs=vizproximity.addBoundingBoxSensor(Block1)
manager_b.addSensor(bs)
b.append(Block1)
#Block1.collideBox()
Block1.disable(viz.DYNAMICS)
#Block1.enable(viz.RENDERING)
/BLOCK 3--------- TABLE
global Block2
Block2=viz.addChild('b9.osgb')
#crate = viz.addChild('crate.osgb',pos=[-7.38,1.2,-2.1])
#crate.visible(viz.OFF)
#crate.collideBox(density=50000000000)
#crate.alpha(0.3)
Block2.setPosition(-7.5,1.1,-1.9)
Block2.setEuler(90,0,0)
Block2.setScale(.3,.3,.3)
bs=vizproximity.addBoundingBoxSensor(Block2)
manager_b.addSensor(bs)
b.append(Block2)
Block2.collideBox()
#Block2.density=0.0000001
Block2.disable(viz.DYNAMICS)
#Block2.enable(viz.RENDERING)
/BLOCK 1----------TABLE2
global Block00
Block00=viz.addChild('b2.osgb')
Block00.setPosition(-7.5,1.15,4)
Block00.setEuler(90,0,0)
Block00.setScale(.3,.01,.3) #.025,.0004,.02,
b2.append(Block00)
/BLOCK 2----------TABLE2
global Block11
Block11=viz.addChild('b7.osgb')
Block11.setPosition(-7.5,1.15,5)
Block11.setEuler(90,0,0)
Block11.setScale(.3,.01,.3)
b2.append(Block11)
/BLOCK 3----------TABLE3
global Block22
Block22=viz.addChild('b9.osgb')
Block22.setPosition(-7.5,1.1,6)
Block22.setEuler(90,0,0)
Block22.setScale(.3,.01,.3)
b2.append(Block22)
#
#viz.phys.setGravity(0,-9) #Sets the Y plane gravity to -2
put_balloons(manager_b,b,b_y,b2)

Related

How to call a function once in a while loop

I have a robotic code, that does the following:
camera starts processing and taking images
Mounting Holes (hough transform) function detection is activated
The holes are drawn on the image
approachcirlce function moves robot towards one of the set coordinates
I have two issues :
The mounting holes keep getting called even after detecting the coordinates once.
The robot in the approachcircle function cant move to one coordinates then onto the other. It keeps going back and forth as the x and y aren't specifically set to finish the first set of coordinates first. i.e : between two circles it does not reach either centers as expected. it never reaches the center of a detected circle if its more than one
I want the code to call the mountingholes function once and have the robot to move to each recorded coordinates, after the intial set of coordinates is done. I will have the robot move to another area and start doing the process again. I'm assuming the problem is that the functions are in the camera processing loop which is run indefinitely
The code is below:
##Def:
def approachcircle (r,t,z):
move = robot.Pose()*transl(r,t,z)
robot.MoveL(move)
def approacharea (z):
move = robot.Pose()*transl(0,0,z)
robot.MoveL(move)
def MountingHoles(img,thresh,r):
minR = r
CannyHighT = 50
min_points = 15 #param2
img_1= cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#img3 = cv2.inRange(img_1, thresh, 255)
circles = cv.HoughCircles(img_1,cv.HOUGH_GRADIENT, 1, 2*minR, param1=CannyHighT,
param2=min_points, minRadius=minR, maxRadius=220)
return circles
#Installation
from robolink import * # RoboDK API
from robodk import * # Robot toolbox
RDK = Robolink()
pose = eye()
ITEM_TYPE_ROBOT
RDK = robolink.Robolink()
robot = RDK.Item('TM12X')
import_install('cv2', 'opencv-python')
import cv2 as cv
import numpy as np
import numpy
#----------------------------------
# Settings
PROCESS_COUNT = -1 # How many frames to process before exiting. -1 means indefinitely.
CAM_NAME = "Camera"
DISPLAY_SETTINGS = True
WDW_NAME_PARAMS = 'RoboDK - Blob detection parameters'
DISPLAY_RESULT = True
WDW_NAME_RESULTS = 'RoboDK - Blob detections1'
# Calculate absolute XYZ position clicked from the camera in absolute coordinates:
cam_item = RDK.Item(CAM_NAME, ITEM_TYPE_CAMERA)
if not cam_item.Valid():
raise Exception("Camera not found! %s" % CAM_NAME)
cam_item.setParam('Open', 1) # Force the camera view to open
#----------------------------------------------
# Create an resizable result window
if DISPLAY_RESULT:
cv.namedWindow(WDW_NAME_RESULTS) #, cv.WINDOW_NORMAL)
#----------------------------------------------
# capture = cv.VideoCapture(0)
# retval, image = capture.read()
#----------------------------------------------
# Process camera frames
count = 0
while count < PROCESS_COUNT or PROCESS_COUNT < 0:
print("=============================================")
print("Processing image %i" % count)
count += 1
#----------------------------------------------
# Get the image from RoboDK
bytes_img = RDK.Cam2D_Snapshot("", cam_item)
if bytes_img == b'':
raise
# Image from RoboDK are BGR, uchar, (h,w,3)
nparr = np.frombuffer(bytes_img, np.uint8)
img = cv.imdecode(nparr, cv.IMREAD_UNCHANGED)
if img is None or img.shape == ():
raise
#----------------------------------------------
# Detect blobs
keypoints = MountingHoles(img,250,50)
i = 0
#----------------------------------------------
# Display the detection to the user (reference image and camera image side by side, with detection results)
if DISPLAY_RESULT:
# Draw detected blobs and their id
i = 0
for keypoint in keypoints[0,:]:
cv.putText(img, str(i), (int(keypoint[0]), int(keypoint[1])), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 1, cv.LINE_AA)
cv.circle(img, (int(keypoint[0]), int(keypoint[1])), int(keypoint[2]), (0, 0, 255), 15)
#
i += 1
# Resize the image, so that it fits your screen
img = cv.resize(img, (int(img.shape[1] * .75), int(img.shape[0] * .75)))#
cv.imshow(WDW_NAME_RESULTS, img)
key = cv.waitKey(500)
if key == 27:
break # User pressed ESC, exit
if cv.getWindowProperty(WDW_NAME_RESULTS, cv.WND_PROP_VISIBLE) < 1:
break # User killed the window, exit
#--------------------------------------------------------------------------------------------
# Movement functions
r=0
t=0
i=0
#approacharea(200)
for keypoint in keypoints[0,:]:
#print("id:%i coord=(%0.0f, %0.0f)" % (i, X, Y))
X= int(keypoint[0])-320
Y=int(keypoint[1])-240
r=int(keypoint[2])
print("id:%i coord=(%0.0f, %0.0f)" % (i, X, Y))
if X!= 0 or Y!=0 :
r=X*0.1
t=Y*0.1
approachcircle(r,t,0)
i+=1

Python3 Print on Same Line - Numbers in 7-Segment-Device Format

I'm new to Python and having difficulty getting the output to print on one line.
This is pertaining to the online Python class Learning Python Essentials Lab 5.1.10.6 and printing to a 7-segment-device. If you are unfamiliar with a 7-segment-device, see Wikipedia.
I am NOT using any external device. I only need it to print to my own terminal. All the other StackOverflow solutions I found are related to using actual devices and didn't help.
Lab Link:
https://edube.org/learn/programming-essentials-in-python-part-2/lab-a-led-display
Purpose: Prompt user for number; print number in 7-segment display
format to your terminal.
Notes: Using Python3.9. I tried 3 alternate solutions (Option 1,2,3), but none do what I want it to.
INSTRUCTIONS: Un/Comment Option 1,2,or 3 to run just that option
I did find this alternate solution, which I mostly understand. However, it's a totally different approach and not one I would have come up with. I know there are many ways to skin a 7-segment-device, and if this is the most correct, then I'll learn it. But I feel like I'm so close and only a superfluous '\n' away from figuring it out with my own method and trying to understand what I'm missing.
Thank you for your help.
Desired Output
### ## ### ### # # ### ### ### ### ###
# # ### # # # # # # # # # # #
# # ## ### ### ### ### ### # ### ###
# # ## # # # # # # # # # #
### ## ### ### # ### ### # ### ###
My Code
# clear screen each time you run the script
import os
clear = lambda: os.system('cls')
clear()
#
# Dictionary of (number:7-segment-hash)
dict1 = {
'0':('###','# #','# #','# #','###'),
'1':('#####'),
'2':('###',' #','###','# ','###'),
'3':('###',' #','###',' #','###'),
'4':('# #','# #','###',' #',' #'),
'5':('###','# ','###',' #','###'),
'6':('###','# ','###','# #','###'),
'7':('###',' #',' #',' #',' #'),
'8':('###','# #','###','# #','###'),
'9':('###','# #','###',' #','###')
}
# Function to print numbers in 7-segment-device format
def fun_PrintNums(num):
if num < 0 or num % 1 > 0 or type(num)!=int: # if num is NOT a positive whole integer
return "Invalid entry, please try again"
else:
display = [' ']
for i in str(num): # convert 'num' to STRING; for each "number" in string 'num'
#'''Option 1: works, but prints nums vertically instead of side-by-side; Return=None ''' #
for char in dict1[i]:
print(*char)
print(fun_PrintNums(int(input("Enter any string of whole numbers: "))))
#----------------------------------------------------------------#
#''' Option 2: Return works, but still vertical and not spaced out ''' #
# for char in dict1[i]:
# display.append(char)
# return display
# print('\n'.join(fun_PrintNums(int(input("Enter any string of whole numbers: ")))))
#---------------------------------------------------------------------#
#''' Option 3: 'display' row1 offset; spaced out as desired, but vertical; Return=None''' #
# for char in dict1[i]:
# display += char
# display += '\n'
# a = print(*display,end='')
# return a
# print(fun_PrintNums(int(input("Enter any string of whole numbers: "))))
#---------------------------------------------------------------#
Option 1 Output
Works, but prints nums vertically instead of side-by-side; Return=None
# # #
#
# # #
#
# # #
# # #
#
# # #
#
# # #
None
Option 2 Output
Return works, but still vertical and not spaced out.
###
#
###
#
###
###
#
###
#
###
Option 3 Output
'display' row1 offset; spaced out as desired, but vertical; Return=None
# # #
#
# # #
#
# # #
# # #
#
# # #
#
# # #
None
Your problem is that you are printing each number before the next, but you need to print each row before the next. As a simplified example:
dict1 = {
'0':('###','# #','# #','# #','###'),
'1':(' ##','###',' ##',' ##',' ##'),
'2':('###',' #','###','# ','###'),
'3':('###',' #','###',' #','###'),
'4':('# #','# #','###',' #',' #'),
'5':('###','# ','###',' #','###'),
'6':('###','# ','###','# #','###'),
'7':('###',' #',' #',' #',' #'),
'8':('###','# #','###','# #','###'),
'9':('###','# #','###',' #','###')
}
num = '0123456789'
for row in range(len(dict1['0'])):
print(' '.join(dict1[i][row] for i in num))
Output:
### ## ### ### # # ### ### ### ### ###
# # ### # # # # # # # # # # #
# # ## ### ### ### ### ### # ### ###
# # ## # # # # # # # # # #
### ## ### ### # ### ### # ### ###
If you don't want to use a list comprehension inside join, you can unroll that like this:
for row in range(len(dict1['0'])):
line = []
for i in num:
line.append(dict1[i][row])
print(' '.join(line))

PsychoPy playing sounds with irregular delay in an EEG experiment

I'm using PsychoPy to prepare an oddball paradigm in which I preset a picture on the screen for 7 seconds and during the picture presentation 14 consecutive sounds are displayed every half a second. For every sound onset I send a trigger to the parallel port. I then ran timing tests to see whether the sounds are played at the same time as the triggers.
While the triggers seem to be fine and arrive every half a second, this is not the case for the sounds. The sounds are played with a delay of 100ms-200ms after the trigger and the difference between consecutive sounds' onsets is not half a second. The size of the sound file doesn't make a difference and the delays seem to be the case both for very short sounds (10ms) and longer ones (250ms). I tried to add ISI at the very beginning of each trial and load both a picture and the sounds during that period but it didn't help.
I also tried to add the ISI before every sound and load the sounds during these shorts ISIs but it didn't help either. Do you have any idea how the problem could be solved? Is there any way ISI could help? Am I supposed to have one ISI at the beginning of the trial to load all the stimuli for that trial or multiple ISIs per trial, one per stimulus?
The delay for the visual stimulus (i.e. the picture) is small and constant across trials.
The code below plays only two sounds but demonstrates the issue well.
from __future__ import absolute_import, division
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, parallel
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
# Setup the Window
win = visual.Window(
size=(1920, 1080), fullscr=True, screen=0,
allowGUI=True, allowStencil=False,
monitor='testMonitor', color=[-1, -1, -1], colorSpace='rgb',
blendMode='avg', useFBO=True)
snd_2_tr = 'sound1.wav'
snd_3_tr = 'sound2.wav'
picture_tr = 'pic.jpg'
win.setRecordFrameIntervals(True)
win._refreshThreshold = 1 / 60.0 + 0.004
image_tr = visual.ImageStim(
win=win, name='image_tr',
image='sin', mask=None,
ori=0, pos=(0, 0), size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
sound_2_tr = sound.Sound('A', secs=-1)
sound_2_tr.setVolume(1)
sound_3_tr = sound.Sound('A', secs=-1)
sound_3_tr.setVolume(1)
image_port_tr = parallel.ParallelPort(address='0xD010')
sound_2_port_tr = parallel.ParallelPort(address='0xD010')
sound_3_port_tr = parallel.ParallelPort(address='0xD010')
ISI_17 = core.StaticPeriod(win=win, screenHz=60, name='ISI_17')
# ------Prepare to start Routine "main_tr"-------
main_trClock = core.Clock()
t = 0
main_trClock.reset() # clock
frameN = -1
continueRoutine = True
# keep track of which components have finished
main_trComponents = [image_tr, sound_2_tr, sound_3_tr, image_port_tr, sound_2_port_tr, sound_3_port_tr, ISI_17]
for thisComponent in main_trComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "main_tr"-------
while continueRoutine:
# get current time
t = main_trClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image_tr* updates
if frameN >= 60 and image_tr.status == NOT_STARTED:
# keep track of start time/frame for later
image_tr.tStart = t
image_tr.frameNStart = frameN # exact frame index
image_tr.setAutoDraw(True)
if image_tr.status == STARTED and frameN >= (image_tr.frameNStart + 420):
image_tr.setAutoDraw(False)
# start/stop sound_2_tr
if frameN >= 90 and sound_2_tr.status == NOT_STARTED:
# keep track of start time/frame for later
sound_2_tr.tStart = t
sound_2_tr.frameNStart = frameN # exact frame index
sound_2_tr.play() # start the sound (it finishes automatically)
if sound_2_tr.status == STARTED and t >= (sound_2_tr.tStart + 0.25):
sound_2_tr.stop() # stop the sound (if longer than duration)
# start/stop sound_3_tr
if frameN >= 120 and sound_3_tr.status == NOT_STARTED:
# keep track of start time/frame for later
sound_3_tr.tStart = t
sound_3_tr.frameNStart = frameN # exact frame index
sound_3_tr.play() # start the sound (it finishes automatically)
if sound_3_tr.status == STARTED and t >= (sound_3_tr.tStart + 0.25):
sound_3_tr.stop() # stop the sound (if longer than duration)
# *sound_1_port_tr* updates
if frameN >= 60 and image_port_tr.status == NOT_STARTED:
# keep track of start time/frame for later
image_port_tr.tStart = t
image_port_tr.frameNStart = frameN # exact frame index
image_port_tr.status = STARTED
win.callOnFlip(image_port_tr.setData, int(triggers_image_tr))
if image_port_tr.status == STARTED and frameN >= (image_port_tr.frameNStart + 15):
image_port_tr.status = STOPPED
win.callOnFlip(image_port_tr.setData, int(0))
# *sound_2_port_tr* updates
if frameN >= 90 and sound_2_port_tr.status == NOT_STARTED:
# keep track of start time/frame for later
sound_2_port_tr.tStart = t
sound_2_port_tr.frameNStart = frameN # exact frame index
sound_2_port_tr.status = STARTED
win.callOnFlip(sound_2_port_tr.setData, int(triggers_sound_2_tr))
if sound_2_port_tr.status == STARTED and frameN >= (sound_2_port_tr.frameNStart + 15):
sound_2_port_tr.status = STOPPED
win.callOnFlip(sound_2_port_tr.setData, int(0))
# *sound_3_port_tr* updates
if frameN >= 120 and sound_3_port_tr.status == NOT_STARTED:
# keep track of start time/frame for later
sound_3_port_tr.tStart = t
sound_3_port_tr.frameNStart = frameN # exact frame index
sound_3_port_tr.status = STARTED
win.callOnFlip(sound_3_port_tr.setData, int(triggers_sound_3_tr))
if sound_3_port_tr.status == STARTED and frameN >= (sound_3_port_tr.frameNStart + 15):
sound_3_port_tr.status = STOPPED
win.callOnFlip(sound_3_port_tr.setData, int(0))
# *ISI_17* period
if frameN >= 0 and ISI_17.status == NOT_STARTED:
# keep track of start time/frame for later
ISI_17.tStart = t
ISI_17.frameNStart = frameN # exact frame index
ISI_17.start(60 * frameDur)
elif ISI_17.status == STARTED: # one frame should pass before updating params and completing
# updating other components during *ISI_17*
image_tr.setImage(picture_tr)
sound_2_tr.setSound(snd_2_tr, secs=0.25)
sound_3_tr.setSound(snd_3_tr, secs=0.25)
# component updates done
ISI_17.complete() # finish the static period
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in main_trComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()

Maze Pattern Building in Python

Hello I am a newbie to python and using python 3.
I wish to learn patterns and printing e.g stars etc. I want to make maze pattern but i confused to make maze no 2-no4
No 1
# #############
# #
############# #
# #
# #############
# #
############# #
# #
# #############
# #
############# #
# #
# #############
# #
############# #
No 2
# #############
# # # # #
# # # # # # ###
# # # # # # #
# # # # # ### #
# # # # # #
# # # # #######
# # # # #
# # # ####### #
# # # #
# # ###########
# # #
# ########### #
# #
###############
No 3
# #############
# # #
# # ######### #
# # # # #
# # # ##### # #
# # # # # # #
# # # # # # # #
# # # # # # # #
# # # ### # # #
# # # # # #
# # ####### # #
# # # #
# ########### #
# #
###############
No 4
# #############
# # #
# # ######### #
# # # # #
# # # ##### # #
# # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # #
# # ##### # # #
# # # # #
# ######### # #
# # #
############# #
This is my code maze no1:
def SimpleMaze(S):
bool=1
for i in range(S):
if (i+1)%2==0:
print('#'+' '*(S-2)+'#')
else:
if bool==1:
print('#'+' '+'#'*(S-2))
else:
print('#'*(S-2)+' '+'#')
bool=not bool
S= input("Nilai S:")
SimpleMaze(int(S))
You built Maze 1 by assembling it row by row, but the other mazes appear to have messier patterns when you think about them in terms of rows.
Here's another way to break down the problem. Start with a solid block, with rows 0..R and columns 0..C (inclusive).
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
Then envision yourself creating a maze by driving a bulldozer through it, opening up the path as you go. Under this approach, we can represent a maze as a set of driving instructions. For example, Maze 1 looks like this:
Start at r==-1, c==1.
Go South 2 steps.
Go East until c==C-1.
Go South 2 steps.
Go West until c==1.
Repeat ... until r>R.
I think Mazes 2 through 4 will be easier to think about in those terms. Ideally, each of those concepts (go south, go east, etc) could be implemented as simple functions or methods.

Plotting a graph on a white box in Processing

I am fairly new to Processing but I have managed to make a good amount of a GUI in the Python Mode. I wanted to graph some data on a white box. I don't want to use background(0) because that'll make the entire window white. Using a rectangular in the draw() function also did not help as the rectangular kept on refreshing the graph. I am trying to simulate the hold on function as in MATLAB
Here's my pseudo code:
class plotEverything:
def __init__
def plotAxis
def plotGraph
def clearGraph
def setup():
size (800,600)
p1 = plotEverything()
background(0)
def draw():
rect (100,100,200,200)
fill(255)
p1.drawAxis()
p1.plotGraph()
Is there any way I can make that rectangle fixed in the background?
EDIT Added graph class | Ignore indents(Assume they are all properly indented) --
class graphData:
def __init__(self, originX, originY, xUpper, yUpper):
self.originX = originX
self.originY = originY
self.xUpper = xUpper
self.yUpper = yUpper
self.pointX1 = originX
self.pointX2 = xUpper
self.pointY1 = originY
self.pointY2 = yUpper
self.scaleFactorX = 10.0/(xUpper - originX) #Assuming data is between is 0 and 10
self.scaleFactorY = 10.0/(originY - yUpper) #Assuming data is between is 0 and 1
def drawAxis(self):
stroke(255)
strokeWeight(1.5)
line(self.originX, self.originY, self.originX, self.yUpper) #y axis
line(self.originX, self.originY, self.xUpper, self.originY) #x axis
def plotStaticData(self,data2Plot): #X-axis static
ab = zip(data2Plot,data2Plot[1:],data2Plot[2:],data2Plot[3:])[::2]
if ab:
(X1,Y1,X2,Y2) = ab[-1]
print (X1,Y1,X2,Y2)
self.pointX1 = self.originX + ceil((float(X1) - 0.0)/self.scaleFactorX)
self.pointX2 = self.originX + ceil((float(X2) - 0.0)/self.scaleFactorX)
self.pointY1 = self.originY - ceil((float(Y1) - 0.0)/self.scaleFactorY)
self.pointY2 = self.originY - ceil((float(Y2) - 0.0)/self.scaleFactorY)
stroke(255)
strokeWeight(2.0)
line(self.pointX1,self.pointY1,self.pointX2,self.pointY2)
def clearPlot(self):
background(0)
self.drawAxis()

Categories