Changing partial effect lenght with keyframe - python

FULL CODE
import bpy
bpy.ops.mesh.primitive_plane_add(size=2, location=(0, 0, 0))
bpy.ops.transform.resize(value=(10, 10, 10))
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.mesh.primitive_uv_sphere_add(segments=16, ring_count=8, radius=1,
location=(0, 0, 5))
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.context.object.modifiers["Subdivision"].levels = 1
bpy.context.object.modifiers["Subdivision"].render_levels = 3
bpy.ops.object.shade_smooth()
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.object.modifier_add(type='SOFT_BODY')
bpy.context.object.modifiers["Softbody"].settings.use_goal = False
bpy.context.object.modifiers["Softbody"].settings.bend = 5
# Particle physics for hair
mod = bpy.context.object.modifiers.new("ParticleSystem", type =
'PARTICLE_SYSTEM')
hair_stngs = mod.particle_system.settings
hair_stngs.type = 'HAIR'
hair_stngs.hair_length = 0
hair_stngs.use_advanced_hair = True
hair_stngs.count = 5000
hair_stngs.hair_step = 12
mod.particle_system.use_hair_dynamics = False
bpy.data.particles["ParticleSettings"].use_regrow_hair = True
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 30)
bpy.data.particles["ParticleSettings"].hair_length = 2
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 60)
bpy.data.particles["ParticleSettings"].hair_length = 4
When I want to change the data path = hair_length, it does not accept the data path. How can i access the hair lenght?
bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0
I tried right click and copy data path in partical settings hair lenght but data path didnt recognize by the blender

Related

how can I run this code with two loops faster? Can I run it without using for?

I wanna run this code for a wide range instead of this range. So I wanna make it better to run faster.
Is it impossible to use something else instead of these loops?
z1=3
z2=HEIGHT-1
def myfunction(z1,z2):
for l in range(z1):
vector = np.zeros(WIDTH)
vector[WIDTH//2] = 1
result = []
result.append(vector)
for i in range(z2):
vector = doPercolationStep(vector, PROP, i)
result.append(vector)
result = np.array(result)
ss = result.astype(int)
ss = np.where(ss==0, -1, ss)
ww = (ss+(ss.T))/2
re_size = ww/(np.sqrt(L))
matr5 = re_size
np.savetxt('F:/folder/matr5/'+str(l)+'.csv', matr5)
and doPercolationStep is:
WIDTH = 5
HEIGHT = 5
L=5
PROP = 0.6447
def doPercolationStep(vector, PROP, time):
even = time%2 # even is 1 or 0
vector_copy = np.copy(vector)
WIDTH = len(vector)
for i in range(even, WIDTH, 2):
if vector[i] == 1:
pro1 = random.random()
pro2 = random.random()
if pro1 < PROP:
vector_copy[(i+WIDTH-1)%WIDTH] = 1 # left neighbour of i
if pro2 < PROP:
vector_copy[(i+1)%WIDTH] = 1 # right neighbour of i
vector_copy[i] = 0
return vector_copy

Infinity loop issue using for loops

import pandas as pd
import time
import yfinance as yf
import money_18
import talib
def backtest(df,us_code, profit_target, stop_loss, macd_diff):
pos_opened = False
open_price = 0
close_price = 0
pnl = 0
pnl_list = []
original_capital = 100000
temp_capital = original_capital
num_of_lot = 0
equity_value = 0
equity_value_list = []
dd_dollar = 0
dd_dollar_list = []
dd_pct = 0
dd_pct_list = []
mdd_dollar = 0
mdd_pct = 0
total_profit = 0
num_of_trade = 0
for i in range(1, len(df)):
now_date = df.loc[i,'Date']
now_open = df.loc[i,'Open']
now_high = df.loc[i,'High']
now_low = df.loc[i,'Low']
now_close = df.loc[i,'Close']
now_rsi = df.loc[i,'RSI']
now_upper_band = df.loc[i,'Upper_Band']
now_middle_band = df.loc[i,'Middle_Band']
now_lower_band = df.loc[i,'Lower_Band']
now_macd = df.loc[i,'MACD']
now_macd_signal = df.loc[i,'MACD_Signal']
now_macd_hist = df.loc[i,'MACD_Hist']
##### equity curve #####
equity_value = round(temp_capital + (now_open - open_price) * num_of_lot )
equity_value_list.append(equity_value)
temp_max_equity = max(equity_value_list)
dd_dollar = temp_max_equity - equity_value
dd_dollar_list.append(dd_dollar)
mdd_dollar = max(dd_dollar_list)
dd_pct = (temp_max_equity - equity_value) / temp_max_equity
dd_pct_list.append(dd_pct)
mdd_pct = max(dd_pct_list)
##### open position #####
if (pos_opened == False) and (i < len(df) - 1) and now_macd_hist > macd_diff :
pos_opened = True
open_price = now_close
num_of_lot = temp_capital // (open_price)
##### profit taking and stop loss #####
if (pos_opened == True) and ((now_open - open_price > profit_target * open_price) or (now_open - open_price < stop_loss * open_price) or (i == len(df) -1)):
pos_opened = False
close_price = now_open
pnl = (close_price - open_price) * num_of_lot
pnl_list.append(pnl)
open_price = 0
num_of_lot = 0
temp_capital = temp_capital + pnl
if len(pnl_list) > 0:
total_profit = sum(pnl_list)
num_of_trade = len(pnl_list)
return us_code, profit_target, stop_loss, total_profit, num_of_trade, mdd_dollar, mdd_pct, macd_diff
if __name__ == '__main__':
us_code_list = ['TSLA', 'AAPL']
macd_diff_list = [0, 0.05]
profit_target_list = [0.03, 0.06]
stop_loss_list = [-0.01, -0.02, -0.03]
start_date = '2020-01-01'
end_date = '2020-12-31'
df_dict = {}
for us_code in us_code_list:
df= yf.Ticker(us_code).history(start=start_date, end=end_date)
df= df[df['Volume'] > 0]
df = df[['Open', 'High', 'Low', 'Close']]
df['RSI'] = talib.RSI(df['Close'], timeperiod=14)
df['Upper_Band'], df['Middle_Band'], df['Lower_Band'] = talib.BBANDS(df['Close'], 20, 2, 2)
df['MACD'], df['MACD_Signal'], df['MACD_Hist'] = talib.MACD(df['Close'], fastperiod=12, slowperiod=26,
signalperiod=9)
df = df[df['MACD_Hist'].notna()]
df = df.reset_index()
df_dict[us_code] = df
save_us_code = ''
save_macd_diff = 0
save_profit_target = 0
save_stop_loss = 0
total_profit = 0
num_of_trade = 0
mdd_dollar = 0
mdd_pct = 0
save_us_code_list = []
save_macd_diff_list = []
save_profit_target_list = []
save_stop_loss_list = []
total_profit_list = []
num_of_trade_list = []
mdd_dollar_list = []
mdd_pct_list = []
result_dict = {}
for us_code in us_code_list:
for macd_diff in macd_diff_list:
for profit_target in profit_target_list:
for stop_loss in stop_loss_list:
print(us_code, macd_diff, profit_target, stop_loss) ## the problem should be starting from here##
save_us_code, save_profit_target, save_stop_loss, total_profit, num_of_trade, mdd_dollar, mdd_pct, macd_diff = backtest(df, us_code, profit_target, stop_loss, macd_diff)
save_us_code_list.append(save_us_code)
save_profit_target_list.append(save_profit_target)
save_stop_loss_list.append(save_stop_loss)
total_profit_list.append(total_profit)
num_of_trade_list.append(num_of_trade)
mdd_dollar_list.append(mdd_dollar)
mdd_pct_list.append(mdd_pct)
macd_diff_list.append(macd_diff)
I am working on the algo trade, however, I created a for loop to put my parameter into my backtest function. However, the for loop keeps looping non-stop.
I think the error starting from "for macd_diff in macd_diff_list:" because i try to print the result below that row, the result is already indefinite.
Now that you've shown the full code, your problem is obvious. Your original example didn't show the issue because you didn't include all relevant code. Here's your example with the relevant code that's causing the issue:
for us_code in us_code_list:
for macd_diff in macd_diff_list:
for profit_target in profit_target_list:
for stop_loss in stop_loss_list:
... # irrelevant code not shown
macd_diff_list.append(macd_diff)
The issue is that you're looping through each item in macd_diff_list, but then for each loop iteration, you add an item to that list. So of course the loop will be infinite. You need to be looping through a different list, or adding items to a different list.

Radio button indicators not showing up

I am new to GUI development and have recently started developing a simple app on Ubuntu by designing the UI with glade and writing the code in python using PyGObject. I have done decently so far until I ran into a mysterious issue.
The indicators of radio buttons on a child window are not showing up. I have been able to toggle them and retrieve which button is active but the indicators themselves do not show up. I have compared the Properties of these buttons with two other radio buttons that I have put up on the main window (look and work as expected) but do not see any difference.
Could someone suggest a way to fix this? I am not sure what all information is required but here are a few images for starters.
Screenshot from glade
General Properties
Common Properties
Screenshot from the executable
Edit: Code which brings up the generate logs window
def on_generate_logs_activate(self, widget):
#Setup generate logs window
self.builder.add_from_file("myprogram6.glade")
self.generate_logs_window = self.builder.get_object("generate_logs_window")
self.generate_logs_window.show_all()
self.all_records = self.builder.get_object("all_records") #Radio1
self.specific_record = self.builder.get_object("specific_record") #Radio2
self.dialog_record_combo = self.builder.get_object("dialog_record_combo")
self.generate = self.builder.get_object("generate")
self.dialog_close = self.builder.get_object("dialog_close")
self.record_set1 = self.builder.get_object("liststore1")
self.dialog_record_combo.set_sensitive(False)
#Setup combotext
self.dialog_record_combo.set_entry_text_column(1)
records = self.get_unprocessed_records()
for record in records:
record=record.split('.')
self.record_set1.append([record[0]])
#Radios
self.all_records.connect("toggled", self.on_all_records_toggled)
self.specific_record.connect("toggled", self.on_specific_record_toggled)
#Generate button
self.generate.connect("clicked", self.on_generate_clicked)
#Close button
self.dialog_close.connect("clicked", self.on_dialog_close_clicked)
Please let me know if you would like me to add more information.
I'm guessing you didn't call window.show_all(). Again, I'm guessing because you didn't post your code, so it's impossible to know.
Look at https://www.youtube.com/watch?v=RxqZ_2fz-ZI
My speculation: you did not structure correctly your application.
Look at video 4 and 5 and you will understand how to structure.
a) python file creation with import at the top. so call it application.py and include
import gi
#
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk as gtk, Gdk as gdk, GLib, GObject as gobject
gobject.threads_init()
import string # not used for now
import os # not used for now
from datetime import datetime, timedelta
import time
import threading..
b) class GUI (called "foo" in the video) hereunder called GUIclass
c) several def linked to the glade file within that class
d) init with import of the glade file
e) main
see few extracts below. look at few applications done with glade / pygtk on github.
class GUIclass:
#
def exit_action(self, widget, data=None):
self.exitdialog.show()
def exit_confirmed(self, widget, data=None):
self.exitdialog.hide()
game_not_cancelled = False
...
gtk.main_quit()
return True
def exit_aborted(self, widget, data=None):
self.exitdialog.hide()
def watch_stop_yes(self, widget, data=None):
#
def deactivate_event_mode(self, widget, data=None):
...
def __init__(self):
...
number_of_period = 2
watch_stop_default = True
add_time_seconds = 0
#
# define all relations between labels and entries and combobox and spinbutton and python variables
builder = gtk.Builder()
builder.add_from_file("/home/family/glade/scoreboard_uwr_180815.glade")
#
# load all windows
self.controlwindow = builder.get_object("scoreboard_control_window")
self.viewwindow = builder.get_object("scoreboard_view_window")
self.logdialog = builder.get_object("scoreboard_log_dialog")
self.logoffdialog = builder.get_object("scoreboard_logoff_confirm")
self.logcanceldialog = builder.get_object("scoreboard_logcancel_confirm")
self.resetdialog = builder.get_object("scoreboard_resetconfirm")
self.exitdialog = builder.get_object("scoreboard_exitconfirm")
#
# declaration of all data from the "scoreboard_control_window"
self.spinbutton_points_team_left = builder.get_object("spinbutton_points_team_left")
self.spinbutton_points_team_right = builder.get_object("spinbutton_points_team_right")
self.spinbutton_timeout_left = builder.get_object("spinbutton_timeout_left")
self.spinbutton_timeout_right = builder.get_object("spinbutton_timeout_right")
self.spinbutton_period_time = builder.get_object("spinbutton_period_time")
self.spinbutton_period = builder.get_object("spinbutton_period")
self.spinbutton_break_time = builder.get_object("spinbutton_break_time")
self.spinbutton_penalty_duration = builder.get_object("spinbutton_penalty_duration")
self.spinbutton_timeout = builder.get_object("spinbutton_timeout")
self.spinbutton_time_penalty = builder.get_object("spinbutton_time_penalty")
self.spinbutton_add_time = builder.get_object("spinbutton_add_time")
self.spinbutton_warning_timepenalty = builder.get_object("spinbutton_warning_timepenalty")
self.spinbutton_warning_break_timeout = builder.get_object("spinbutton_warning_break_timeout")
#
self.togglebutton_start_stop_game = builder.get_object("togglebutton_start_stop_game")
# self.comboboxtext_watch_stop = builder.get_object("comboboxtext_watch_stop")
self.entry_tournament_name = builder.get_object("entry_tournament_name")
self.entry_tournament_contact = builder.get_object("entry_tournament_contact")
self.entry_team_blue_name = builder.get_object("entry_team_blue_name")
self.entry_team_white_name = builder.get_object("entry_team_white_name")
self.entry_name_penalty_player_1_left = builder.get_object("entry_name_penalty_player_1_left")
self.entry_name_penalty_player_2_left = builder.get_object("entry_name_penalty_player_2_left")
self.entry_name_penalty_player_3_left = builder.get_object("entry_name_penalty_player_3_left")
self.entry_name_penalty_player_1_right = builder.get_object("entry_name_penalty_player_1_right")
self.entry_name_penalty_player_2_right = builder.get_object("entry_name_penalty_player_2_right")
self.entry_name_penalty_player_3_right = builder.get_object("entry_name_penalty_player_3_right")
# define here further entries
#
self.label_control_current_time = builder.get_object("label_control_current_time")
self.eventbox_control_left = builder.get_object("eventbox_control_left")
# self.eventbox_blue_team = builder.get_object("eventbox_blue_team")
self.label_control_team_name_left = builder.get_object("label_control_team_name_left")
self.eventbox_control_right = builder.get_object("eventbox_control_right")
self.label_control_team_name_right = builder.get_object("label_control_team_name_right")
self.label_control_tournament_name = builder.get_object("label_control_tournament_name")
self.label_control_tournament_contact = builder.get_object("label_control_tournament_contact")
self.spinbutton_minutes_time_correction = builder.get_object("spinbutton_minutes_time_correction")
self.spinbutton_seconds_time_correction = builder.get_object("spinbutton_seconds_time_correction")
# self.label_special_time_sequence = builder.get_object("label_special_time_sequence")
#
self.label_control_time_penalty_player_1_left = builder.get_object("label_control_time_penalty_player_1_left")
self.label_control_time_penalty_player_2_left = builder.get_object("label_control_time_penalty_player_2_left")
self.label_control_time_penalty_player_3_left = builder.get_object("label_control_time_penalty_player_3_left")
self.label_control_time_penalty_player_1_right = builder.get_object("label_control_time_penalty_player_1_right")
self.label_control_time_penalty_player_2_right = builder.get_object("label_control_time_penalty_player_2_right")
self.label_control_time_penalty_player_3_right = builder.get_object("label_control_time_penalty_player_3_right")
#
# self.label_timeout = builder.get_object("label_timeout")
# self.label_break = builder.get_object("label_break")
# self.label_penalty = builder.get_object("label_penalty")
#
self.spinbutton_points_team_left = builder.get_object("spinbutton_points_team_left")
self.spinbutton_points_team_right = builder.get_object("spinbutton_points_team_right")
self.eventbox_control_points_team_left = builder.get_object("eventbox_control_points_team_left")
self.eventbox_control_points_team_right = builder.get_object("eventbox_control_points_team_right")
self.label_control_points_team_left = builder.get_object("label_control_points_team_left")
self.label_control_points_team_right = builder.get_object("label_control_points_team_right")
self.label_control_special_time_sequence = builder.get_object("label_control_special_time_sequence")
self.eventbox_control_team_name_left = builder.get_object("eventbox_control_team_name_left")
self.eventbox_control_team_name_right = builder.get_object("eventbox_control_team_name_right")
#
# declaration of all data from the view window
self.eventbox_view_team_color_left = builder.get_object("eventbox_view_team_color_left")
self.eventbox_view_team_color_right = builder.get_object("eventbox_view_team_color_right")
self.eventbox_view_points_team_left = builder.get_object("eventbox_view_points_team_left")
self.eventbox_view_points_team_right = builder.get_object("eventbox_view_points_team_right")
self.label_view_period = builder.get_object("label_view_period")
self.label_view_current_time = builder.get_object("label_view_current_time")
self.label_view_points_team_left = builder.get_object("label_view_points_team_left")
self.label_view_timeout_left = builder.get_object("label_view_timeout_left")
self.label_view_timeout_right = builder.get_object("label_view_timeout_right")
self.label_view_points_team_right = builder.get_object("label_view_points_team_right")
self.eventbox_view_team_color_left = builder.get_object("eventbox_view_team_color_left")
self.eventbox_view_team_color_right = builder.get_object("eventbox_view_team_color_right")
self.label_view_team_name_left = builder.get_object("label_view_team_name_left")
self.label_view_team_name_right = builder.get_object("label_view_team_name_right")
self.eventbox_view_team_name_left = builder.get_object("eventbox_view_team_name_left")
self.eventbox_view_team_name_right = builder.get_object("eventbox_view_team_name_right")
self.label_view_tournament_name = builder.get_object("label_view_tournament_name")
self.label_view_tournament_contact = builder.get_object("label_view_tournament_contact")
self.label_view_specific_timesequence = builder.get_object("label_view_specific_timesequence")
self.label_view_status_specific_timesequence = builder.get_object("label_view_status_specific_timesequence")
self.label_view_special_time_sequence = builder.get_object("label_view_special_time_sequence")
self.label_view_time_penalty_player_1_left = builder.get_object("label_view_time_penalty_player_1_left")
self.label_view_time_penalty_player_2_left = builder.get_object("label_view_time_penalty_player_2_left")
self.label_view_time_penalty_player_3_left = builder.get_object("label_view_time_penalty_player_3_left")
self.label_view_time_penalty_player_1_right = builder.get_object("label_view_time_penalty_player_1_right")
self.label_view_time_penalty_player_2_right = builder.get_object("label_view_time_penalty_player_2_right")
self.label_view_time_penalty_player_3_right = builder.get_object("label_view_time_penalty_player_3_right")
#
self.label_view_name_penalty_player_1_left = builder.get_object("label_view_name_penalty_player_1_left")
self.label_view_name_penalty_player_2_left = builder.get_object("label_view_name_penalty_player_2_left")
self.label_view_name_penalty_player_3_left = builder.get_object("label_view_name_penalty_player_3_left")
self.label_view_name_penalty_player_1_right = builder.get_object("label_view_name_penalty_player_1_right")
self.label_view_name_penalty_player_2_right = builder.get_object("label_view_name_penalty_player_2_right")
self.label_view_name_penalty_player_3_right = builder.get_object("label_view_name_penalty_player_3_right")
#
self.button_blue_starts_left = builder.get_object("button_blue_starts_left")
self.button_blue_starts_right = builder.get_object("button_blue_starts_right")
self.button_type_view_invertedcontrolview = builder.get_object("button_type_view_invertedcontrolview")
self.button_type_view_copycontrolview = builder.get_object("button_type_view_copycontrolview")
self.button_separate_game_view_off = builder.get_object("button_separate_game_view_off")
self.button_separate_game_view_on = builder.get_object("button_separate_game_view_on")
self.button_log_functionality_off = builder.get_object("button_log_functionality_off")
self.button_log_functionality_on = builder.get_object("button_log_functionality_on")
self.entry_log_filename = builder.get_object("entry_log_filename")
self.button_nostop_watch = builder.get_object("button_nostop_watch")
self.button_stop_watch = builder.get_object("button_stop_watch")
self.button_activate_timepenalty_player_1_left = builder.get_object("button_activate_timepenalty_player_1_left")
self.button_activate_timepenalty_player_2_left = builder.get_object("button_activate_timepenalty_player_2_left")
self.button_activate_timepenalty_player_3_left = builder.get_object("button_activate_timepenalty_player_3_left")
self.button_activate_timepenalty_player_1_right = builder.get_object(
"button_activate_timepenalty_player_1_right")
self.button_activate_timepenalty_player_2_right = builder.get_object(
"button_activate_timepenalty_player_2_right")
self.button_activate_timepenalty_player_3_right = builder.get_object(
"button_activate_timepenalty_player_3_right")
self.button_clear_timepenalty_player_1_left = builder.get_object("button_clear_timepenalty_player_1_left")
self.button_clear_timepenalty_player_2_left = builder.get_object("button_clear_timepenalty_player_2_left")
self.button_clear_timepenalty_player_3_left = builder.get_object("button_clear_timepenalty_player_3_left")
self.button_clear_timepenalty_player_1_right = builder.get_object("button_clear_timepenalty_player_1_right")
self.button_clear_timepenalty_player_2_right = builder.get_object("button_clear_timepenalty_player_2_right")
self.button_clear_timepenalty_player_3_right = builder.get_object("button_clear_timepenalty_player_3_right")
self.button_stop_special_time_sequence = builder.get_object("button_stop_special_time_sequence")
self.button_start_special_time_sequence = builder.get_object("button_start_special_time_sequence")
self.button_clearreset_special_time_sequence = builder.get_object("button_clearreset_special_time_sequence")
self.button_special_time_sequence_none = builder.get_object("button_special_time_sequence_none")
self.button_special_time_sequence_timeout = builder.get_object("button_special_time_sequence_timeout")
self.button_special_time_sequence_break = builder.get_object("button_special_time_sequence_break")
self.button_special_time_sequence_penalty = builder.get_object("button_special_time_sequence_penalty")
#
self.ChooserButton_read_file_settings = builder.get_object("ChooserButton_read_file_settings")
#
self.label_log_dialog_time = builder.get_object("label_log_dialog_time")
self.entry_log_dialog_remark_referee = builder.get_object("entry_log_dialog_remark_referee")
self.entry_log_dialog_remark_scripter = builder.get_object("entry_log_dialog_remark_scripter")
##################################
# INIT the matrix of all inputs
#
col = 14
row = 10
logdata_array = [[""] * col for _ in range(row)]
#neutralarrayline = ["","","","","","","","","","","","","",""]
#logdata_array = []
#for i in range(9):
# logdata_array.append(neutralarrayline)
self.entry_logarray = []
for i in range(10):
self.entry_logarray.append([])
for j in range(14):
self.entry_logarray[i].append([])
stringglade = str('%(prefix)s%(line)02d_%(column)02d'%{'prefix': "ld", 'line': i, 'column': j})
#print(stringglade)
#"ld"+str(i)+"_"+str(j)
self.entry_logarray[i][j] = builder.get_object(stringglade)
##################################
#self.entry_log_dialog_remark_equipment = builder.get_object("entry_log_dialog_remark_equipment")
self.entry_anytime_line1intolog = builder.get_object("entry_anytime_line1intolog")
self.entry_anytime_line2intolog = builder.get_object("entry_anytime_line2intolog")
self.eventbox_exitbutton = builder.get_object("eventbox_exitbutton")
self.eventbox_resetbutton = builder.get_object("eventbox_resetbutton")
self.button_exit_view_window = builder.get_object("button_exit_view_window")
#
# connect all signals to actions
builder.connect_signals(self)
thread_time_control.connect("update_timers", self.update_timer_labels)
#
# GDK_Escape = 0xff1b
buffer_time_start_special_time_sequence = datetime.now()
#
# datetime data useful for elapsed time calculation and later for log / protocol
start_time_of_the_game = datetime.now()
start_time_control_timepenalty_player1_left = datetime.now()
start_time_control_timepenalty_player2_left = datetime.now()
start_time_control_timepenalty_player3_left = datetime.now()
start_time_control_timepenalty_player1_right = datetime.now()
start_time_control_timepenalty_player2_right = datetime.now()
start_time_control_timepenalty_player3_right = datetime.now()
start_time_of_second_period = datetime.now()
end_time_of_the_game = datetime.now() # usefull for log / protocol
# for running time calculation of the main time counting
buffer_last_time_stop = datetime.now()
buffer_last_time_stop_control_timepenalty_player1_left = datetime.now()
buffer_last_time_stop_control_timepenalty_player2_left = datetime.now()
buffer_last_time_stop_control_timepenalty_player3_left = datetime.now()
buffer_last_time_stop_control_timepenalty_player1_right = datetime.now()
buffer_last_time_stop_control_timepenalty_player2_right = datetime.now()
buffer_last_time_stop_control_timepenalty_player3_right = datetime.now()
buffer_last_time_start = datetime.now()
buffer_last_time_start_control_timepenalty_player1_left = datetime.now()
buffer_last_time_start_control_timepenalty_player2_left = datetime.now()
buffer_last_time_start_control_timepenalty_player3_left = datetime.now()
buffer_last_time_start_control_timepenalty_player1_right = datetime.now()
buffer_last_time_start_control_timepenalty_player2_right = datetime.now()
buffer_last_time_start_control_timepenalty_player3_right = datetime.now()
#
# SEVERAL global parameters and stopwatches to be defined
# FIRST for period time downcounting
# SECOND for special_time_sequence
# 3 for the time penalty players left
# 3 for the time penalty players right
#
ellapsed_period_time_seconds = 0
buffer_last_started_ellapsed_period_time_seconds = 0
period_time_in_second = 15 * 60
period_time_in_second_orig = 15*60
counter_seconds_board = 15 * 60
warning_timepenalty = warning_default_timepenalty
warning_break_timeout = warning_default_break_timeout
#
# diverse parameter of special_time_sequence
timepenalty_maximum_seconds = 120
penalty_maximum_seconds = 45
timeout_maximum_seconds = 1 * 60
break_maximum_seconds = 300
ellapsed_special_time_sequence_seconds = 0
counter_seconds_special_time_sequence = 0
ellapsed_maximum_time_special_sequence_seconds = 300
#
ellapsed_time_penalty_player_1_left_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_1_left_seconds = 0
counter_seconds_time_penalty_player_1_left = 0
#
ellapsed_time_penalty_player_2_left_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_2_left_seconds = 0
counter_seconds_time_penalty_player_2_left = 0
#
ellapsed_time_penalty_player_3_left_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_3_left_seconds = 0
counter_seconds_time_penalty_player_3_left = 0
#
ellapsed_time_penalty_player_1_right_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_1_right_seconds = 0
counter_seconds_time_penalty_player_1_right = 0
#
ellapsed_time_penalty_player_2_right_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_2_right_seconds = 0
counter_seconds_time_penalty_player_2_right = 0
#
ellapsed_time_penalty_player_3_right_seconds = 0
buffer_last_started_ellapsed_time_penalty_player_3_right_seconds = 0
counter_seconds_time_penalty_player_3_right = 0
#
activated_time_penalty_player_1_left_to_enter_or_delete = False
activated_time_penalty_player_2_left_to_enter_or_delete = False
activated_time_penalty_player_3_left_to_enter_or_delete = False
activated_time_penalty_player_1_right_to_enter_or_delete = False
activated_time_penalty_player_2_right_to_enter_or_delete = False
activated_time_penalty_player_3_right_to_enter_or_delete = False
#
time_penalty_player_1_left_initialized = False
time_penalty_player_1_right_initialized = False
time_penalty_player_2_left_initialized = False
time_penalty_player_2_right_initialized = False
time_penalty_player_3_left_initialized = False
time_penalty_player_3_right_initialized = False
#
# diverse helpfull match status or timing
game_started = False
action_start_time_of_the_game_is_ACTIVE = False # toggle button start / stop of the overall timing
running_period_time = False
running_first_period_time = False
running_second_period_time = False
running_penalty = False
running_timeout = False
running_break = False
stopped_special_time_sequence = False
# basic setup of team name
left_team_is_blue = True # at application start
#
running_time_penalty_player_1_left = False
running_time_penalty_player_2_left = False
running_time_penalty_player_3_left = False
running_time_penalty_player_1_right = False
running_time_penalty_player_2_right = False
running_time_penalty_player_3_right = False
#
# buffer for switching the results from right to left in the score viewer
buffer_counter_minutes_time_penalty_player_1 = 0
buffer_counter_seconds_time_penalty_player_1 = 0
buffer_counter_minutes_time_penalty_player_2 = 0
buffer_counter_seconds_time_penalty_player_2 = 0
buffer_counter_minutes_time_penalty_player_3 = 0
buffer_counter_seconds_time_penalty_player_3 = 0
buffer_running_time_penalty_player_1_left = False
buffer_running_time_penalty_player_2_left = False
buffer_running_time_penalty_player_3_left = False
buffer_points_team = 0
################################
# right is white background (and black letter)
self.eventbox_control_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_view_team_color_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
# right point area white
self.eventbox_control_points_team_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_view_points_team_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_control_team_name_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_view_team_name_right.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
# right letters of points black in white team
self.label_control_points_team_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
self.label_view_points_team_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
self.label_control_team_name_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
self.label_view_team_name_right.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1))
#
# left point area blue
self.eventbox_control_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_view_team_color_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_control_points_team_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_view_points_team_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
# left letters of points white in blue team
self.label_control_points_team_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.label_view_points_team_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.eventbox_control_team_name_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.eventbox_view_team_name_left.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 1, 1))
self.label_control_team_name_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
self.label_view_team_name_left.override_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 1, 1, 1))
#
#
self.entry_tournament_name.set_text("tournament")
self.label_control_tournament_name.set_text("tournament")
self.label_view_tournament_name.set_text("tournament")
#
self.entry_tournament_contact.set_text("Ms./Mr.")
self.label_control_tournament_contact.set_text("Ms./Mr.")
self.label_view_tournament_contact.set_text("Ms./Mr.")
#
self.entry_team_blue_name.set_text("TeamBLUE")
self.label_control_team_name_left.set_text("TeamBLUE")
self.label_view_team_name_left.set_text("Team BLUE")
#
self.entry_team_white_name.set_text("TeamWHITE")
self.label_control_team_name_right.set_text("TeamWHITE")
self.label_view_team_name_right.set_text("Team WHITE")
#
# make exit button for red
self.eventbox_exitbutton.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 0, 0, 1))
#
# orange https://en.wikipedia.org/wiki/X11_color_names test rgb 100% 65% 0%
self.eventbox_resetbutton.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 0.65, 0, 1))
# make reset button for red
# self.eventbox_resetbutton.override_background_color(gtk.StateFlags.NORMAL, gdk.RGBA(1, 0, 0, 1))
self.label_control_special_time_sequence.set_text("none")
#
style_provider = gtk.CssProvider()
############################################################################################
############################################################################################
#
# modify that link below at a new installation
#
############################################################################################
css = open('/home/family/glade/scoreboard_uwr/scoreboard_gui_styles.css',
'rb') # rb needed for python 3 support
############################################################################################
############################################################################################
css_data = css.read()
css.close()
style_provider.load_from_data(css_data)
gtk.StyleContext.add_provider_for_screen(gdk.Screen.get_default(), style_provider,
gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
if __name__ == "__main__":
GUI = GUIclass()
GUI.controlwindow.show()
gtk.main()

how to create a row of cubes with a random width in python

I want to create a row of tiles with a random width. i can do it for 2 cubes, but i don't know how to do it for 100 cubes.
import maya.cmds as cmds
import random
cubeList = cmds.ls( 'Tiles*' )
if len(cubeList) > 0:
cmds.delete( cubeList )
#create row and col list
cols = 2
arr = []
for col in xrange (cols):
width_rand_Size = random.uniform(0.8,3)
arr.append(cmds.polyCube (ax = (0,0,1), w = width_rand_Size, h = 1, d =1 , n='Tiles#'))
if col != 0:
cmds.setAttr( "Tiles2.tx",(cmds.polyCube('Tiles1', q = 1, w = 1))/2 + (cmds.polyCube('Tiles2', q = 1, w = 1))/2)
You have to make the script automatically find the name of your object and previous object each time you're iterating. Then you compute the space between the current tile and all the previous created tiles.
Here is the code:
import maya.cmds as cmds
import random
cubeList = cmds.ls( 'Tiles*' )
if len(cubeList) > 0:
cmds.delete( cubeList )
#create row and col list
cols = 10 # number of tiles to create
x = 1 # increment variable
arr = []
allTilesSpace = [] # cumalated space between tiles
for col in xrange (cols):
# if there is no tile to create, do nothing
if not cols:
break
# get the names of the objects
currentTile = 'Tiles%d' % x
previousTile = "Tiles%d" % (x - 1)
# set random width
width_rand_Size = random.uniform(0.8,3)
arr.append(cmds.polyCube (ax = (0,0,1), w = width_rand_Size, h = 1, d =1 , n=currentTile))
# Move the tiles
currentTileWidth = cmds.polyCube(currentTile, q = 1, w = 1)
if cmds.objExists(previousTile):
previousTileWidth = cmds.polyCube(previousTile, q = 1, w = 1)
allTilesSpace.append(previousTileWidth)
tilesSpace = sum(allTilesSpace) + (currentTileWidth / 2)
cmds.setAttr(currentTile + ".tx",tilesSpace)
else:
cmds.setAttr(currentTile + ".tx", currentTileWidth / 2)
x += 1 # increment

Creating a tiled map with blender

I'm looking at creating map tiles based on a 3D model made in blender,
The map is 16 x 16 in blender.
I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400.
The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600
What I need is a script for blender that can create the tiles from the model.
I've never written in python before so I've been trying to adapt a couple of the scripts which are already there.
So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles.
Here is what I've got so far...
#!BPY
"""
Name: 'Export Map Tiles'
Blender: '242'
Group: 'Export'
Tip: 'Export to Map'
"""
import Blender
from Blender import Scene,sys
from Blender.Scene import Render
def init():
thumbsize = 200
CameraHeight = 4.4
YStart = -8
YMove = 4
XStart = -8
XMove = 4
ZoomLevel = 1
Path = "/Images/Map/"
Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path]
def show_prefs():
buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]);
buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1])
buttonYStart = Blender.Draw.Create(Blender.drawmap[2])
buttonYMove = Blender.Draw.Create(Blender.drawmap[3])
buttonXStart = Blender.Draw.Create(Blender.drawmap[4])
buttonXMove = Blender.Draw.Create(Blender.drawmap[5])
buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6])
buttonPath = Blender.Draw.Create(Blender.drawmap[7])
block = []
block.append(("Image Size", buttonthumbsize, 0, 500))
block.append(("Camera Height", buttonCameraHeight, -0, 10))
block.append(("Y Start", buttonYStart, -10, 10))
block.append(("Y Move", buttonYMove, 0, 5))
block.append(("X Start", buttonXStart,-10, 10))
block.append(("X Move", buttonXMove, 0, 5))
block.append(("Zoom Level", buttonZoomLevel, 1, 10))
block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles"))
retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block)
if retval:
Blender.drawmap[0] = buttonthumbsize.val
Blender.drawmap[1] = buttonCameraHeight.val
Blender.drawmap[2] = buttonYStart.val
Blender.drawmap[3] = buttonYMove.val
Blender.drawmap[4] = buttonXStart.val
Blender.drawmap[5] = buttonXMove.val
Blender.drawmap[6] = buttonZoomLevel.val
Blender.drawmap[7] = buttonPath.val
Export()
def Export():
scn = Scene.GetCurrent()
context = scn.getRenderingContext()
def cutStr(str): #cut off path leaving name
c = str.find("\\")
while c != -1:
c = c + 1
str = str[c:]
c = str.find("\\")
str = str[:-6]
return str
#variables from gui:
thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap
XMove = XMove / ZoomLevel
YMove = YMove / ZoomLevel
Camera = Scene.GetCurrent().getCurrentCamera()
Camera.LocZ = CameraHeight / ZoomLevel
YStart = YStart + (YMove / 2)
XStart = XStart + (XMove / 2)
#Point it straight down
Camera.RotX = 0
Camera.RotY = 0
Camera.RotZ = 0
TileCount = 4**ZoomLevel
#Because the first thing we do is move the camera, start it off the map
Camera.LocY = YStart - YMove
for i in range(0,TileCount):
Camera.LocY = Camera.LocY + YMove
Camera.LocX = XStart - XMove
for j in range(0,TileCount):
Camera.LocX = Camera.LocX + XMove
Render.EnableDispWin()
context.extensions = True
context.renderPath = Path
#setting thumbsize
context.imageSizeX(thumbsize)
context.imageSizeY(thumbsize)
#could be put into a gui.
context.imageType = Render.PNG
context.enableOversampling(0)
#render
context.render()
#save image
ZasString = '%s' %(int(ZoomLevel))
XasString = '%s' %(int(j+1))
YasString = '%s' %(int((3-i)+1))
context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString)
#close the windows
Render.CloseRenderWindow()
try:
type(Blender.drawmap)
except:
#print 'initialize extern variables'
init()
show_prefs()
This was relatively simple in the end.
I scaled up the model so that 1 tile on the map was 1 grid in blender.
Set the camera to be orthographic.
Set the scale on the camera to 1 for the highest zoom, 4 for the next one, 16 for the next one and so on.
Updated the start coordinates and move values accordingly.

Categories

Resources