def input_loop(self): if self._ship: self.callRemote(PacketShipInput, id=self._ship.id, up=Game().keys[self._ship._input_up], down=Game().keys[self._ship._input_down], left=Game().keys[self._ship._input_left], right=Game().keys[self._ship._input_right], fire=Game().keys[self._ship._input_fire])
def main(screen: curses.window, height, width): game: Optional[Game] = None curses.curs_set(0) while True: display_string_builder: list[str, ...] = list() display_string_builder.append('###########################') display_string_builder.append('# WELCOME TO BATTLESHIP #') display_string_builder.append('###########################') display_string_builder.append('') if game and game.winner: display_string_builder.append( f'The winner of the last game is {game.winner}!') display_string_builder.append('') display_string_builder.append('Press n to start new game.') display_string_builder.append('Press l to load the game (if exists).') display_string_builder.append('Press q to quit the game.') screen.clear() check_text_size(display_string_builder, *screen.getmaxyx()) display_string = '\n'.join(display_string_builder) screen.addstr(0, 0, display_string) input_character = screen.getch() if input_character == ord('q'): return if input_character in (ord('n'), ord('l')): if input_character == ord('l'): try: with open(SAVE_FILE_NAME, 'rb') as file: game = pickle.load(file) except OSError: continue else: first_player = HumanPlayer('You') second_player = RandomPlayer('Robot') game = Game(first_player=first_player, second_player=second_player, board_size=(height, width)) try: game.play(screen) except QuitSignal as qs: if qs.signal_type == QuitSignal.BACK_TO_MAIN_MENU: continue if qs.signal_type == QuitSignal.QUIT: return if qs.signal_type == QuitSignal.QUIT_AND_SAVE: with open(SAVE_FILE_NAME, 'wb') as file: pickle.dump(game, file, pickle.HIGHEST_PROTOCOL) return
def sync(self): for client in self.clients: for ship in Game().ships: ship.update_network(client) for bullet in Game().bullets: bullet.update_network(client) for id in SyncedObject.destroyed_ids: client.callRemote(PacketDelete, id=id); SyncedObject.destroyed_ids = [] for ship in Game().ships: ship._dirty_creation = False for bullet in Game().bullets: bullet._dirty_creation = False
def packetdelete(self, id=None): print("Delete " + str(id)) try: obj = SyncedObject.objects[id] Game().ships = [ship for ship in Game().ships if ship != obj] Game().bullets = [ bullet for bullet in Game().bullets if bullet != obj ] del obj except KeyError as e: pass return {}
def main(): while True: os.system('cls' if os.name == 'nt' else 'clear') print(constants.TEXT_MENU) user_input = raw_input() if user_input not in ('1', '2', '3', 'q'): continue if user_input == 'q': break game = Game(int(user_input)) print game.main_loop() os.system('pause' if os.name == 'nt' else\ 'read -n1 -r -p "Nacisnij enter by kontynuowac..." key')
def packetship(self, id=None, color_r=None, color_g=None, color_b=None, position_x=None, position_y=None, velocity_x=None, velocity_y=None, rotation=None, angvelocity=None, isme=None): if id is not None and id not in SyncedObject.objects.keys(): ship = Ship(id=id, position=np.array([position_x, position_y]), color=(color_r, color_g, color_b), velocity=np.array([velocity_x, velocity_y]), rotation=rotation, angvelocity=angvelocity) if isme: self._ship = ship Game().ships.append(ship) ship.set_input(pyglet.window.key.UP, pyglet.window.key.DOWN, pyglet.window.key.LEFT, pyglet.window.key.RIGHT, pyglet.window.key.SPACE) return {}
def connectionLost(self, reason): playership = None playershipindex = 0 i = 0 for ship in Game().ships: if ship._client == self: playership = ship playershipindex = i + 0 i += 1 del Game().ships[playershipindex] del SyncedObject.objects[playership.id] self.sendMsg("- %s left." % self.name) print(t() + "- Connection lost: " + self.name) self.factory.clients.remove(self)
def _new_game(self): if (self._stack[-1].title.replace( ' ', '') == string.lowercase[:self._settings['types']]): self._stack.back() del self._game self._game = Game( self._settings, { 'n': Option('n', 'new game', self._new_game), 'm': Option('m', 'menu', self._stack.back), 'q': Option('q', 'quit', close) }, ['n', 'm', 'q']) self._stack.push(self._game.page)
def main(): bg_music.play(-1) game = Game() flag = game.render_menu() while flag: if game.start_game(): flag = game.render_menu() game = Game() else: flag = False
def packetplanet(self, id=None, image=None, radius=None, mass=None, position_x=None, position_y=None): # print("Packet Planet") Game().add_planet(id=id, image=image, radius=radius, mass=mass, position=np.array([position_x, position_y])) return {}
def packetbulletnew(self, id=None, color_r=None, color_g=None, color_b=None, position_x=None, position_y=None, velocity_x=None, velocity_y=None): # print("Packet Bullet. ID: " + str(id)) if id is not None: Game().add_bullet(id=id, position=np.array([position_x, position_y]), color=(color_r, color_g, color_b), velocity=np.array([velocity_x, velocity_y])) return {}
def connectionMade(self): # self.sendLine(b"Welcome to the server") self.factory.clients.append(self) self.callRemote(PacketGameSize, width=Game().width, height=Game().height) print(t() + "+ Connection from: " + self.transport.getPeer().host) for planet in Game().planets: planet.update_connected(self) for ship in Game().ships: ship.update_connected(self) for bullet in Game().bullets: bullet.update_connected(self) # Spawn Ship player = Ship(color=(random.randrange(100, 255), random.randrange(100, 255), random.randrange(100, 255))) player._client = self Game().ships.append(player) player.respawn(Game().random_spawn()) player.update_connected(self) player.set_input(pyglet.window.key.UP, pyglet.window.key.LEFT, pyglet.window.key.RIGHT, pyglet.window.key.DOWN, pyglet.window.key.SPACE)
def test_game(): game = Game('player_1', 'player_2') assert game.player_1 == 'player_1' assert game.player_2 == 'player_2'
def update(self): Game().dt = 1 / 60.0 Game().update(1 / 60.0)
def __init__(self): self.output = None self._ship = None Game()._server = self
def on_key_release(symbol, modifiers): for ship in Game().ships: ship.on_key_release(symbol, modifiers)
def update(dt): Game().dt = dt Game().update(dt)
def on_draw(): window.clear() Game().draw()
import time import random import pyglet from twisted.internet import reactor, protocol from source.game import Game from source.syncedobject import SyncedObject from source.ship import Ship Game().Client = False Game().Server = True Game().width = 1300 Game().height = 700 Game().generate() Game().keys = {} from source.packets import * def t(): return "[" + time.strftime("%H:%M:%S") + "] " class EchoProtocol(amp.AMP): name = "Unnamed" def connectionMade(self): # self.sendLine(b"Welcome to the server")
import source.pygletreactor as pygletreactor from source.syncedobject import SyncedObject pygletreactor.install( ) # Must be installed before importing reactor from twisted.internet from twisted.internet import reactor, task, protocol # Create a Pyglet window with a simple message window = pyglet.window.Window(fullscreen=False) # Set resource path pyglet.resource.path = ["resources"] pyglet.resource.reindex() # Establish to the game that this is the Client Game().Server = False Game().Client = True # Set the initial game size (will be resized on connection to server) Game().width = window.width Game().height = window.height # Input handling # TODO: Needs reworking Game.keys = pyglet.window.key.KeyStateHandler() window.push_handlers(Game.keys) keys = pyglet.window.key.KeyStateHandler() window.push_handlers(keys) # The main drawing loop of pyglet
def test_game(): x = Game(1) if x.screen is not None: assert True else: assert False
import tcod import tcod.event import argparse from source.game import Game if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("-d", "--debug", required=False, action='store_true') config = vars(ap.parse_args()) game = Game(config) game.generate_school() # Initialize the root console in a context. game.game_loop() # The libtcod window will be closed at the end of this with-block.
def on_key_press(symbol, modifiers): for ship in Game().ships: ship.on_key_press(symbol, modifiers)