def update(self, mario, goombas, stats, settings): self.check_collisions(mario, goombas, stats, settings) if self.status == "Dying": if pygame.time.get_ticks( ) - self.killed_time > self.killed_delay_time: # If enough time has passed since the enemy was killed self.status = "DisplayingScore" # Show the enemy's point value if self.status == "DisplayingScore": self.rect.y -= 5 if pygame.time.get_ticks( ) - self.killed_time > 1000: # If enough time has passed since the score began displaying goombas.remove( self) # Remove the score and the enemy simultaneously if self.gamemap.object_touching_wall(self): self.speed *= -1 # Walking self.rect.x += 1 * self.speed # Perform gravity if not self.gamemap.object_touching_ground(self): Gravity.perform(self) self.animate() self.blitme()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity(nobroadcast=True, wif=[wif]) # from getpass import getpass # self.grv.wallet.unlock(getpass()) set_shared_gravity_instance(self.grv) self.grv.set_default_account("init0")
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, wif={"active": wif} ) set_shared_gravity_instance(self.grv) self.grv.set_default_account("init0") self.mock()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, # We want to bundle many operations into a single transaction bundle=True, # Overwrite wallet to use this list of wifs only wif=[wif]) self.grv.set_default_account("init0") set_shared_gravity_instance(self.grv)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, wif={ # Force signing with this key "active": wif }) set_shared_gravity_instance(self.grv) self.grv.set_default_account("init0")
class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, # We want to bundle many operations into a single transaction bundle=True, # Overwrite wallet to use this list of wifs only wif=[wif]) self.grv.set_default_account("init0") set_shared_gravity_instance(self.grv) def test_account(self): Account("witness-account") Account("1.2.3") asset = Asset("1.3.0") symbol = asset["symbol"] account = Account("witness-account", full=True) self.assertEqual(account.name, "witness-account") self.assertEqual(account["name"], account.name) self.assertEqual(account["id"], "1.2.1") self.assertIsInstance(account.balance("1.3.0"), Amount) self.assertIsInstance(account.balance({"symbol": symbol}), Amount) self.assertIsInstance(account.balances, list) for h in account.history(limit=1): pass # BlockchainObjects method account.cached = False self.assertTrue(account.items()) account.cached = False self.assertIn("id", account) account.cached = False self.assertEqual(account["id"], "1.2.1") self.assertEqual(str(account), "<Account 1.2.1>") self.assertIsInstance(Account(account), Account) def test_account_upgrade(self): account = Account("witness-account") tx = account.upgrade() ops = tx["operations"] op = ops[0][1] self.assertEqual(len(ops), 1) self.assertEqual(getOperationNameForId(ops[0][0]), "account_upgrade") self.assertTrue(op["upgrade_to_lifetime_member"]) self.assertEqual( op["account_to_upgrade"], "1.2.1", )
def new_func(ctx, *args, **kwargs): newoptions = ctx.obj newoptions.update(kwargsChain) ctx.gravity = Gravity(**newoptions) ctx.blockchain = ctx.gravity set_shared_gravity_instance(ctx.gravity) return ctx.invoke(f, *args, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, ) set_shared_gravity_instance(self.grv)
class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): super(Testcases, self).__init__(*args, **kwargs) self.grv = Gravity(nobroadcast=True, keys=wifs) set_shared_gravity_instance(self.grv) self.mockAccount() def mockAccount(self): _cache = ObjectCache(default_expiration=60 * 60 * 1, no_overwrite=True) for i in test_operation_dicts: _cache[i["id"]] = i BlockchainObject._cache = _cache def test_finalize(self): account = Account(account_id) op = operations.Transfer( **{ "fee": { "asset_id": "1.3.0", "amount": 1 }, "from": account_id, "to": '1.2.8', "amount": { "asset_id": "1.3.0", "amount": 1 } }) tx = self.grv.finalizeOp(op, account, "active") self.assertEqual(len(tx["signatures"]), 1)
def __init__(self,x,y,image,folder=''): Image.__init__(self,x,y,image,folder) self.spawn_x = x self.spawn_y = y self.xvel = 0 self.yvel = 0 self.gravity = Gravity(5)
def __init__(self): self.state = State() self.state.timestep = ts_simulation self.rigid_body = RigidBody() self.gravity = Gravity(self.state) self.wind = Wind(self.state) self.aero = Aerodynamics(self.state) self.thrust = Thrust(self.state) self.intg = get_integrator(self.state.timestep, self.eom)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity(nobroadcast=True, ) set_shared_gravity_instance(self.grv) self.asset = Asset("1.3.0") self.symbol = self.asset["symbol"] self.precision = self.asset["precision"] self.asset2 = Asset("1.3.1")
class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, # We want to bundle many operations into a single transaction bundle=True, # Overwrite wallet to use this list of wifs only wif=[wif], offline=True ) self.grv.set_default_account("init0") set_shared_gravity_instance(self.grv) def test_get_pub_from_wif(self): self.assertEqual( self.grv.wallet._get_pub_from_wif(wif), "ZGV6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV" )
def __init__(self, screen, settings, gamemap): super(Mario, self).__init__() self.screen = screen self.screen_rect = self.screen.get_rect() self.settings = settings self.gravity = Gravity() self.gamemap = gamemap self.image = pygame.image.load("media/images/mario/standing.png") self.image = pygame.transform.scale(self.image, (35, 50)) self.rect = self.image.get_rect() self.dist = 0 self.speed = 0 self.dir = 1 # -1 = moving left, 0 = standing still, 1 = moving right self.moving_right = False self.moving_left = False self.jumping = False self.jump_finished = False self.jump_speed = 0 self.jump_start = False self.last_img_update = pygame.time.get_ticks() self.last_img_mode = 1
def AddGravity(self): #This method adds gravity to the simulation: if (len(FreeCAD.ActiveDocument.getObjectsByLabel("MBDyn_simulation")) == 1): #Only if a world exists: #Add gravity: obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "gravity") Gravity(obj) CustomView(obj.ViewObject) #Move the gravity object to it's container: FreeCAD.ActiveDocument.getObject("Forces").addObject(obj) else: QtGui.QMessageBox.information(None, 'Error.', 'You have to create a world firts.')
def run(self): self.objects = [m for m in self.objects if not m.isDead()] self.satellite = 0 for m in self.objects: if type(m) == type(Satellite(self.parent,self)): self.satellite += 1 m.run() m.applyForce(Gravity.getForce(m.location,self.planet.location)) for m2 in self.objects: if m == m2: continue if m.isCollide() or m2.isCollide(): continue if m.isCollide(m2): m.explosion() m2.explosion() self.planet.run() self.update() self.output()
class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, wif={"active": wif} ) set_shared_gravity_instance(self.grv) self.grv.set_default_account("init0") self.mock() def mock(self): # Inject test data into cache _cache = ObjectCache(default_expiration=60 * 60 * 1, no_overwrite=True) for i in _objects: _cache[i["id"]] = i BlockchainObject._cache = _cache def test_connect(self): self.grv.connect() def test_set_default_account(self): self.grv.set_default_account("init0") def test_info(self): info = self.grv.info() for key in ['current_witness', 'head_block_id', 'head_block_number', 'id', 'last_irreversible_block_num', 'next_maintenance_time', 'random', 'recently_missed_count', 'time']: self.assertTrue(key in info) def test_finalizeOps(self): grv = self.grv tx1 = grv.new_tx() tx2 = grv.new_tx() self.grv.transfer("init1", 1, core_unit, append_to=tx1) self.grv.transfer("init1", 2, core_unit, append_to=tx2) self.grv.transfer("init1", 3, core_unit, append_to=tx1) tx1 = tx1.json() tx2 = tx2.json() ops1 = tx1["operations"] ops2 = tx2["operations"] self.assertEqual(len(ops1), 2) self.assertEqual(len(ops2), 1) def test_transfer(self): grv = self.grv tx = grv.transfer( "1.2.8", 1.33, core_unit, memo="Foobar", account="1.2.7") self.assertEqual( getOperationNameForId(tx["operations"][0][0]), "transfer" ) op = tx["operations"][0][1] self.assertIn("memo", op) self.assertEqual(op["from"], "1.2.7") self.assertEqual(op["to"], "1.2.8") amount = Amount(op["amount"]) self.assertEqual(float(amount), 1.33) def test_create_account(self): grv = self.grv name = ''.join(random.choice(string.ascii_lowercase) for _ in range(12)) key1 = PrivateKey() key2 = PrivateKey() key3 = PrivateKey() key4 = PrivateKey() tx = grv.create_account( name, registrar="init0", # 1.2.7 referrer="init1", # 1.2.8 referrer_percent=33, owner_key=str(key1.pubkey), active_key=str(key2.pubkey), memo_key=str(key3.pubkey), additional_owner_keys=[str(key4.pubkey)], additional_active_keys=[str(key4.pubkey)], additional_owner_accounts=["committee-account"], # 1.2.0 additional_active_accounts=["committee-account"], proxy_account="init0", storekeys=False ) self.assertEqual( getOperationNameForId(tx["operations"][0][0]), "account_create" ) op = tx["operations"][0][1] role = "active" self.assertIn( str(key2.pubkey), [x[0] for x in op[role]["key_auths"]]) self.assertIn( str(key4.pubkey), [x[0] for x in op[role]["key_auths"]]) self.assertIn( "1.2.0", [x[0] for x in op[role]["account_auths"]]) role = "owner" self.assertIn( str(key1.pubkey), [x[0] for x in op[role]["key_auths"]]) self.assertIn( str(key4.pubkey), [x[0] for x in op[role]["key_auths"]]) self.assertIn( "1.2.0", [x[0] for x in op[role]["account_auths"]]) self.assertEqual( op["options"]["voting_account"], "1.2.7") self.assertEqual( op["registrar"], "1.2.7") self.assertEqual( op["referrer"], "1.2.8") self.assertEqual( op["referrer_percent"], 33 * 100) def test_weight_threshold(self): grv = self.grv auth = {'account_auths': [['1.2.0', '1']], 'extensions': [], 'key_auths': [ ['ZGV55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n', 1], ['ZGV7GM9YXcsoAJAgKbqW2oVj7bnNXFNL4pk9NugqKWPmuhoEDbkDv', 1]], 'weight_threshold': 3} # threshold fine grv._test_weights_treshold(auth) auth = {'account_auths': [['1.2.0', '1']], 'extensions': [], 'key_auths': [ ['ZGV55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n', 1], ['ZGV7GM9YXcsoAJAgKbqW2oVj7bnNXFNL4pk9NugqKWPmuhoEDbkDv', 1]], 'weight_threshold': 4} # too high with self.assertRaises(ValueError): grv._test_weights_treshold(auth) def test_allow(self): grv = self.grv tx = grv.allow( "ZGV55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n", weight=1, threshold=1, permission="owner" ) self.assertEqual( getOperationNameForId(tx["operations"][0][0]), "account_update" ) op = tx["operations"][0][1] self.assertIn("owner", op) self.assertIn( ["ZGV55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n", '1'], op["owner"]["key_auths"]) self.assertEqual(op["owner"]["weight_threshold"], 1) """ Disable this test until we can test with an actual setup on the main/testnet def test_disallow(self): grv = self.grv with self.assertRaisesRegex(ValueError, ".*Changes nothing.*"): grv.disallow( "ZGV55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n", weight=1, threshold=1, permission="owner" ) with self.assertRaisesRegex(ValueError, ".*Cannot have threshold of 0.*"): grv.disallow( "ZGV6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV", weight=1, threshold=1, permission="owner" ) """ def test_update_memo_key(self): grv = self.grv tx = grv.update_memo_key("ZGV55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n") self.assertEqual( getOperationNameForId(tx["operations"][0][0]), "account_update" ) op = tx["operations"][0][1] self.assertEqual( op["new_options"]["memo_key"], "ZGV55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n") def test_approvewitness(self): grv = self.grv tx = grv.approvewitness("1.6.1") self.assertEqual( getOperationNameForId(tx["operations"][0][0]), "account_update" ) op = tx["operations"][0][1] self.assertIn( "1:0", op["new_options"]["votes"]) def test_approvecommittee(self): grv = self.grv tx = grv.approvecommittee("1.5.0") self.assertEqual( getOperationNameForId(tx["operations"][0][0]), "account_update" ) op = tx["operations"][0][1] self.assertIn( "0:11", op["new_options"]["votes"])
class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity( nobroadcast=True, wif={ # Force signing with this key "active": wif }) set_shared_gravity_instance(self.grv) self.grv.set_default_account("init0") def test_add_one_proposal_one_op(self): grv = self.grv tx1 = grv.new_tx() proposal1 = grv.new_proposal(tx1, proposer="init0") op = operations.Transfer( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "from": "1.2.0", "to": "1.2.0", "amount": { "amount": 0, "asset_id": "1.3.0" }, "prefix": "ZGV" }) proposal1.appendOps(op) tx = tx1.json() self.assertEqual(tx["operations"][0][0], 22) self.assertEqual(len(tx["operations"]), 1) ps = tx["operations"][0][1] self.assertEqual(len(ps["proposed_ops"]), 1) self.assertEqual(ps["proposed_ops"][0]["op"][0], 0) def test_add_one_proposal_two_ops(self): grv = self.grv tx1 = grv.new_tx() proposal1 = grv.new_proposal(tx1, proposer="init0") op = operations.Transfer( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "from": "1.2.0", "to": "1.2.0", "amount": { "amount": 0, "asset_id": "1.3.0" }, "prefix": "ZGV" }) proposal1.appendOps(op) proposal1.appendOps(op) tx = tx1.json() self.assertEqual(tx["operations"][0][0], 22) self.assertEqual(len(tx["operations"]), 1) ps = tx["operations"][0][1] self.assertEqual(len(ps["proposed_ops"]), 2) self.assertEqual(ps["proposed_ops"][0]["op"][0], 0) self.assertEqual(ps["proposed_ops"][1]["op"][0], 0) def test_have_two_proposals(self): grv = self.grv tx1 = grv.new_tx() # Proposal 1 proposal1 = grv.new_proposal(tx1, proposer="init0") op = operations.Transfer( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "from": "1.2.0", "to": "1.2.0", "amount": { "amount": 0, "asset_id": "1.3.0" }, "prefix": "ZGV" }) for i in range(0, 3): proposal1.appendOps(op) # Proposal 1 proposal2 = grv.new_proposal(tx1, proposer="init0") op = operations.Transfer( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "from": "1.2.0", "to": "1.2.0", "amount": { "amount": 5555555, "asset_id": "1.3.0" }, "prefix": "ZGV" }) for i in range(0, 2): proposal2.appendOps(op) tx = tx1.json() self.assertEqual(len(tx["operations"]), 2) # 2 proposals # Test proposal 1 prop = tx["operations"][0] self.assertEqual(prop[0], 22) ps = prop[1] self.assertEqual(len(ps["proposed_ops"]), 3) for i in range(0, 3): self.assertEqual(ps["proposed_ops"][i]["op"][0], 0) # Test proposal 2 prop = tx["operations"][1] self.assertEqual(prop[0], 22) ps = prop[1] self.assertEqual(len(ps["proposed_ops"]), 2) for i in range(0, 2): self.assertEqual(ps["proposed_ops"][i]["op"][0], 0)
from gravity import Gravity from gravity.account import Account grv = Gravity("wss://grvapi.graphenelab.org/ws") acc = Account('g9480a2230f7280f3790') print('Getting Account: {}'.format(acc))
def __init__(self, *args, **kwargs): super(Testcases, self).__init__(*args, **kwargs) self.grv = Gravity(nobroadcast=True, keys=wifs) set_shared_gravity_instance(self.grv) self.mockAccount()
class App(): #управляющий приложением класс def __init__(self): self.running = True self.window = None self.clock = pygame.time.Clock() self.fps = 60 self.w_size = (WINDOW_W, WINDOW_H) self.s_size = (SCREEN_W, SCREEN_H) self.collide_ent = [] self.gravity_ent = [] self.decor_ent_fore = [] self.decor_ent_back = [] self.spikes = [] self.dialog_windows = [] self.texts = [] text = open("texts.json", "r", encoding="utf-8") self.texts = loads(text.read()) text.close() self.upgrades = [] self.fullScreen = True self.difficulty = 1 self.mainFont = "gui/font.ttf" text = open("language.json", "r") language = loads(text.read()) text.close() self.language = language["Language"] self.creditsImage = (pygame.image.load("gui/credits.png")) self.creditsOn = False self.story = False self.level = 1 ##### self.nextWave = False self.pause = False self.stop = False self.enemies = [] ##### self.dt = 0 def credits(self, screen): if self.creditsOn: screen.blit(self.creditsImage, (WINDOW_W - self.creditsImage.get_width(), 0, self.creditsImage.get_width(), self.creditsImage.get_height())) def init_gamepad(self): #инициализация одного геймпада self.joystick_count = pygame.joystick.get_count() if self.joystick_count > 0: self.joystick = pygame.joystick.Joystick(0) self.joystick.init() def save_game(self): #сохрание прогресса игрока text = open("save.json", "r") save = loads(text.read()) text.close() save["hp"] = self.player.hp save["Points"] = self.player.points save["Wave"] = self.waves upgrades = [] for upgrade in self.upgrades: upgrades.append(upgrade.bought) save["Upgrades"] = upgrades text = open("save.json", "w") dump(save, text) text.close() def next_wave(self): #вызов следующей волны self.waves += 1 if self.story: #story mode self.wave = Wave(5, self) self.nextWave = True if self.waves == 6: self.game_channel.pause() self.battle_music.play(-1) else: #arena mode if self.waves > 10: self.win() elif self.waves > 9: self.game_channel.pause() self.battle_music.play(-1) self.newboss.activate() self.create_enemy(type=4, boss=True) self.wave = Wave(3, self) self.nextWave = True else: self.nextWave = True self.wave = Wave(randint(2, 5), self) #if self.waves % 2 == 0 and self.waves != 12 and self.player.hp > 0: #сохранение #self.save_game() def create_enemy(self, type=None, boss=False, x=None, y=None): #создание случайного врага if x == None: x = randint(20 * BLOCK_SIZE, SCREEN_W - 20 * BLOCK_SIZE) if y == None: y = SCREEN_H - BLOCK_SIZE speed = randint(2, 5) if not type: if self.waves > 3: type = randint(1, 3) elif self.waves > 1: type = randint(1, 2) elif self.waves == 1: type = 1 ''' if self.waves >= 7: #self.newmobgolem.activate() type = randint(0,3) elif self.waves >= 5: #self.newmobskeleton.activate() type = randint(0,2) elif self.waves >= 3: #self.newmobvampire.activate() type = randint(0,1) else: type = 0 ''' if boss: enemy = Boss(x, y, copy(self.types["Mob"][type]["Idle_r"]), copy(self.types["Mob"][type]["Idle_l"]), self, speed, copy(self.types["Mob"][type]["HP"]), copy(self.types["Mob"][type]["Damage"]), copy(self.types["Mob"][type]["Points"])) else: enemy = Enemy(x, y, copy(self.types["Mob"][type]["Idle_r"]), copy(self.types["Mob"][type]["Idle_l"]), self, speed, copy(self.types["Mob"][type]["HP"]), copy(self.types["Mob"][type]["Damage"]), copy(self.types["Mob"][type]["Points"])) self.enemies.append(enemy) enemy.set_target(self.player) enemy.initSpawn(copy(self.types["Mob"][type]["Anims"]["Anim_spawn"])) enemy.initAnim(copy(self.types["Mob"][type]["Anim_go_r"]), copy(self.types["Mob"][type]["Anim_go_l"])) effect = pygame.mixer.Sound("enemy/damage.ogg") effect.set_volume(VOLUME) enemy.initAttack(copy(self.types["Mob"][type]["Anim_attack_r"]), copy(self.types["Mob"][type]["Anim_attack_l"]), effect) effect_dead = pygame.mixer.Sound('enemy/dead.ogg') effect_dead.set_volume(VOLUME) effect_hit = pygame.mixer.Sound("enemy/hit.ogg") effect_hit.set_volume(VOLUME) enemy.initDead(copy(self.types["Mob"][type]["Anims"]["Anim_death_r"]), copy(self.types["Mob"][type]["Anims"]["Anim_death_l"]), effect_dead, effect_hit) if boss: spell = Spell(0, 0, self.types["Spell"][0]["Idle"], self.types["Spell"][0]["Damage"], self) effect = pygame.mixer.Sound(self.types["Spell"][0]["Sound"]) effect.set_volume(VOLUME) spell.initAnim(self.types["Spell"][0]["Anims"]["Anim_r"], self.types["Spell"][0]["Anims"]["Anim_l"], effect) enemy.set_spell(spell) def play_a_different_song(self, songs): next_song = choice(songs) while next_song == self.currently_playing_song: next_song = choice(songs) self.currently_playing_song = next_song self.game_channel.queue(next_song) def new_game(self, wave=0, load=False): #начало новой игры #pygame.mouse.set_visible(False) #курсор скроется self.upgradesMenu.set_button_colors() if not load: #обнуление улучшений for upgrade in self.upgrades: upgrade.bought = False for caption in self.dialog_windows: caption.count = 0 if self.story: self.level = 1 self.map = "level1.txt" else: self.greeting.activate() self.level = 0 self.map = "map.txt" self.create_map(self.map) #self.nextWave = False self.waves = wave #счётчик волн self.creditsOn = False self.pause = False self.stop = False self.menu_music.stop() self.battle_music.stop() self.end_music.stop() self.game_channel.stop() self.enemies = [] create_player(self) def load_game(self): #загрузка игры с сохранения text = open("save.json") save = loads(text.read()) text.close() self.new_game(wave=save["Wave"] - 1, load=True) upgrades = save["Upgrades"] for idUpgrade in range(len(self.upgrades)): self.upgrades[idUpgrade].bought = upgrades[idUpgrade] for upgrade in self.upgrades: if upgrade.bought: upgrade.bought = False upgrade.buy(noLimits=True) self.player.hp = save["hp"] self.player.points = save["Points"] def win(self): #завершение игры(победа) self.textend = pygame.font.Font(self.mainFont, 100).render( self.texts[self.language]["Win"], True, (255, 0, 0)) self.stop = True def game_over(self): #завершение игры(поражение) self.textend = pygame.font.Font(self.mainFont, 100).render( self.texts[self.language]["GameOver"], True, (255, 0, 0)) self.stop = True def delete_map(self): #удаление карты self.collide_ent = [] self.decor_ent_fore = [] self.decor_ent_back = [] self.spikes = [] def create_map(self, map): #карта #newmap = Map() #newmap.generate() #newmap.write() self.delete_map() text = open(map) blocks = [ "", "tiles/block.png", "tiles/grass.png", "tiles/stone.png", "tiles/decor1.png", "tiles/tree.png", "tiles/decor2.png", "tiles/decor3.png", "tiles/spikes.png", "tiles/wall.png", "tiles/backwall.png", "tiles/door.png", "tiles/backblock.png", "tiles/roof.png" ] i = 10 for line in text: j = 0 for block in line: if block == " ": continue elif block in ("1", "2", "3", "9"): object = CollideObject(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i, blocks[int(block)]) self.collide_ent.append(object) elif block in ("4", "5", "6", "7"): decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i, blocks[int(block)]) #self.decor_ent_fore.append(decor) self.decor_ent_back.append(decor) elif block in ("8"): spikes = Spikes(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i, blocks[int(block)], self) self.spikes.append(spikes) elif block in ("B"): decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i, blocks[10]) self.decor_ent_back.append(decor) elif block in ("D"): decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i, blocks[11]) self.decor_ent_back.append(decor) elif block in ("C"): decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i, blocks[12]) self.decor_ent_back.append(decor) elif block in ("R"): decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i, blocks[13]) self.decor_ent_back.append(decor) j += 1 i -= 1 #тк генерируем снизу (зеркально) text.close() def set_full_screen(self): #полноэкранный режим self.window = pygame.display.set_mode( self.w_size, pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) def set_window_screen(self): #оконный режим self.window = pygame.display.set_mode(self.w_size) def on_init(self): #инициализация игры pygame.init() self.init_gamepad() self.set_full_screen() pygame.display.set_caption('Dead riot') #строчка на панели управления pygame.display.set_icon( pygame.image.load("enemy/zombie/idle_r.png")) #иконка self.running = True self.map = "level1.txt" self.battle_music = pygame.mixer.Sound("music/battle_music.ogg") self.battle_music.set_volume(VOLUME) self.end_music = pygame.mixer.Sound("music/end_music.ogg") self.menu_music = pygame.mixer.Sound("music/menu_music.ogg") self.menu_music.set_volume(VOLUME) self.music1 = pygame.mixer.Sound("music/music1.ogg") self.music2 = pygame.mixer.Sound("music/music2.ogg") self.music3 = pygame.mixer.Sound("music/music3.ogg") self.music4 = pygame.mixer.Sound("music/music4.ogg") self.music1.set_volume(VOLUME) self.music2.set_volume(VOLUME / 3) self.music3.set_volume(VOLUME * 3) self.music4.set_volume(VOLUME) self.songs = [] self.songs.append(self.music1) self.songs.append(self.music2) self.songs.append(self.music3) self.songs.append(self.music4) self.currently_playing_song = None self.SONGEND = pygame.USEREVENT + 1 self.game_channel = pygame.mixer.Channel(0) self.game_channel.set_endevent(self.SONGEND) self.screen = pygame.Surface(self.s_size) self.subscreen = pygame.Surface(self.w_size) self.gravity = Gravity(0.1) #главное меню self.mainMenu = MainMenu(0, 0, "gui/back.png", self) self.mainMenu.activate() #self.create_map(self.map) initAnims(self) #меню self.menu = SideMenu(0, 0, "gui/window.png", self) #вывод диалогового окна print(self.texts[self.language]["Msg1.1"]) self.msg11 = DialogWindow(self.texts[self.language]["Msg1.1"], self, 1) self.msg12 = DialogWindow(self.texts[self.language]["Msg1.2"], self, 1) self.msg13 = DialogWindow(self.texts[self.language]["Msg1.3"], self, 1) self.msg14 = DialogWindow(self.texts[self.language]["Msg1.4"], self, 1) self.msg21 = DialogWindow(self.texts[self.language]["Msg2.1"], self, 1) self.msg22 = DialogWindow(self.texts[self.language]["Msg2.2"], self, 1) self.msg23 = DialogWindow(self.texts[self.language]["Msg2.3"], self, 1) self.msg31 = DialogWindow(self.texts[self.language]["Msg3.1"], self, 1) self.msg32 = DialogWindow(self.texts[self.language]["Msg3.2"], self, 1) self.msg33 = DialogWindow(self.texts[self.language]["Msg3.3"], self, 1) self.msg41 = DialogWindow(self.texts[self.language]["Msg4.1"], self, 1) self.msg42 = DialogWindow(self.texts[self.language]["Msg4.2"], self, 1) self.msg43 = DialogWindow(self.texts[self.language]["Msg4.3"], self, 1) self.msg44 = DialogWindow(self.texts[self.language]["Msg4.4"], self, 1) self.msg45 = DialogWindow(self.texts[self.language]["Msg4.5"], self, 1) ''' self.newmobvampire = DialogWindow("Beware of bloodsuckers... ", self, 1) self.newmobskeleton = DialogWindow("Bones are ringing... ", self, 1) self.newmobgolem = DialogWindow("Something big is coming... ", self, 1) ''' self.greeting = DialogWindow(self.texts[self.language]["MsgA1"], self, 1) self.newboss = DialogWindow(self.texts[self.language]["MsgA2"], self, 1) #меню улучшений self.upgradesMenu = Upgrades(0, 0, "gui/windowWide.png", self) create_player(self) #self.new_game() self.pause = True self.game_channel.pause() self.menu_music.play(-1) #вывод надписи с номером волны text = pygame.font.Font(self.mainFont, 100).render( self.texts[self.language]["WaveCaption"] + str(0), True, (150, 150, 0)) #изначальный self.waveCaption = Delay(text, 500) def menu_activation(self): pygame.mouse.set_pos([WINDOW_W // 2, BLOCK_SIZE * 3]) if not self.mainMenu.working: if self.pause: self.pause = False pygame.mouse.set_visible(False) #курсор скроется else: self.pause = True pygame.mouse.set_visible(True) if not self.upgradesMenu.working: self.menu.activate() else: self.upgradesMenu.activate() def mouse_move(self): #движение мыши с помощью джойстика x, y = pygame.mouse.get_pos() y += round(self.joystick.get_axis(1), 1) * 10 x += round(self.joystick.get_axis(0), 1) * 10 pygame.mouse.set_pos([x, y]) def keyboard(self, event): #клавиатура if event.type == pygame.KEYUP: if event.key == pygame.K_a: self.player.left = False if event.key == pygame.K_d: self.player.right = False if event.key == pygame.K_w: self.player.up = False #if event.key == pygame.K_s: #self.player.down = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: self.player.left = True if event.key == pygame.K_d: self.player.right = True if event.key == pygame.K_w: self.player.up = True #if event.key == pygame.K_s: #self.player.down = True if event.key == pygame.K_ESCAPE: #меню self.menu_activation() if event.key == pygame.K_x: #экстренный выход self.running = False if event.key == pygame.K_SPACE: #стрельба self.player.shoot() if event.key == pygame.K_h: #не для публичного использования! self.player.hp += 50 if event.key == pygame.K_p: #не для публичного использования! self.player.points += 50 def gamepad(self, event): #геймпад if event.type == pygame.JOYHATMOTION: #ходьба if self.joystick.get_hat(0)[0] == -1: self.player.left = True else: self.player.left = False if self.joystick.get_hat(0)[0] == 1: self.player.right = True else: self.player.right = False if event.type == pygame.JOYBUTTONDOWN: if self.joystick.get_button(9) == 1: #меню self.menu_activation() if self.joystick.get_button(0) == 1: #стрельба self.player.shoot() if self.joystick.get_button(6) == 1: #прыжок self.player.up = True if event.type == pygame.JOYBUTTONUP: if self.joystick.get_button(6) == 0: #прыжок self.player.up = False def on_event(self, event): #отслеживание событий self.keyboard(event) if self.joystick_count > 0: self.gamepad(event) if event.type == pygame.QUIT: self.running = False if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.JOYBUTTONDOWN: self.menu.down = True self.mainMenu.down = True self.upgradesMenu.down = True self.menu.up = False self.mainMenu.up = False self.upgradesMenu.up = False if event.type == pygame.MOUSEBUTTONUP or event.type == pygame.JOYBUTTONUP: self.menu.up = True self.mainMenu.up = True self.upgradesMenu.up = True self.menu.down = False self.mainMenu.down = False self.upgradesMenu.down = False else: self.menu.up = False self.mainMenu.up = False self.upgradesMenu.up = False if event.type == self.SONGEND: print("New song in queue") self.play_a_different_song(self.songs) def on_loop(self): #игровые вычисления в цикле if self.joystick_count > 0 and self.pause: self.mouse_move() if not self.stop and not self.pause: if self.story: triggers(self) self.gravity.force(self.gravity_ent) self.player.move(self.collide_ent, self.dt) for spikes in self.spikes: spikes.collide() for enemy in self.enemies: enemy.move(self.collide_ent, self.dt) try: enemy.spell.anim_hit_l.anim(self.dt) enemy.spell.anim_hit_r.anim(self.dt) except: pass if len(self.enemies) == 0: if not self.story: self.next_wave() elif self.level == 2 and self.waves > 0 and self.waves < 3: self.next_wave() elif self.level == 4 and self.waves > 0 and self.waves < 5: self.next_wave() if self.nextWave: if (self.waves == 6 and self.story) or (self.waves == 10 and not self.story): caption = self.texts[self.language]["BossWaveCaption"] else: caption = self.texts[self.language]["WaveCaption"] + str( self.waves) text = pygame.font.Font(self.mainFont, 100).render(caption, True, (150, 150, 0)) self.waveCaption = Delay(text, 1000) self.waveCaption.working = True self.nextWave = False for caption in self.dialog_windows: if caption.textOutput.working: caption.textOutput.anim(self.dt) elif caption.delay.working: caption.delay.update(self.dt) if self.waveCaption.working: self.waveCaption.update(self.dt) def on_render(self): #отрисовка объектов #self.draw_background() self.screen.fill((0, 20, 100)) for spikes in self.spikes: #шипы spikes.render(self.screen) for entity in self.collide_ent: #все объекты взаимодействия entity.render(self.screen) for entity in self.decor_ent_back: #объекты декора заднего плана entity.render(self.screen) self.player.render(self.screen) #игрок for enemy in self.enemies: #враги enemy.render(self.screen) for item in self.player.bullets: #пули item.render(self.screen) for entity in self.decor_ent_fore: #все объекты декора переднего плана entity.render(self.screen) subscreen = self.screen.subsurface(self.look.update()) for caption in self.dialog_windows: caption.render(subscreen) self.player.render_hp(subscreen) if self.stop: textw = self.textend.get_width() texth = self.textend.get_height() subscreen.blit( self.textend, (WINDOW_W // 2 - textw // 2, WINDOW_H // 2 - texth // 2)) if self.upgradesMenu.working: self.upgradesMenu.render(subscreen) self.player.render_points(subscreen) if self.waveCaption.working: text = pygame.font.Font(self.mainFont, 100).render( self.texts[self.language]["WaveCaption"] + str(self.waves), True, (255, 0, 0)) textw = text.get_width() texth = text.get_height() subscreen.blit( self.waveCaption.get_sprite(), (WINDOW_W // 2 - textw // 2, WINDOW_H // 2 - texth // 2)) if self.mainMenu.working: self.mainMenu.render(subscreen) if self.menu.working: self.menu.render(subscreen) self.credits(self.screen) self.window.blit(subscreen, (0, 0)) pygame.display.flip() def on_cleanup(self): #завершение работы программы pygame.quit() def draw_background(self): #отрисовка фона self.window.blit(self.screen, (0, 0)) def on_execute(self): #цикл работы приложения if self.on_init() == False: self.running = False while (self.running): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.dt = self.clock.tick(self.fps) self.on_cleanup()
def on_init(self): #инициализация игры pygame.init() self.init_gamepad() self.set_full_screen() pygame.display.set_caption('Dead riot') #строчка на панели управления pygame.display.set_icon( pygame.image.load("enemy/zombie/idle_r.png")) #иконка self.running = True self.map = "level1.txt" self.battle_music = pygame.mixer.Sound("music/battle_music.ogg") self.battle_music.set_volume(VOLUME) self.end_music = pygame.mixer.Sound("music/end_music.ogg") self.menu_music = pygame.mixer.Sound("music/menu_music.ogg") self.menu_music.set_volume(VOLUME) self.music1 = pygame.mixer.Sound("music/music1.ogg") self.music2 = pygame.mixer.Sound("music/music2.ogg") self.music3 = pygame.mixer.Sound("music/music3.ogg") self.music4 = pygame.mixer.Sound("music/music4.ogg") self.music1.set_volume(VOLUME) self.music2.set_volume(VOLUME / 3) self.music3.set_volume(VOLUME * 3) self.music4.set_volume(VOLUME) self.songs = [] self.songs.append(self.music1) self.songs.append(self.music2) self.songs.append(self.music3) self.songs.append(self.music4) self.currently_playing_song = None self.SONGEND = pygame.USEREVENT + 1 self.game_channel = pygame.mixer.Channel(0) self.game_channel.set_endevent(self.SONGEND) self.screen = pygame.Surface(self.s_size) self.subscreen = pygame.Surface(self.w_size) self.gravity = Gravity(0.1) #главное меню self.mainMenu = MainMenu(0, 0, "gui/back.png", self) self.mainMenu.activate() #self.create_map(self.map) initAnims(self) #меню self.menu = SideMenu(0, 0, "gui/window.png", self) #вывод диалогового окна print(self.texts[self.language]["Msg1.1"]) self.msg11 = DialogWindow(self.texts[self.language]["Msg1.1"], self, 1) self.msg12 = DialogWindow(self.texts[self.language]["Msg1.2"], self, 1) self.msg13 = DialogWindow(self.texts[self.language]["Msg1.3"], self, 1) self.msg14 = DialogWindow(self.texts[self.language]["Msg1.4"], self, 1) self.msg21 = DialogWindow(self.texts[self.language]["Msg2.1"], self, 1) self.msg22 = DialogWindow(self.texts[self.language]["Msg2.2"], self, 1) self.msg23 = DialogWindow(self.texts[self.language]["Msg2.3"], self, 1) self.msg31 = DialogWindow(self.texts[self.language]["Msg3.1"], self, 1) self.msg32 = DialogWindow(self.texts[self.language]["Msg3.2"], self, 1) self.msg33 = DialogWindow(self.texts[self.language]["Msg3.3"], self, 1) self.msg41 = DialogWindow(self.texts[self.language]["Msg4.1"], self, 1) self.msg42 = DialogWindow(self.texts[self.language]["Msg4.2"], self, 1) self.msg43 = DialogWindow(self.texts[self.language]["Msg4.3"], self, 1) self.msg44 = DialogWindow(self.texts[self.language]["Msg4.4"], self, 1) self.msg45 = DialogWindow(self.texts[self.language]["Msg4.5"], self, 1) ''' self.newmobvampire = DialogWindow("Beware of bloodsuckers... ", self, 1) self.newmobskeleton = DialogWindow("Bones are ringing... ", self, 1) self.newmobgolem = DialogWindow("Something big is coming... ", self, 1) ''' self.greeting = DialogWindow(self.texts[self.language]["MsgA1"], self, 1) self.newboss = DialogWindow(self.texts[self.language]["MsgA2"], self, 1) #меню улучшений self.upgradesMenu = Upgrades(0, 0, "gui/windowWide.png", self) create_player(self) #self.new_game() self.pause = True self.game_channel.pause() self.menu_music.play(-1) #вывод надписи с номером волны text = pygame.font.Font(self.mainFont, 100).render( self.texts[self.language]["WaveCaption"] + str(0), True, (150, 150, 0)) #изначальный self.waveCaption = Delay(text, 500)
def test__contains__(self): witnesses = Witnesses(gravity_instance=Gravity()) self.assertIn("init0", witnesses) self.assertIn("1.2.7", witnesses) self.assertIn("1.6.1", witnesses) self.assertNotIn("nathan", witnesses)
from gravity import Gravity data_path = '/Users/chrisbert/Documents/Projects/Dev_Gravity_processing/sample_data/DGS/OIB-P3_2017_F2001/' gravity_path = data_path + 'OIB-P3_20170322_F2001_DGS_100600.dat' trajectory_path = data_path + 'OIB-P3_20170322_F2001_DGS-INS_RAPID_For_Chris.txt' data = Gravity() print 'Importing gravity data.' data.import_DGS_format_data(gravity_path) print 'Importing trajectory data.' data.import_trajectory(trajectory_path, interval=.1) print 'Joining trajectory with gravity data.' data.join_grav_traj() begin_pre_static = '2017-03-22 10:27:00' end_pre_static = '2017-03-22 10:52:00' begin_post_static = '2017-03-22 19:06:00' end_post_static = '2017-03-22 19:49:00' data.set_pre_static_reading( data.compute_static(begin_pre_static, end_pre_static)) data.set_post_static_reading( data.compute_static(begin_post_static, end_post_static)) tie_reading = 982889.68 data.set_tie_reading(tie_reading) data.compute_corrections()
def new_func(ctx, *args, **kwargs): ctx.obj["offline"] = True ctx.gravity = Gravity(**ctx.obj) ctx.blockchain = ctx.gravity set_shared_gravity_instance(ctx.gravity) return ctx.invoke(f, *args, **kwargs)
class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grv = Gravity(nobroadcast=True, wif=[wif]) # from getpass import getpass # self.grv.wallet.unlock(getpass()) set_shared_gravity_instance(self.grv) self.grv.set_default_account("init0") def test_finalizeOps_proposal(self): grv = self.grv # proposal = grv.new_proposal(grv.tx()) proposal = grv.proposal() self.grv.transfer("init1", 1, "ZGV", append_to=proposal) tx = grv.tx().json() # default tx buffer ops = tx["operations"] self.assertEqual(len(ops), 1) self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create") prop = ops[0][1] self.assertEqual(len(prop["proposed_ops"]), 1) self.assertEqual( getOperationNameForId(prop["proposed_ops"][0]["op"][0]), "transfer") def test_finalizeOps_proposal2(self): grv = self.grv proposal = grv.new_proposal() # proposal = grv.proposal() self.grv.transfer("init1", 1, "ZGV", append_to=proposal) tx = grv.tx().json() # default tx buffer ops = tx["operations"] self.assertEqual(len(ops), 1) self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create") prop = ops[0][1] self.assertEqual(len(prop["proposed_ops"]), 1) self.assertEqual( getOperationNameForId(prop["proposed_ops"][0]["op"][0]), "transfer") def test_finalizeOps_combined_proposal(self): grv = self.grv parent = grv.new_tx() proposal = grv.new_proposal(parent) self.grv.transfer("init1", 1, "ZGV", append_to=proposal) self.grv.transfer("init1", 1, "ZGV", append_to=parent) tx = parent.json() ops = tx["operations"] self.assertEqual(len(ops), 2) self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create") self.assertEqual(getOperationNameForId(ops[1][0]), "transfer") prop = ops[0][1] self.assertEqual(len(prop["proposed_ops"]), 1) self.assertEqual( getOperationNameForId(prop["proposed_ops"][0]["op"][0]), "transfer") def test_finalizeOps_changeproposer_new(self): grv = self.grv proposal = grv.proposal(proposer="init5") grv.transfer("init1", 1, "ZGV", append_to=proposal) tx = grv.tx().json() ops = tx["operations"] self.assertEqual(len(ops), 1) self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create") prop = ops[0][1] self.assertEqual(len(prop["proposed_ops"]), 1) self.assertEqual(prop["fee_paying_account"], "1.2.12") self.assertEqual( getOperationNameForId(prop["proposed_ops"][0]["op"][0]), "transfer") def test_finalizeOps_changeproposer_legacy(self): grv = self.grv grv.proposer = "init5" tx = grv.transfer("init1", 1, "ZGV") ops = tx["operations"] self.assertEqual(len(ops), 1) self.assertEqual(getOperationNameForId(ops[0][0]), "proposal_create") prop = ops[0][1] self.assertEqual(len(prop["proposed_ops"]), 1) self.assertEqual(prop["fee_paying_account"], "1.2.12") self.assertEqual( getOperationNameForId(prop["proposed_ops"][0]["op"][0]), "transfer") def test_new_proposals(self): grv = self.grv p1 = grv.new_proposal() p2 = grv.new_proposal() self.assertIsNotNone(id(p1), id(p2)) def test_new_txs(self): grv = self.grv p1 = grv.new_tx() p2 = grv.new_tx() self.assertIsNotNone(id(p1), id(p2))
class Mario(Sprite): SPEED_CAP = 4 # Prevents extreme speed ACCEL_FACTOR = 0.025 DECEL_FACTOR = 0.25 FALL_FACTOR = 0.20 TURN_FACTOR = 0.3 def __init__(self, screen, settings, gamemap): super(Mario, self).__init__() self.screen = screen self.screen_rect = self.screen.get_rect() self.settings = settings self.gravity = Gravity() self.gamemap = gamemap self.image = pygame.image.load("media/images/mario/standing.png") self.image = pygame.transform.scale(self.image, (35, 50)) self.rect = self.image.get_rect() self.dist = 0 self.speed = 0 self.dir = 1 # -1 = moving left, 0 = standing still, 1 = moving right self.moving_right = False self.moving_left = False self.jumping = False self.jump_finished = False self.jump_speed = 0 self.jump_start = False self.last_img_update = pygame.time.get_ticks() self.last_img_mode = 1 def __str__(self): return 'Mario: x:' + str(self.rect.x) + ' y:' + str(self.rect.y) def update(self, gamemap, stats): # Update and then blit if self.rect.top > self.screen_rect.bottom + 80: # Has Mario fallen offscreen? stats.decrement_lives() self.settings.game_active = False self.settings.game_status = "Reset" return if not self.jumping and not gamemap.object_touching_ground(self): self.gravity.perform(self) if self.jumping: if gamemap.object_touching_ground(self): audio.play(0) self.jump() elif self.jumping and gamemap.object_touching_ground(self): self.jump() elif self.gamemap.object_touching_ground: self.jump_start = False self.jump_speed = 0 if self.moving_left: if self.dir == 1 and self.speed != 0: self.turn() elif self.dir == 0: self.dir = -1 self.accelerate() if self.rect.x > 0: self.rect.x += self.dir * self.speed elif self.moving_right: if self.dir == -1 and self.speed != 0: self.turn() elif self.dir == 0: self.dir = 1 self.accelerate() if self.rect.centerx >= self.screen_rect.width / 2: self.gamemap.scroll(self.speed) else: self.rect.x += self.dir * self.speed else: self.decelerate() if self.rect.x > 0 and self.rect.right < self.screen_rect.width: self.rect.x += self.dir * self.speed if self.rect.centerx >= self.screen_rect.width / 2: self.gamemap.scroll(self.speed) self.rect.y -= self.jump_speed self.gamemap.collide(self) self.animate() self.blitme() def animate(self): if pygame.time.get_ticks() - self.last_img_update >= 50: if self.jumping: img_string = "media/images/mario/jumping_1.png" self.image = pygame.image.load(img_string) self.image = pygame.transform.scale(self.image, (35, 50)) if self.dir == -1: self.image = pygame.transform.flip(self.image, 1, 0) elif self.moving_right or self.moving_left: if self.gamemap.object_touching_ground: img_string = "media/images/mario/walking_" + str( self.last_img_mode) + ".png" self.image = pygame.image.load(img_string) self.image = pygame.transform.scale(self.image, (35, 50)) if self.dir == -1: self.image = pygame.transform.flip(self.image, 1, 0) else: img_string = "media/images/mario/standing.png" self.image = pygame.image.load(img_string) self.image = pygame.transform.scale(self.image, (35, 50)) if self.dir == -1: self.image = pygame.transform.flip(self.image, 1, 0) if self.last_img_mode == 4: self.last_img_mode = 1 else: self.last_img_mode += 1 self.last_img_update = pygame.time.get_ticks() def accelerate(self): if self.speed == 0: self.speed = 2 + Mario.ACCEL_FACTOR if self.speed < Mario.SPEED_CAP: self.speed *= 1 + Mario.ACCEL_FACTOR def decelerate(self): if self.speed >= Mario.ACCEL_FACTOR: self.speed -= Mario.DECEL_FACTOR else: self.speed = 0 self.dir = 0 def turn(self): if self.speed >= Mario.ACCEL_FACTOR: self.speed -= Mario.TURN_FACTOR else: self.speed = 0 self.dir *= -1 def jump(self): if not self.jump_finished: self.jump_start = True if self.jump_speed <= 0: self.jump_speed = 7 else: self.jump_speed -= Mario.FALL_FACTOR if self.jump_speed <= 0: self.jump_finished = True elif self.gamemap.object_touching_ground(self): self.jump_finished = True else: self.jump_speed -= Mario.FALL_FACTOR if self.gamemap.object_touching_ground(self): self.jump_finished = False self.jump_start = False def blitme(self): # Blit Mario self.screen.blit(self.image, self.rect)