Если ваша среда выполнения Python одинакова при каждом запуске скрипта, попробуйте переместить инициализацию в обработчик исключений. Вот так:
try:
velocity_x = (velocity_x * -1)
except:
velocity_x = 0.09
Вы также можете попробовать вставить переменную в модуль __main__
, если это не сработает. Вот так:
try:
__main__.velocity_x = (velocity_x * -1)
except:
__main__.velocity_x = 0.09
Если это не сработает, вам понадобится что-то более легкое и встроенное, например модуль sqlite3.
Я переписал весь ваш фрагмент кода:
import sqlite3
#The current location of the object
loc_x = obj.getPosition()[0]
loc_y = obj.getPosition()[1]
c = sqlite3.connect('/tmp/globals.db')
#c = sqlite3.connect('/dev/shm/globals.db')
# Using the commented connection line above instead will be
# faster on Linux. But it will not persist beyond a reboot.
# Both statements create the database if it doesn't exist.
# This will auto commit on exiting this context
with c:
# Creates table if it doesn't exist
c.execute('''create table if not exist vectors
(vector_name text primary key not null,
vector_value float not null,
unique (vector_name))''')
# Try to retrieve the value from the vectors table.
c.execute('''select * from vectors''')
vector_count = 0
for vector in c:
vector_count = vector_count + 1
# sqlite3 always returns unicode strings
if vector['vector_name'] == u'x':
vector_x = vector['vector_value']
elif vector['vector_name'] == u'y':
vector_y = vector['vector_value']
# This is a shortcut to avoid exception logic
# Change the count to match the number of vectors
if vector_count != 2:
vector_x = 0.09
vector_y = 0.03
# Insert default x vector. Should only have to do this once
with c:
c.executemany("""replace into stocks values
(?, ?)""", [('x', vector_x), ('y', vector_y)])
#If the location of the object is over 5, bounce off.
if loc_x > 5:
velocity_x = (velocity_x * -1)
if loc_y > 5:
velocity_y = (velocity_y * -1)
# Update stored vectors every time through the loop
with c:
c.executemany("""update or replace stocks set vector_name = ?,
vector_value = ?)""", [('x', vector_x), ('y', vector_y)])
#Every frame set the object's position to the old position plus the velocity
obj.setPosition([(loc_x + velocity_x),(loc_y + velocity_y),0])
# We can also close the connection if we are done with it
c.close()
Да, это может быть настроено на функции или необычные классы, но если это то, что вы делаете, вам не нужно намного больше, чем это.