本文整理汇总了Python中kivy.storage.jsonstore.JsonStore.exists方法的典型用法代码示例。如果您正苦于以下问题:Python JsonStore.exists方法的具体用法?Python JsonStore.exists怎么用?Python JsonStore.exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kivy.storage.jsonstore.JsonStore
的用法示例。
在下文中一共展示了JsonStore.exists方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WeatherRoot
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class WeatherRoot(BoxLayout):
carousel = ObjectProperty()
current_weather = ObjectProperty()
forecast = ObjectProperty()
locations = ObjectProperty()
add_location_form = ObjectProperty()
def __init__(self, **kwargs):
super(WeatherRoot, self).__init__(**kwargs)
self.store = JsonStore("weather_store.json")
if self.store.exists('locations'):
current_location = self.store.get("locations")["current_location"]
self.show_current_weather(current_location)
def show_current_weather(self, location=None):
self.clear_widgets()
if self.current_weather is None:
self.current_weather = CurrentWeather()
if self.locations is None:
self.locations = Factory.Locations()
if (self.store.exists('locations')):
locations = self.store.get("locations")['locations']
self.locations.locations_list.adapter.data.extend(locations)
if location is not None:
self.current_weather.location = location
if location not in self.locations.locations_list.adapter.data:
self.locations.locations_list.adapter.data.append(location)
self.locations.locations_list._trigger_reset_populate()
self.store.put("locations",
locations=list(self.locations.locations_list.adapter.data),
current_location=location)
self.current_weather.update_weather()
self.add_widget(self.current_weather)
def show_forecast(self, location=None):
self.clear_widgets()
if self.forecast is None:
self.forecast = Factory.Forecast()
if location is not None:
self.forecast.location = location
self.forecast.update_weather()
self.add_widget(self.forecast)
# BEGIN SHOW_MODAL_VIEW
def show_add_location_form(self):
self.add_location_form = AddLocationForm()
self.add_location_form.open()
# END SHOW_MODAL_VIEW
def show_locations(self):
self.clear_widgets()
self.add_widget(self.locations)
示例2: ScoreBar
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class ScoreBar(BoxLayout):
score = NumericProperty()
hi_score = NumericProperty()
game_id = StringProperty()
players = NumericProperty()
active_player = NumericProperty()
def __init__(self,**kwargs):
super(ScoreBar,self).__init__(**kwargs)
self.store = JsonStore(os.path.join(get_user_path(),'scores.json'))
self.bind(score = self.score_changed)
self.set_game_id()
def set_game_id(self, game_id = 'default', multiplayer = False):
self.players = int(multiplayer) + 1
self.active_player = 1
self.game_id = game_id
if self.players == 1:
if self.store.exists(game_id):
data = self.store.get(game_id)
self.hi_score = data['high_score']
else:
self.hi_score = 0
def score_changed(self, *args):
if self.players == 2:
return
if self.game_id != 'default':
date = uspac.fromutc(datetime.datetime.utcnow())
game_id = 'd%i%i%i'%(date.year, date.month, date.day)
if self.game_id != game_id:
#daily challenge has finished, the game reverts to default type so we only update the default high score table
self.set_game_id()
else:
#store the high score in the default table as well as in the daily table
hi_score = 0
if self.store.exists('default'):
data = self.store.get('default')
hi_score = data['high_score']
if self.score > hi_score:
self.store.put('default',high_score=int(self.score))
if self.score > self.hi_score:
self.hi_score = self.score
self.store.put(self.game_id,high_score=int(self.score))
if platform == 'android' and self.players == 1:
if self.score > 600:
App.get_running_app().gs_achieve('achievement_score_of_600')
if self.score > 800:
App.get_running_app().gs_achieve('achievement_score_of_800')
if self.score > 1000:
App.get_running_app().gs_achieve('achievement_score_of_1000')
if self.score > 1200:
App.get_running_app().gs_achieve('achievement_score_of_1200')
示例3: UrbanRoot
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class UrbanRoot(BoxLayout):
urbansearch = ObjectProperty()
urbandict = ObjectProperty()
def __init__(self, **kwargs):
super(UrbanRoot, self).__init__(**kwargs)
self.store = JsonStore("dictionary.json")
self.update_urbandict()
def add_to_dictionary(self, word, definition, example):
current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else []
d = {
'word' : word.encode('utf-8'),
'definition' : definition.encode('utf-8'),
'example' : example.encode('utf-8')
}
if d not in current:
current.append(d)
self.store.put('dictionary', dictionary = list(current))
self.update_urbandict()
Popup(size_hint=(0.8,0.2),title='Success', content = Label(text = 'Word has been added into dictionary')).open()
def update_urbandict(self):
current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else []
self.urbandict.urbandictcontainer.clear_widgets()
for d in current:
item = Factory.UrbanItemDict()
item.word = d['word'].encode('utf-8')
item.definition = d['definition'].replace('\r','').replace('\t','').encode('utf-8')
item.example = d['example'].replace('\r','').replace('\t','').encode('utf-8')
self.urbandict.urbandictcontainer.add_widget(item)
def remove_from_dict(self, word, definition, example):
current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else []
d = {
'word' : word.encode('utf-8'),
'definition' : definition.encode('utf-8'),
'example' : example.encode('utf-8')
}
if d in current:
current.remove(d)
self.store.put('dictionary', dictionary = list(current))
print 'removed'
self.update_urbandict()
示例4: on_enter
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
def on_enter(self):
pathstore = JsonStore("pathstore.json")
if pathstore.exists("path"):
print pathstore["path"]
self.imagepath = pathstore["path"]["path"][0]
print self.imagepath
self.populateCarousel()
示例5: on_enter
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
def on_enter(self):
""" The filebrowser screen is being opened """
if not self.initailized:
self.initailized = True
store = JsonStore("zenplayer.json")
if store.exists("filebrowser"):
if "path" in store.get("filebrowser").keys():
file_path = store.get("filebrowser")["path"]
if exists(file_path):
self.filechooser.path = file_path
示例6: MainApp
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class MainApp(App):
#create the application screens
def build(self):
data_dir = getattr(self, 'user_data_dir') #get a writable path to save our score
self.store = JsonStore(join(data_dir, 'score.json')) # create a JsonScore file in the available location
if(not self.store.exists('score')): # if there is no file, we need to save the best score as 1
self.store.put('score', best=1)
if platform() == 'android': # if we are on Android, we can initialize the ADs service
revmob.start_session('54c247f420e1fb71091ad44a')
self.screens = {} # list of app screens
self.screens['menu'] = MenuScreen(self) #self the MainApp instance, so others objects can change the screen
self.screens['game'] = GameScreen(self)
self.root = FloatLayout()
self.open_screen('menu')
self.sound = SoundLoader.load('res/background.mp3') # open the background music
# kivy support music loop, but it was not working on Android. I coded in a different way to fix it
# but if fixed, we can just set the loop to True and call the play(), so it'll auto repeat
# self.sound.loop = True It # was not working on android, so I wrote the following code:
self.sound.play() # play the sound
Clock.schedule_interval(self.check_sound, 1) #every second force the music to be playing
return self.root
# play the sound
def check_sound(self, dt = None):
self.sound.play()
# when the app is minimized on Android
def on_pause(self):
self.sound.stop() # the stop the sound
Clock.unschedule(self.check_sound)
if platform() == 'android': #if on android, we load an ADs and show it
revmob.show_popup()
return True
# when the app is resumed
def on_resume(self):
self.sound.play() # we start the music again
Clock.schedule_interval(self.check_sound, 1)
# show a new screen.
def open_screen(self, name):
self.root.clear_widgets() #remove the current screen
self.root.add_widget(self.screens[name]) # add a new one
self.screens[name].run() # call the run method from the desired screen
示例7: ClockApp
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class ClockApp(App):
clearcolor = (0,0,0,1)
def __init__(self,**kwargs):
super(ClockApp,self).__init__(**kwargs)
from os.path import join
self.store = JsonStore(join(self.user_data_dir,"clockalarm.json"))
def build(self):
root = ClockWidget()
root.init_alarms()
self.root=root
return self.root
def on_pause(self):
return True
def on_resume(self):
pass
def get_alarm_from_store(self,id):
if self.store.exists("alarms"):
try:
return self.store.get("alarms")["a{}".format(id)]
except:
return None
def set_alarm_to_store(self,id,alarm):
allAlarms = {}
for i in range(1,5):
if i == int(id):
allAlarms["{}".format(i)]=alarm
else:
allAlarms["{}".format(i)]=app.get_alarm_from_store("{}".format(i))
self.store.put("alarms",a1=allAlarms["1"],a2=allAlarms["2"],a3=allAlarms["3"],a4=allAlarms["4"])
示例8: Settings
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class Settings(object):
MIN_TOASTING_TIME = 10
MAX_TOASTING_TIME = 600
FILENAME = 'sofatech_toaster_storage'
SETTINGS_KEY = 'settings'
def __init__(self):
self._ip = '127.0.0.1'
self._port = 50007
self._store = JsonStore(Settings.FILENAME)
@property
def ip(self):
return self._ip
@ip.setter
def ip(self, value):
self._ip = value
@property
def port(self):
return self._port
@port.setter
def port(self, value):
self._port = value
def load(self):
if self._store.exists(Settings.SETTINGS_KEY):
settings_dict = self._store.get(Settings.SETTINGS_KEY)
self._ip = settings_dict['ip']
self._port = settings_dict['port']
def save(self):
self._store.put(Settings.SETTINGS_KEY, ip=self._ip, port=self._port)
示例9: DescargarApp
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class DescargarApp(App):
# Desactiva el cuadro de configuración genérico de Kivy
use_kivy_settings = False
# Para que no se cierre al cambiar de aplicación en Android
def on_pause(self):
return True
def build(self):
self.download_thread = None
self.store = JsonStore("descargar-aragontv.json")
if not self.store.exists("target_folder"):
if self.get_platform_name()=="android":
from jnius import autoclass
Environment = autoclass('android.os.Environment')
download_folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
self.store.put("target_folder",value=download_folder.getAbsolutePath() )
else:
self.store.put("target_folder",value=os.path.expanduser("~") )
if not self.store.exists("source_url"):
self.store.put("source_url",value="http://alacarta.aragontelevision.es/programas/chino-chano/por-la-sierra-de-armantes-28022016-1452")
self.screen_manager = ScreenManager(transition=FadeTransition())
self.paso1 = Paso1(name='Paso 1')
self.paso1.ids.target_folder.text = self.store.get("target_folder")["value"]
self.paso1.ids.page_url.text = self.store.get("source_url")["value"]
self.paso2 = Paso2(name='Paso 2')
self.paso3 = Paso3(name='Paso 3')
self.screen_manager.add_widget(self.paso1)
self.screen_manager.add_widget(self.paso2)
self.screen_manager.add_widget(self.paso3)
return self.screen_manager
def dismiss_popup(self):
self._popup.dismiss()
def target_selected(self, path, filename):
self._popup.dismiss()
self.paso1.ids.target_folder.text = path
self.store.put("target_folder",value=self.paso1.ids.target_folder.text)
def target_selection(self):
content = LoadDialog(load=self.target_selected, cancel=self.dismiss_popup)
content.ids.filechooser.path = self.paso1.ids.target_folder.text
self._popup = Popup(title="Elige destino", content=content, size_hint=(0.9, 0.9))
self._popup.open()
def message(self,title,body):
content = MessageDialog()
content.ids.message_body.text = body
self._popup = Popup(title=title, content=content, size_hint=(0.8, 0.8))
self._popup.open()
def url_ready(self,page_url):
print "url_ready"
print self.paso1.ids.page_url.text
if not self.paso1.ids.page_url.text.startswith("http://") and not self.paso1.ids.page_url.text.startswith("https://"):
self.message("Hay un problema...","La URL que has introducido no es válida")
return
self.store.put("target_folder",value=self.paso1.ids.target_folder.text)
self.store.put("source_url",value=self.paso1.ids.page_url.text)
from core.item import Item
item = Item(url=self.paso1.ids.page_url.text)
from channels import aragontv
item = aragontv.detalle_episodio(item)
self.video_title = item.title
self.media_url = item.media_url
if self.media_url=="":
self.message("Hay un problema...","No se puede encontrar un vídeo en esa URL")
return
self.screen_manager.current = self.screen_manager.next()
self.paso2.ids.description.text = "[b]"+item.title+"[/b]\n\n"+item.plot
def start_download(self):
print "start_download"
self.paso3.resultado = "Descargando "+self.media_url+"\n\n"
self.screen_manager.current = self.screen_manager.next()
# Start download in background
from core import downloadtools
clean_file_name = downloadtools.limpia_nombre_caracteres_especiales(self.video_title.decode("utf-8"))+".flv"
#.........这里部分代码省略.........
示例10: WeatherRoot
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class WeatherRoot(BoxLayout):
current_weather = ObjectProperty()
locations = ObjectProperty()
forecast = ObjectProperty()
def __init__(self, **kwargs):
super(WeatherRoot, self).__init__(**kwargs)
self.store = JsonStore("weather_store.json")
if self.store.exists('locations'):
current_location = self.store.get("locations")["current_location"]
self.show_current_weather(current_location)
def show_current_weather(self, location=None):
self.clear_widgets()
if self.current_weather is None:
self.current_weather = CurrentWeather()
if self.locations is None:
self.locations = Factory.Locations()
if self.store.exists('locations'):
locations = self.store.get("locations")['locations']
self.locations.locations_list.adapter.data.extend(locations)
if location is not None:
self.current_weather = CurrentWeather(location=location)
adapter_data = self.locations.locations_list.adapter.data
if location not in adapter_data:
adapter_data.append(location)
self.locations.locations_list._trigger_reset_populate()
self.store.put("locations", locations=list(adapter_data),
current_location=location)
self.current_weather.update_weather()
self.add_widget(self.current_weather)
def show_add_location_form(self):
self.clear_widgets()
self.add_widget(AddLocationForm())
def show_locations(self):
self.clear_widgets()
self.add_widget(self.locations)
def show_forecast(self, location=None):
self.clear_widgets()
if self.forecast is None:
self.forecast = Factory.Forecast()
if location is not None:
self.forecast.location = location
self.forecast.update_weather()
self.add_widget(self.forecast)
@staticmethod
def format_location(location):
return "{} ({})".format(*location)
示例11: __init__
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class _2048Controller:
def __init__(self):
self.width = 4
self.height = 4
self.store = JsonStore('data.json')
self.best_score = 0
if self.store.exists('score'):
self.best_score = self.store.get('score')['best_score']
self.initGame()
def initGame(self):
self.score = 0
self.undo_left = 2
self.undo_game_array = []
self.game_array = self.generateGameArray()
#self.game_array = [[0, 0, 8, 16], [32, 64, 128, 256], [512, 1024, 2048, 4096], [8192, 16384, 32768, 65536]]
self.end_game = False
self.new_number_array = [] # list of new number is generated
self.undo_game_array = [] # ####
for i in range(2):
self.generateNumber() # generate 2 new numbers
def checkExists(self, x, y):
return self.game_array[y][x] != 0
def generateGameArray(self):
game_board = []
for y in range(self.height):
rows = []
for x in range(self.width):
rows.append(0)
game_board.append(rows)
return game_board
def generateNumber(self):
while True: # loop until the position is valid
x = random.randint(0, self.width - 1)
y = random.randint(0, self.height - 1)
if not self.checkExists(x, y):
number = 2
if random.randint(1, 100) > 80:
number = 4
self.game_array[y][x] = number
break
self.new_number_array.append((x, y))
def slideUp(self, game_board=None):
if not game_board:
game_board = self.game_array
moved = False
score = 0
animation_way = []
for x in range(self.width):
notCombineList = []
for y in range(self.height):
if game_board[y][x] == 0:
continue
for stop_y in range(y - 1, -1, -1):
if game_board[stop_y][x] != 0:
if game_board[stop_y][x] == game_board[y][x] and stop_y not in notCombineList:
game_board[stop_y][x] *= 2
game_board[y][x] = 0
moved = True
score += game_board[stop_y][x]
notCombineList.append(stop_y)
animation_way.append([(x, y), (x, stop_y)])
else:
game_board[stop_y + 1][x], game_board[y][x] = game_board[y][x], game_board[stop_y + 1][x]
if y != stop_y + 1:
animation_way.append([(x, y), (x, stop_y + 1)])
moved = True
break
if stop_y == 0 and game_board[0][x] == 0 and game_board[y][x] != game_board[0][x]:
game_board[0][x], game_board[y][x] = game_board[y][x], game_board[0][x]
moved = True
animation_way.append([(x, y), (x, stop_y)])
return [moved, score, animation_way]
def slideDown(self, game_board=None):
if not game_board:
game_board = self.game_array
moved = False
score = 0
animation_way = []
for x in range(self.width):
notCombineList = []
for y in range(self.width - 1, -1, -1):
if game_board[y][x] == 0:
continue
for stop_y in range(y + 1, self.height):
if game_board[stop_y][x] != 0:
if game_board[stop_y][x] == game_board[y][x] and stop_y not in notCombineList:
game_board[stop_y][x] *= 2
game_board[y][x] = 0
moved = True
score += game_board[stop_y][x]
notCombineList.append(stop_y)
animation_way.append([(x, y), (x, stop_y)])
else:
game_board[stop_y - 1][x], game_board[y][x] = game_board[y][x], game_board[stop_y - 1][x]
#.........这里部分代码省略.........
示例12: KivyBirdApp
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class KivyBirdApp(App):
pipes = []
playing = False
score = 0
scored = False
highscore = StringProperty("0")
#legg til her
def build(self):
self.highscorestore = JsonStore("highscore.json")
if self.highscorestore.exists("highscore"):
print self.highscorestore.get("highscore")["score"]
self.highscore = self.highscorestore.get("highscore")["score"]
return KivyBirdRoot()
# Når ting går over til ScreenManager, må du huske å bytte root.ids til screenen sin ID
# Dette gjøres gjennom root.ids.kivybird_screen_manager.get_screen("game_screen")
def on_start(self):
self.spacing = 0.5 * self.root.width
self.background = self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.background
self.score_label = ScoreLabel()
self.bird = self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.bird
Clock.schedule_interval(self.update, 1.0/60.0)
Window.bind(on_key_down=self.on_key_down)
self.background.on_touch_down = self.user_action
sfx_start.play()
self.background.update(1.0 / 60.0)
def on_key_down(self, window, key, *args):
if key == Keyboard.keycodes['spacebar']:
self.user_action()
def user_action(self, *args):
if not self.playing:
sfx_start.play()
self.bird.gravity_on(self.root.height)
self.spawn_pipes()
self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.score_label.text = "0"
self.score = 0
self.playing = True
sfx_flap.play()
self.bird.bump()
def update(self, nap):
if not self.playing:
return
self.background.update(nap)
self.bird.update(nap)
for p in self.pipes:
p.x -= 96 * nap
if p.x <= -64:
p.x += 4 * self.spacing
p.ratio = random.uniform(0.25, 0.75)
p.scored = False
if self.test_game_over():
current_score = self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.score_label.text
#self.highscorestore["highscore"] = {"score": current_score}
if int(current_score) > int(self.highscore):
self.highscore = current_score
self.highscorestore.put("highscore", score=current_score)
sfx_die.play()
self.playing = False
def test_game_over(self):
screen_height = self.root.height
if self.bird.y < 90 or self.bird.y > screen_height - 50:
return True
for p in self.pipes:
if not p.collide_widget(self.bird):
continue
if (self.bird.y < p.lower_len + 116 or
self.bird.y > screen_height - (p.upper_len + 75)):
return True
if not p.scored and p.x < self.bird.x:
p.scored = True
sfx_score.play()
self.score += 1
self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.score_label.text = str(self.score)
return False
def spawn_pipes(self):
for p in self.pipes:
self.root.remove_widget(p)
self.pipes = []
for i in range(4):
p = Pipe(x=self.root.width + (self.spacing * i))
p.ratio = random.uniform(0.25, 0.75)
self.root.add_widget(p)
self.pipes.append(p)
示例13: FindBWidget
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
#.........这里部分代码省略.........
return
i = Random().randint(0,len(self.BBoxList) - 1)
if self.BBoxList[i].isBomb:
return False
else:
self.BBoxList[i].isBomb = True
#set bomb number of the around boxes
row = self.BBoxList[i].row
col = self.BBoxList[i].col
self._add_bomb_number(row - 1,col - 1)
self._add_bomb_number(row - 1,col)
self._add_bomb_number(row - 1,col + 1)
self._add_bomb_number(row,col - 1)
self._add_bomb_number(row,col + 1)
self._add_bomb_number(row + 1,col - 1)
self._add_bomb_number(row + 1,col)
self._add_bomb_number(row + 1,col + 1)
return True
def _add_bomb_number(self,row,col):
if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height:
return
index = row*self.gridSize_width + col
if index < 0 or index >= len(self.BBoxList):
return
self.BBoxList[index].BNumber += 1
def Clear(self,row,col):
if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height:
return
index = row*self.gridSize_width + col
if index < 0 or index >= len(self.BBoxList):
return
self.BBoxList[index].MarkNumberOrEmpty()
def ShowAll(self):
self.status_bar.toggle_mark.state='normal'
for i in range(0,len(self.BBoxList)):
if self.BBoxList[i].isBomb:
self.BBoxList[i].bbutton.MarkB()
else:
self.BBoxList[i].Clear()
def CheckSucceed(self):
if self.bfound > 0 and self.bfound == self.bnumber:
for i in range(0,len(self.BBoxList)):
if self.BBoxList[i].state == 0:
return False
#upgrade level
if self.mute == False:
self.sounds['upgrade'].play()
if self.custimize == False:
duration = round((clock() - self.start_clock),2)
if self.levels_info.has_key(self.level) and self.levels_info[self.level] > 0:
if self.levels_info[self.level] > duration:
self.levels_info[self.level] = duration
else:
self.levels_info[self.level] = duration
if self.level < Max_Level:
self.level += 1
self.store_user_data(self.level,self.levels_info)
self.Restart()
return True
else:
return False
def get_level_info(self):
if self.store.exists("UserData") == False:
self.store.put("UserData",CurrentLevel=1,Levels={})
return self.store.get("UserData")["CurrentLevel"],self.store.get("UserData")["Levels"]
def get_mute_info(self):
return self.config.get('Sounds','Mute') == '1'
def get_customize_info(self):
return self.config.get('Customization','Enable') == '1',self.config.getint('Customization','C_Height'),self.config.getint('Customization','C_Width'),self.config.getint('Customization','Rate')
def store_user_data(self,currentLevel,levels):
self.store.put("UserData",CurrentLevel=currentLevel,Levels=levels)
def GameOver(self):
self.status_bar.toggle_mark.disable = True
self.status_bar.button_reset.image.source='gameover.png'
self.gameover = True
示例14: RobRehabGUI
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
class RobRehabGUI( Widget ):
connection = None
currentServerAddress = None
UPDATE_INTERVAL = 0.02
setpointsUpdated = True
isCalibrating = False
isSampling = False
isOperating = False
samplingEvent = None
operationEvent = None
JOINT = 0
AXIS = 1
deviceIDs = ( [], [] )
currentDeviceIndexes = [ None for i in range( len(deviceIDs) ) ]
NULL_ID = '<Select>'
axisMeasures = [ 0.0 for var in range( DOF_VARS_NUMBER ) ]
setpoints = [ 0.0 for var in range( DOF_VARS_NUMBER ) ]
jointMeasures = [ 0.0 for var in range( DOF_VARS_NUMBER ) ]
class DataPlot:
def __init__( self, handle, values, source, offset ):
self.handle = handle
self.values = values
self.source = source
self.offset = offset
dataPlots = []
INITIAL_VALUES = [ 0.0 for value in range( 101 ) ]
def __init__( self, **kwargs ):
super( RobRehabGUI, self ).__init__( **kwargs )
self.configStorage = JsonStore( 'config.json' )
if self.configStorage.exists( 'server' ): self.ids[ 'address_input' ].text = self.configStorage.get( 'server' )[ 'address' ]
if self.configStorage.exists( 'user' ): self.ids[ 'user_name_input' ].text = self.configStorage.get( 'user' )[ 'name' ]
self.deviceSelectors = ( self.ids[ 'joint_selector' ], self.ids[ 'axis_selector' ] )
self.deviceEntries = [ DropDown() for selector in self.deviceSelectors ]
for index in range( len(self.deviceEntries) ):
def SelectEntry( instance, name, index=index ):
self.SetDevice( index, name )
self.deviceEntries[ index ].bind( on_select=SelectEntry )
self.deviceSelectors[ index ].bind( on_release=self.deviceEntries[ index ].open )
dataGraph = self.ids[ 'data_graph' ]
measure_range = self.ids[ 'measure_slider' ].range
GRAPH_PROPERTIES = { 'xlabel':'Last Samples', 'x_ticks_minor':5, 'x_ticks_major':25, 'y_ticks_major':0.25, 'y_grid_label':True, 'x_grid_label':True,
'padding':5, 'x_grid':True, 'y_grid':True, 'xmin':0, 'xmax':len(self.INITIAL_VALUES) - 1, 'ymin':measure_range[ 0 ], 'ymax':measure_range[ 1 ],
'background_color':[ 1, 1, 1, 1 ], 'tick_color':[ 0, 0, 0, 1 ], 'border_color':[ 0, 0, 0, 1 ], 'label_options':{ 'color': [ 0, 0, 0, 1 ], 'bold':True } }
axisPositionGraph = Graph( ylabel='Position', **GRAPH_PROPERTIES )
axisPositionPlot = SmoothLinePlot( color=[ 0, 0, 1, 1 ] )
axisPositionGraph.add_plot( axisPositionPlot )
self.dataPlots.append( RobRehabGUI.DataPlot( axisPositionPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_POSITION ) )
axisVelocityPlot = SmoothLinePlot( color=[ 0, 1, 0, 1 ] )
axisPositionGraph.add_plot( axisVelocityPlot )
self.dataPlots.append( RobRehabGUI.DataPlot( axisVelocityPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_VELOCITY ) )
refPositionPlot = SmoothLinePlot( color=[ 0, 0, 0.5, 1 ] )
axisPositionGraph.add_plot( refPositionPlot )
self.dataPlots.append( RobRehabGUI.DataPlot( refPositionPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_POSITION ) )
refVelocityPlot = SmoothLinePlot( color=[ 0, 0.5, 0, 1 ] )
axisPositionGraph.add_plot( refVelocityPlot )
self.dataPlots.append( RobRehabGUI.DataPlot( refVelocityPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_VELOCITY ) )
axisAccelerationPlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] )
axisPositionGraph.add_plot( axisAccelerationPlot )
self.dataPlots.append( RobRehabGUI.DataPlot( axisAccelerationPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_ACCELERATION ) )
dataGraph.add_widget( axisPositionGraph )
dataGraph.add_widget( Label( size_hint_y=0.05 ) )
axisForceGraph = Graph( ylabel='Torque', **GRAPH_PROPERTIES )
axisForcePlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] )
axisForceGraph.add_plot( axisForcePlot )
self.dataPlots.append( RobRehabGUI.DataPlot( axisForcePlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_FORCE ) )
dataGraph.add_widget( axisForceGraph )
Clock.schedule_interval( self.NetworkUpdate, self.UPDATE_INTERVAL / 2 )
Clock.schedule_interval( self.GraphUpdate, self.UPDATE_INTERVAL * 2 )
Clock.schedule_interval( self.SliderUpdate, self.UPDATE_INTERVAL )
def ConnectClient( self, serverAddress ):
self.connection = None
self.robotID = ''
self.deviceIDs = ( [], [] )
serverType, serverHost = serverAddress.split( '://' )
print( 'acquired %s server host: %s' % ( serverType, serverHost ) )
if serverType == 'ip': self.connection = ipclient.Connection()
if self.connection is not None:
self.configStorage.put( 'server', address=serverAddress )
self.connection.Connect( serverHost )
self.robotID, self.deviceIDs = self.connection.RefreshInfo()
self.ids[ 'robot_id_display' ].text = self.robotID
def UpdateSelectorEntries( selector, entriesList, entryNames ):
#.........这里部分代码省略.........
示例15: JsonStore
# 需要导入模块: from kivy.storage.jsonstore import JsonStore [as 别名]
# 或者: from kivy.storage.jsonstore.JsonStore import exists [as 别名]
serverTime = datetime.datetime.utcnow().replace(microsecond=0)
# Client Time reported locally.
localTime = datetime.datetime.now().replace(microsecond=0)
# Cache Files
jobCache = JsonStore('jobs.json')
pilotCache = JsonStore('pilots.json')
statusCache = JsonStore('server.json')
# Server connection objects can be reused for each connection point
# to the api as each one may have a different cache timer.
# Server(serverName, serverAddress, serverStatus, serverPlayers, datetime.datetime(cacheExpire), serverPing)
if statusCache.exists('server'):
print('Server Status Already Exists:', statusCache.get('server'))
# This possibly needs moving/redesign (Into preferences dialog)
if (statusCache.get('server')['name']) == 'Tranquility':
apiURL = 'https://api.eveonline.com/'
elif (statusCache.get('server')['name']) == 'Singularity':
apiURL = 'https://api.testeveonline.com/'
else:
apiURL = ''
serverConn = Server(statusCache.get('server')['name'], apiURL, statusCache.get('server')['status'], statusCache.get('server')['players'],
datetime.datetime(*(time.strptime((statusCache.get('server')['cacheExpires']), '%Y-%m-%d %H:%M:%S')[0:6])),
statusCache.get('server')['ping'])
else:
# Provide a default here.