def isPathToGoal(self, path, startPos, goalPos): aPlayer = Player(startPos) for direction in path: aPlayer.move(direction) print(aPlayer.pos, goalPos) if (aPlayer.pos == goalPos): return True # print(aPlayer.pos,goalPos) return False
def __init__(self): self.pai = [] self.create() self.user = Player() self.quan = 0 self.oya = -1 self.xun = 0 self.benchang = 0 self.lizhibang = 0 self.setTag = 0
def start_game(): game = Game() # start game and initialize all players player = Player("You", game) game.players.append(player) for i in range(1, 4): new_name = NAMES.pop() game.players.append(ComputerPlayer(new_name, game, i)) while game.play_hand(): # continues until one player remains pass draw_final_screen() # allow players to quit or start new game
def configure_players(game): robot_names = [ "Eric (BOT)", "Jordan (BOT)", "Sam (BOT)", "Craig (BOT)", "Ryan (BOT)", "Adam (BOT)", "Nate (BOT)", "Conor (BOT)", "Nina (BOT)", "Hayley (BOT)", "Shelsea (BOT)", "Ben (BOT)", "Josh (BOT)", "Jimmy (BOT)" ] picked_names = [] while len(picked_names) < 3: i = randint(0, len(robot_names) - 1) if robot_names[i] not in picked_names: picked_names.append(robot_names[i]) starting_cash = 5000.00 player = Player("You", starting_cash, []) bot1 = Robot(picked_names[0], starting_cash, []) bot2 = Robot(picked_names[1], starting_cash, []) bot3 = Robot(picked_names[2], starting_cash, []) player.get_hand(game.deck.cards) bot1.get_hand(game.deck.cards) bot2.get_hand(game.deck.cards) bot3.get_hand(game.deck.cards) return [player, bot1, bot2, bot3]
def loadBoardData(self): for rIdx, r in enumerate(self.grid): for cIdx, c in enumerate(r): pos = (rIdx, cIdx) if (c == 'w' or c == 'W'): self.weapon = pos elif (c == 'p' or c == 'P'): self.player = Player(pos) elif (c == 'm' or c == 'M'): self.monsters.append(pos) elif (c == 'o' or c == 'O'): self.obstacles.append(pos) if (not self.player): raise Exception('board must have a player') if (not self.weapon): raise Exception('board must have a weapon') if (len(self.obstacles) == 0): raise Exception('board must have obstacles') if (len(self.monsters) == 0): raise Exception('board must have monsters') print('board loaded to game')
def AssignRole(self, is_lack): # 役欠けありなら割り当て対象にGMを選択 if is_lack: self.players.append( Player("GM", 1000) ) shuffled = random.shuffle(self.players) for i in range(len(self.players)): role_tag = self.rule.AssignRole(i) # 役職が見つからないなら、エラーを出して終了 if role_tag == None: return False self.players[i].setRole(role_tag) return True
def two_player(target=4000): p1 = Player("Player 1") p2 = Player("Player 2") p1.new_game() p2.new_game() turn = 0 ## player 1's turn while p1.score < target and p2.score < target: if turn == 0: player_turn(p1, target) turn = 1 else: player_turn(p2, target) turn = 0 if p1.score > p2.score: winner = p1 else: winner = p2 print("{name} is the winner!".format(name=winner.name))
def deal_card(self, player: Player, amount: int = 5): for i in range(amount): card_to_pass = self.cards.pop() player.set_card_in_hand(card_to_pass)
from Game import Game, Player from Tracker import Tracker game = Game(tracker=Tracker(), debug=True) game.add_player(Player("Austin", debug=True)) game.add_player(Player("Alex", debug=True)) game.add_player(Player("Mom", debug=True)) game.add_player(Player("Dad", debug=True)) game.play()
def perform_response(self, tvars={}): game = None # Main page = consent page if not self.path or self.path == "/" or self.path.startswith( "/consent") or self.path.startswith("/?"): self.send_text("html/consent.html") return if self.path.startswith("/tutorial"): self.send_text("html/tutorial.html") return if self.path.startswith("/pandemic"): self.send_text("html/pandemic.html") return if (self.path.startswith("/build/") or self.path.startswith("/images/")) and ".." not in self.path: fname = self.path[1:] if os.path.exists(fname) and os.path.isfile(fname): f = open(fname, "rb") self.send_response(200) self.end_headers() shutil.copyfileobj(f, self.wfile) f.close() else: self.send_response(404) self.end_headers() self.wfile.write("Not found".encode("utf8")) return if self.path.startswith("/newgame") or self.path.startswith( "/renewgame"): self.ok("text/json") gamelock.acquire() pid = self.getgid() if self.path.startswith( "/newgame") else self.path[10:] gorder = participants[pid][0] + 1 if pid in participants else 0 ai = random.choice(computers) role = random.choice(roles) seed = random.choice(seeds) random.shuffle(role) participants[pid] = [ gorder, ai.__name__, str(seed), role[0].name, role[1].name ] gid = self.getgid() game = ServerGame(gid, [Player(), ai()]) games[gid] = game gamelock.release() game.setup(seed=seed, players_roles=role) game.game_advance() game_state = game() game_state.update({"gid": gid, "pid": pid}) game_state["game_log"] = game_state["game_log"][ game_state["game_log"].index("Setting game up"):] game_state = json.dumps(game_state, indent="\t").split('\n') for line in game_state: self.writestring(line) return if self.path.startswith("/game"): gid = self.path[5:self.path.find('?')] gamelock.acquire() if gid in games: game = games[gid] else: print("Game not found, gid: " + gid) gamelock.release() self.send_response(400) self.send_header("Content-type", "text/html") self.end_headers() self.writestring("Error") return gamelock.release() game.ping = time.time() path = self.path[self.path.find('?') + 1:] get_dictionary = { get[:get.find("=")]: get[get.find("=") + 1:] for get in path.split("&") } pid = get_dictionary['pid'] del get_dictionary['pid'] # Transforms specific parameters to int's or array where needed if 'receiver' in get_dictionary.keys(): get_dictionary['receiver'] = int(get_dictionary['receiver']) if 'giver' in get_dictionary.keys(): get_dictionary['giver'] = int(get_dictionary['giver']) if 'player' in get_dictionary.keys(): get_dictionary['player'] = int(get_dictionary['player']) if 'target_player' in get_dictionary.keys(): get_dictionary['target_player'] = int( get_dictionary['target_player']) if 'chosen_cards' in get_dictionary.keys(): get_dictionary['chosen_cards'] = get_dictionary[ 'chosen_cards'].split('-') # Extracts action and acts accordingly action = get_dictionary['action'] del get_dictionary['action'] if game.current_player == 0: # Player must discard if action == 'discard' and game.turn_phase == TurnPhase.DISCARD: game.do_discard(**get_dictionary) # Player must perform action elif game.turn_phase == TurnPhase.ACTIONS: game.do_action(action, get_dictionary) game.game_advance() # Player receives update up to after infection phase, must request "waiting" for AI to execute else: while game.current_player != 0 and game.turn_phase == TurnPhase.ACTIONS: action, kwargs = game.players[ game.current_player].request_action(game) game.do_action(action, kwargs) game.game_advance() while game.current_player != 0 and game.turn_phase == TurnPhase.DISCARD: discard = game.players[ game.current_player].request_discard(game) game.do_discard(discard) game.game_advance() self.ok("text/json") game_state = json.dumps(game(), indent='\t').split('\n') for line in game_state: self.writestring(line) if game.game_state == GameState.LOST or game.game_state == GameState.WON: # Saves game results to game_results.log gameresults.write(",".join([ gid, pid, str(time.time() - game.time_init), game.game_state.name, str(game.current_turn), str(sum(list(game.cures.values()))), str(sum(list(game.eradicated.values()))), str(game.player_deck.remaining), str(game.outbreak_counter), *[ str(game.remaining_disease_cubes[color]) for color in ['red', 'yellow', 'blue', 'black'] ], *[str(param) for param in participants[pid]] ]) + "\n") gameresults.flush() game.close_game(save=True) gamelock.acquire() del games[gid] finished_games.append(gid) gamelock.release() return if self.path.startswith("/reqsurvey"): self.ok("text/json") for line in json.dumps(questionnaire, indent='\t').split('\n'): self.writestring(line) return if self.path.startswith("/survey"): gid = self.path[7:self.path.find('?')] gamelock.acquire() valid = gid in finished_games if valid: finished_games.remove(gid) else: print("Finished game not found, gid: " + gid) gamelock.release() self.send_response(400) self.send_header("Content-type", "text/html") self.end_headers() self.writestring("Error") return gamelock.release() path = self.path[self.path.find('?') + 1:] get_dictionary = { get[:get.find("=")]: get[get.find("=") + 1:] for get in path.split("&") } pid = get_dictionary['pid'] del get_dictionary['pid'] answers = [ '-1' for q in range( sum( len(questionnaire[section]['questions']) for section in questionnaire)) ] for key in get_dictionary: answers[int(key[1:])] = get_dictionary[key] gamesurvey.write(','.join([gid, pid] + answers) + '\n') gamesurvey.flush() self.ok() self.writestring("Thanks!") return self.send_response(400) self.send_header("Content-type", "text/html") self.end_headers()
class Dungeon: def __init__(self, board=None): pygame.init() self.window = pygame.display.set_mode((WIDTH, HEIGHT)) self.font = pygame.font.SysFont('arial', int(cell_size // 2)) self.running = True print('loading board!!') self.selected = None self.mouse_pos = None self.number = None self.finished = False self.obstacles = [] self.monsters = [] self.weapon = None self.player = None if (not board): self.state = 'building' self.grid = [['E' for _ in range(COLS)] for _ in range(ROWS)] else: self.state = 'playing' self.grid = board self.loadBoardData() print("done loading, let's play!") print(self.player) # main functions def start_new_game(self, board=None): self.running = True print('loading board!!') self.selected = None self.mouse_pos = None self.number = None self.finished = False self.obstacles = [] self.monsters = [] self.weapon = None self.player = None if (not board): self.state = 'building' self.grid = [['E' for _ in range(COLS)] for _ in range(ROWS)] else: self.state = 'playing' self.grid = board self.loadBoardData() def loadBoardData(self): for rIdx, r in enumerate(self.grid): for cIdx, c in enumerate(r): pos = (rIdx, cIdx) if (c == 'w' or c == 'W'): self.weapon = pos elif (c == 'p' or c == 'P'): self.player = Player(pos) elif (c == 'm' or c == 'M'): self.monsters.append(pos) elif (c == 'o' or c == 'O'): self.obstacles.append(pos) if (not self.player): raise Exception('board must have a player') if (not self.weapon): raise Exception('board must have a weapon') if (len(self.obstacles) == 0): raise Exception('board must have obstacles') if (len(self.monsters) == 0): raise Exception('board must have monsters') print('board loaded to game') def start_new_game(self, board=None): self.window = pygame.display.set_mode((WIDTH, HEIGHT)) self.running = True print('loading board!!') self.selected = None self.mouse_pos = None self.number = None self.finished = False if (not board): self.state = 'building' self.grid = [[0 for _ in range(COLS)] for _ in range(ROWS)] else: self.state = 'playing' self.grid = board self.loadBoardData() self.obstacles = [] self.monsters = [] self.weapon = None self.player = None #main loop of the game def run(self): while self.running: self.events(self.state) self.update(self.state) self.draw(self.state) pygame.quit() sys.exit() def build(self): while (self.state == 'building'): self.step() #1 step of the game for the Ai def step(self): self.events(self.state) self.update(self.state) self.draw(self.state) #main draw function def draw(self, state): self.window.fill(BLACK) if self.selected: self.drawSelection(self.window, self.selected) if (self.weapon): self.shadeCells(self.window, [self.weapon], DARK_YELLOW) if (self.player): self.shadeCells(self.window, [self.player.pos], DARK_GREEN) self.shadeCells(self.window, self.obstacles, DARK_GRAY) self.shadeCells(self.window, self.monsters, DARK_RED) self.drawGrid(self.window) self.textToScreen(self.window, self.state, (WIDTH // 2, 1), colour=WHITE) if (self.state == 'playing'): self.textToScreen(self.window, "health", (10, 20), colour=WHITE) pygame.draw.rect(self.window, RED, (15, 50, self.player.health, 5)) elif (self.state == 'won' or self.state == 'dead'): self.textToScreen(self.window, "press space to play again", (WIDTH // 2, 50), colour=WHITE) pygame.display.update() #updates the game with the mouse position def update(self, state): self.mouse_pos = pygame.mouse.get_pos() self.grid = [["E" for _ in range(ROWS)] for _ in range(COLS)] for pos in self.monsters: self.grid[pos[0]][pos[1]] = 'M' for pos in self.obstacles: self.grid[pos[0]][pos[1]] = 'O' if (self.player): pos = self.player.pos self.grid[pos[0]][pos[1]] = 'P' if (self.weapon): pos = self.weapon self.grid[pos[0]][pos[1]] = 'W' if (self.state == 'playing'): if (self.player.health <= 0): self.state = 'dead' #handles all kinds of ingame events def events(self, state): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False pygame.quit() sys.exit() if (self.state == 'playing'): self.handlePlayingEvents(event) elif (self.state == 'building'): self.handleBuildingEvents(event) elif (self.state == 'dead' or self.state == 'won'): self.handleGameOverEvents(event) #events helper Functions def handlePlayingEvents(self, event): if event.type == pygame.MOUSEBUTTONDOWN: selected = self.handleMouseSelection() if (selected): self.selected = selected else: self.selected = None if event.type == pygame.KEYDOWN: if (event.unicode == 'w' or event.unicode == 'W'): if (self.validPlayerMove(self.player.pos, 'up')): self.player.move('up') elif (event.unicode == 's' or event.unicode == 'S'): if (self.validPlayerMove(self.player.pos, 'down')): self.player.move('down') elif (event.unicode == 'a' or event.unicode == 'A'): if (self.validPlayerMove(self.player.pos, 'left')): self.player.move('left') elif (event.unicode == 'd' or event.unicode == 'd'): if (self.validPlayerMove(self.player.pos, 'right')): self.player.move('right') def handleBuildingEvents(self, event): if event.type == pygame.MOUSEBUTTONDOWN: selected = self.handleMouseSelection() if (selected): self.selected = selected else: self.selected = None elif event.type == pygame.KEYDOWN: if (self.selected): #obstacle handling if (event.unicode == 'o' or event.unicode == 'O'): if (self.selected in self.monsters): print( 'can\'t choose this point, remove the monster to add something here!' ) return if (self.player): if (self.player.pos == self.selected): print( 'can\'t choose this point, change the player pos to add something here!' ) return if (self.weapon): if (self.weapon == self.selected): print( 'can\'t choose this point, change the weapon pos to add something here!' ) return if (self.selected not in self.obstacles): print('added as obstacle') self.obstacles.append(self.selected) else: print('removed from obstacles') self.obstacles.remove(self.selected) #weapon handling if (event.unicode == 'w' or event.unicode == 'W'): if (self.selected in self.monsters): print( 'can\'t choose this point, remove the monster to add something here!' ) return if (self.selected in self.obstacles): print( 'can\'t choose this point, remove the obstacle to add something here!' ) return if (self.player): if (self.player.pos == self.selected): print( 'can\'t choose this point, change the player pos to add something here!' ) return if (not self.weapon): self.weapon = self.selected print('added weapon') else: if (self.weapon == self.selected): print('removed weapon') self.weapon = None else: print('changed weapon pos') self.weapon = self.selected #monster handling if (event.unicode == 'm' or event.unicode == 'M'): if (self.selected in self.obstacles): print( 'can\'t choose this point, remove the obstacle to add something here!' ) return if (self.player): if (self.player.pos == self.selected): print( 'can\'t choose this point, change the player pos to add something here!' ) return if (self.weapon): if (self.weapon == self.selected): print( 'can\'t choose this point, change the weapon pos to add something here!' ) return if (self.selected not in self.monsters): print('added as monster') self.monsters.append(self.selected) else: print('removed from monsters') self.monsters.remove(self.selected) #player handling if (event.unicode == 'p' or event.unicode == 'P'): if (self.selected in self.obstacles): print( 'can\'t choose this point, remove the obstacle to add something here!' ) return if (self.selected in self.monsters): print( 'can\'t choose this point, remove the monster to add something here!' ) return if (self.weapon): if (self.weapon == self.selected): print( 'can\'t choose this point, change the weapon pos to add something here!' ) return if (self.player): if (self.selected == self.player.pos): self.player = None print('removed player!') else: self.player = Player(self.selected) print('changed player pos!') else: self.player = Player(self.selected) #handling state change if (event.unicode == ' '): if (not self.player): print('please add a player to the field!') return if (not self.weapon): print('please add a weapon to the field') return if (len(self.monsters) == 0): print('please add at least one monster') return if (len(self.obstacles) == 0): print('please add at least one obstacle') return print('done building') self.state = 'playing' self.displayGrid() def handleGameOverEvents(self, event): if event.type == pygame.KEYDOWN: if (event.unicode == ' '): self.start_new_game() def handleMouseSelection(self): x_in_grid = grid_pos[0] < self.mouse_pos[0] < grid_pos[2] + grid_pos[0] y_in_grid = grid_pos[1] < self.mouse_pos[1] < grid_pos[3] + grid_pos[1] if (x_in_grid and y_in_grid): return ((self.mouse_pos[0] - grid_pos[0]) // cell_size, (self.mouse_pos[1] - grid_pos[1]) // cell_size) return False #player movement helper functions def validPlayerMove(self, position, direction): pos = [position[0], position[1]] if (direction == 'up'): pos[1] -= 1 elif (direction == 'down'): pos[1] += 1 elif (direction == 'left'): pos[0] -= 1 elif (direction == 'right'): pos[0] += 1 pos = (pos[0], pos[1]) if ((pos[0] < 0 or pos[0] >= len(self.grid)) or (pos[1] < 0 or pos[1] >= len(self.grid[0]))): # print('invalid move! out of bounds') return False if (pos in self.obstacles): # print('invalid move! obstacle here') self.player.health /= 2 # print('you lost health') if (self.player.health <= 1): self.player.health = 0 # print('you died') self.finished = True return False if (pos in self.monsters): if (self.player.hasWeapon): # print('nice you killed a monster!') self.monsters.remove(pos) if (len(self.monsters) == 0): # print('you killed all monsters you won the game!!') self.finished = True self.state = "won" return True else: # print('invalid move! monster here') self.player.health = 0 # print('you died') self.finished = True # self.running=False return False if (pos == self.weapon): # print('nice move! weapon here') self.player.health = 100 self.player.hasWeapon = True self.weapon = None return True #player movement helper functions def validMove(self, position, direction): pos = [position[0], position[1]] if (direction == 'up'): pos[1] -= 1 elif (direction == 'down'): pos[1] += 1 elif (direction == 'left'): pos[0] -= 1 elif (direction == 'right'): pos[0] += 1 pos = (pos[0], pos[1]) if ((pos[0] < 0 or pos[0] >= len(self.grid)) or (pos[1] < 0 or pos[1] >= len(self.grid[0]))): return False if (pos in self.obstacles): return False if (pos in self.monsters): if (self.player.hasWeapon): if (len(self.monsters) == 0): print('game won!') return True else: return False if (pos == self.weapon): return True return True #drawing helper functions #draws the sudoku grid def drawGrid(self, window): pygame.draw.rect(window, GRAY, grid_pos, 2) for c in range(COLS): start_x = grid_pos[0] + (c * cell_size) start_y = grid_pos[1] end_x = grid_pos[0] + (c * cell_size) end_y = grid_pos[1] + grid_pos[3] pygame.draw.line(window, GRAY, (start_x, start_y), (end_x, end_y), 2) for r in range(ROWS): start_x = grid_pos[0] start_y = grid_pos[1] + (r * cell_size) end_x = grid_pos[0] + grid_pos[2] end_y = grid_pos[1] + (r * cell_size) pygame.draw.line(window, GRAY, (start_x, start_y), (end_x, end_y), 2) #draws the blue box showing the selected cell def drawSelection(self, window, pos): margin = 3 pygame.draw.rect( window, BLUE, (pos[0] * cell_size + grid_pos[0], pos[1] * cell_size + grid_pos[1], cell_size + margin, cell_size + margin)) #adds the numbers inside their prober cells def drawNumbers(self, window): margin = 10 for rIdx, row in enumerate(self.grid): for cIdx, col in enumerate(row): if col != 0: self.textToScreen( window, str(col), (rIdx * cell_size + grid_pos[0] + margin, cIdx * cell_size + grid_pos[1] + margin)) #adds text to the GUI def textToScreen(self, window, text, pos, colour=WHITE): font = self.font.render(text, False, colour) window.blit(font, pos) #adds a shade to cells def shadeCells(self, window, cells, colour): margin = 3 for cell in cells: pygame.draw.rect( window, colour, (cell[0] * cell_size + grid_pos[0], cell[1] * cell_size + grid_pos[1], cell_size + margin, cell_size + margin)) #general helpers # proper printing function def displayGrid(self): for row in self.grid: for col in row: print(f"{col}, ", end='') print() def isPathToGoal(self, path, startPos, goalPos): aPlayer = Player(startPos) for direction in path: aPlayer.move(direction) print(aPlayer.pos, goalPos) if (aPlayer.pos == goalPos): return True # print(aPlayer.pos,goalPos) return False def getPosFromPath(self, path, startPos): aPlayer = Player(startPos) for direction in path: aPlayer.move(direction) return aPlayer.pos
except socket.error as e: print(e) exit(-1) finished = False message_from_server = client_socket.recv(5 * 1024).decode('utf-8') print(message_from_server) while True: response = input('>') client_socket.send(response.encode('utf-8')) message_from_server = client_socket.recv(5 * 1024).decode(('utf-8')) print(message_from_server) if message_from_server == 'You entered the game please wait...\n': break your_player = Player(response) while not finished: try: print(your_player) cprint('Please enter your next move: (Example: A5)\n', 'white', attrs=['bold']) move = input('>') y = move[0] if len(move) > 1 else ':(' x = move[1] + move[2] if len(move) > 2 else move[1] if len( move) == 2 else ':(' if y not in [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' ] or x not in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']: cprint('Please enter a valid option!\n', 'white',
def game_loop(): # Main game loop player = Player(player_img, Player.start_x, Player.start_y) Enemy.target_player = player # Clear all existing entities Platform.platforms.clear() Meatball.meatballs.clear() Coin.coins.clear() Enemy.enemies.clear() Upgrades.update_upgrades('data.json') Platform.create_plates(15, screen) camera = Camera() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pause() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: player.spawn_bullet() key = pygame.key.get_pressed() if key[pygame.K_a]: player.x_velocity = -player.walk_speed if key[pygame.K_d]: player.x_velocity = player.walk_speed if not key[pygame.K_d] and not key[pygame.K_a]: player.x_velocity = 0 if key[pygame.K_F4] and key[pygame.K_LALT]: running = False if key[pygame.K_SPACE]: player.jump() # UPDATE player.update_physics(screen) if player.hearts <= 0: highscores = read_data('data.json') if highscores['high'] < player.high: highscores['high'] = player.high dump_data('data.json', highscores) enter_score() main_menu() coins = read_data('data.json')['coins'] # DRAW screen.fill((47, 47, 47)) camera.draw_and_scroll(player, screen) score = score_font.render(f"SCORE: {str(player.high)}", True, (255, 255, 255)) coins = score_font.render(f"COINS: {coins}", True, (255, 255, 255)) player.draw_hearts(screen) screen.blit(score, (10, 5)) screen.blit(coins, (width - coins.get_width() - 200, 5)) pygame.display.flip() fpsClock.tick(fps) pygame.quit() sys.exit(0)
def makePopulation(size): population = [] for i in range(size): population.append(Player()) return population
def handleBuildingEvents(self, event): if event.type == pygame.MOUSEBUTTONDOWN: selected = self.handleMouseSelection() if (selected): self.selected = selected else: self.selected = None elif event.type == pygame.KEYDOWN: if (self.selected): #obstacle handling if (event.unicode == 'o' or event.unicode == 'O'): if (self.selected in self.monsters): print( 'can\'t choose this point, remove the monster to add something here!' ) return if (self.player): if (self.player.pos == self.selected): print( 'can\'t choose this point, change the player pos to add something here!' ) return if (self.weapon): if (self.weapon == self.selected): print( 'can\'t choose this point, change the weapon pos to add something here!' ) return if (self.selected not in self.obstacles): print('added as obstacle') self.obstacles.append(self.selected) else: print('removed from obstacles') self.obstacles.remove(self.selected) #weapon handling if (event.unicode == 'w' or event.unicode == 'W'): if (self.selected in self.monsters): print( 'can\'t choose this point, remove the monster to add something here!' ) return if (self.selected in self.obstacles): print( 'can\'t choose this point, remove the obstacle to add something here!' ) return if (self.player): if (self.player.pos == self.selected): print( 'can\'t choose this point, change the player pos to add something here!' ) return if (not self.weapon): self.weapon = self.selected print('added weapon') else: if (self.weapon == self.selected): print('removed weapon') self.weapon = None else: print('changed weapon pos') self.weapon = self.selected #monster handling if (event.unicode == 'm' or event.unicode == 'M'): if (self.selected in self.obstacles): print( 'can\'t choose this point, remove the obstacle to add something here!' ) return if (self.player): if (self.player.pos == self.selected): print( 'can\'t choose this point, change the player pos to add something here!' ) return if (self.weapon): if (self.weapon == self.selected): print( 'can\'t choose this point, change the weapon pos to add something here!' ) return if (self.selected not in self.monsters): print('added as monster') self.monsters.append(self.selected) else: print('removed from monsters') self.monsters.remove(self.selected) #player handling if (event.unicode == 'p' or event.unicode == 'P'): if (self.selected in self.obstacles): print( 'can\'t choose this point, remove the obstacle to add something here!' ) return if (self.selected in self.monsters): print( 'can\'t choose this point, remove the monster to add something here!' ) return if (self.weapon): if (self.weapon == self.selected): print( 'can\'t choose this point, change the weapon pos to add something here!' ) return if (self.player): if (self.selected == self.player.pos): self.player = None print('removed player!') else: self.player = Player(self.selected) print('changed player pos!') else: self.player = Player(self.selected) #handling state change if (event.unicode == ' '): if (not self.player): print('please add a player to the field!') return if (not self.weapon): print('please add a weapon to the field') return if (len(self.monsters) == 0): print('please add at least one monster') return if (len(self.obstacles) == 0): print('please add at least one obstacle') return print('done building') self.state = 'playing' self.displayGrid()
class MahjongGame(): def __init__(self): self.pai = [] self.create() self.user = Player() self.quan = 0 self.oya = -1 self.xun = 0 self.benchang = 0 self.lizhibang = 0 self.setTag = 0 def create(self): for i in range(4): for j in range(TILE_START + 1, TILE_START + TILE_RANGE): if j % 10 != 0: self.pai.append(j) for k in range(41, 48): self.pai.append(k) def newset(self): self.oya += 1 self.quan, self.oya = self.quan + self.oya // NUM_OF_SET_PER_QUAN, self.oya % NUM_OF_SET_PER_QUAN self.yama = self.pai[:] random.shuffle(self.yama) self.dora = [DORA_DEFAULT] self.ura = [] self.xun = 0 tmp = self.user.money self.user.__init__() self.user.money = tmp self.user.hand.in_hand, self.yama = self.yama[-13:], self.yama[:-13] self.user.hand.in_hand.sort() self.fu, self.yi, self.fan = [0, 0], [0, 0], [0, 0] self.dedian = 0 self.setTag = 0 def serve(self): self.user.lingshang = False if len(self.yama) == MIN_TILES_IN_YAMA or self.xun >= MAX_XUN: self.setTag = END_LIUJU return 0 else: self.user.hand.new_tile = self.yama.pop() self.xun = int(self.xun + 1) self.user.lingshang = False return self.user.hand.new_tile def gangserve(self): self.user.lingshang = True self.user.hand.new_tile, self.yama = self.yama[0], self.yama[1:] for i in range(len(self.dora)): self.dora[i] -= 1 self.user.gangTag = False ## Already moved to utility. # def nextpai(self, _pai): # # TODO: Lots of constants here. # # Currently I guess these are already readable. # m, n = _pai // 10, _pai % 10 # if m == 4: # if n == 4: # return 41 # elif n == 7: # return 45 # else: # return _pai + 1 # else: # return m * 10 + n % 9 + 1 # def gang(self, _pai, _gangpai): # tmp = self.user.hand.in_hand + [_pai] # + [_pai] # n = tmp.count(_gangpai) # if n < 4: # return False # else: # if len(self.yama) > MIN_TILES_IN_YAMA: # tmp.remove(_gangpai) # tmp.remove(_gangpai) # tmp.remove(_gangpai) # tmp.remove(_gangpai) # tmp.sort() # self.user.hand.in_hand = tmp # self.user.agang += [[_gangpai] * 4] # self.xun += 0.1 # # tmpdora = [x-1 for x in self.dora] # # self.dora = tmpdora[:] # return True # else: # return False def jiesuan(self, _pai): # TODO: dedian like 8000,12000 etc are readable. self.user.zimo = 1 self.fu, self.yi, self.fan = self.user.rong(_pai, self.quan, self.oya) if len(self.yama) == MIN_TILES_IN_YAMA: if self.user.zimo == 1: if u'岭上开花' not in self.fan[0]: self.yi[0] += 1 self.fan[0] += [u'海底捞月'] else: self.yi[0] += 1 self.fan[0] += [u'河底捞鱼'] if self.yi != [0, 0]: if self.yi[1] != 0: if self.user.position == self.oya: self.dedian = 48000 * self.yi[1] else: self.dedian = 32000 * self.yi[1] else: tmp = self.user.hand.in_hand + [self.user.rongpai] for gang in self.user.agang: tmp = tmp + gang for gang in self.user.mgang: tmp = tmp + gang if self.xun - self.user.riichi == 1 and self.user.riichi > 0: self.yi[0] += 1 self.fan[0] += [u'一發'] tmpk = 0 numdora = 0 for dora in self.dora: numdora += tmp.count(Util.nextpai(self.yama[dora])) self.ura.append(dora - 1) tmpk += 2 self.yi[0] += numdora if numdora != 0: self.fan[0] += ['Dora ' + str(numdora)] if self.user.riichi > 0: numura = 0 for ura in self.ura: numura += tmp.count(Util.nextpai(self.yama[ura])) self.yi[0] += numura if numura != 0: self.fan[0] += ['Ura ' + str(numura)] if self.fu[0] != 25: self.fu[0] = int(math.ceil(self.fu[0] / 10.) * 10) self.dedian = 0 self.jbd = self.fu[0] * 4 * pow(2, self.yi[0]) if self.yi[0] == 0: self.dedian = -8000 elif self.jbd < 2000: if self.user.position == self.oya: self.dedian = math.ceil(self.jbd * 6 / 100) * 100 else: self.dedian = math.ceil(self.jbd * 4 / 100) * 100 else: if self.yi[0] <= 5: self.dedian = 8000 elif self.yi[0] <= 7: self.dedian = 12000 elif self.yi[0] <= 10: self.dedian = 16000 elif self.yi[0] <= 12: self.dedian = 24000 elif self.yi[0] >= 13: self.dedian = 32000 if self.user.position == self.oya: self.dedian = self.dedian * 1.5 self.user.money += int(self.dedian) + self.lizhibang * 1000 self.lizhibang = 0 def setComplete(self): return self.setTag != 0 def menu_respond(self, button_pressed): if button_pressed == 'rong': self.menu_rong(self.user.hand.new_tile) elif button_pressed == 'riichi': self.menu_riichi() elif button_pressed == 'gang': self.menu_gang() elif button_pressed == 'analysis': self.menu_analysis() def tile_respond(self, tile_pressed): if self.user.riichi == WAIT_FOR_RIICHI_PAI: # This is a status of waiting for riichi droptmp = self.user.drop(tile_pressed) if droptmp: self.user.riichi = self.xun self.serve() elif self.user.gangTag == False: droptmp = self.user.drop(tile_pressed) if droptmp: self.serve() else: gangtmp = self.user.gang(tile_pressed) if gangtmp: self.gangserve() self.add_gang_dora() else: self.user.gangTag = False def add_gang_dora(self): self.dora.append(self.dora[-1]+2) def menu_rong(self, _pai): self.user.rongTag = True self.user.analysisTag = False self.setTag = END_RONG self.jiesuan(_pai) def menu_riichi(self): if self.user.riichi == 0: self.user.riichi = WAIT_FOR_RIICHI_PAI self.user.money -= 1000 self.lizhibang += 1 def menu_gang(self): if len(self.yama) > MIN_TILES_IN_YAMA: self.user.gangTag = True def menu_analysis(self): self.user.analysisTag = not self.user.analysisTag def menu_clear(self): self.user.rongTag = False self.user.gangTag = False def tagclear(self): self.user.rongTag = False self.user.gangTag = False
class Environment(): """ The main class that controls the entire game """ def __init__(self): self.entities = pygame.sprite.Group() self.walls = pygame.sprite.Group() self.enemies = pygame.sprite.Group() self.clock = pygame.time.Clock() self.fps = 30 self.running = False def load_images(self): """ loads all the image files """ # dont forget to convert them when you load them self.player_image = pygame.image.load( "IMAGES\\player.png").convert_alpha() self.bush_image = pygame.image.load( "IMAGES\\bush.png").convert_alpha() self.cursor_image = pygame.image.load( "IMAGES\\cursor.png").convert_alpha() self.wall_image = pygame.image.load( "IMAGES\\wall.png").convert_alpha() self.gem_image = pygame.image.load("IMAGES\\gem.png").convert_alpha() self.enemy_image = pygame.image.load( "IMAGES\\banenemy.png").convert_alpha() self.bullet_image = pygame.image.load( "IMAGES\\bullet.png").convert_alpha() self.gun_image = pygame.image.load("IMAGES\\gun.png").convert_alpha() self.exit_image = pygame.image.load("IMAGES\\door.png").convert() self.background_image = self.stitch( pygame.transform.scale( pygame.image.load("IMAGES\\background1.png").convert(), (32, 32)), self.level_width, self.level_height) self.water_image = pygame.Surface((32, 32)) self.water_image.fill((0, 64, 255)) def load_scene(self, file, clear=True): """ reads a text file with a level in it """ if clear: self.entities.empty() self.walls.empty() self.enemies.empty() x, y = 0, 0 with open(file) as f: for row in f: for col in row: if col in "1H": Wall([self.entities, self.walls], (x, y), self.wall_image) elif col in "2V": Wall([self.entities, self.walls], (x, y), self.wall_image, "vertical") elif col in "3B": Scenery([self.entities], (x, y), self.bush_image) elif col in "4W": Scenery([self.entities], (x, y), self.water_image) elif col in "5G": Item([self.entities], (x, y), self.gem_image, self.player.increase_gems) elif col in "6E": Enemy([self.enemies], (x, y), self.enemy_image) elif col in "7D": Item([self.entities], (x, y), self.exit_image, self.end_game, False) elif col in "8S": Item([self.entities], (x, y), self.gun_image, self.player.activate_weapon) x += 32 y += 32 x = 0 def get_scene_dimensions(self, file): with open(file) as f: lines = f.readlines() width = 32 * (len(lines[0]) - 1) # - 1 because of newline character height = 32 * len(lines) del lines return width, height def stitch(self, image, total_width, total_height): """ Repeats an image so it fills the whole screen """ total_width = max(800, total_width) total_height = max(600, total_height) x, y = 0, 0 *_, iwidth, iheight = image.get_rect() x_num = math.ceil(total_width / iwidth) y_num = math.ceil(total_height / iheight) background = pygame.Surface((total_width, total_height), pygame.SRCALPHA, 32) for i in range(y_num): for i2 in range(x_num): background.blit(image, (x, y)) x += iwidth y += iheight x = 0 return background def end_game(self, b=True, error=None): """ ends the game, exits the program, prints the results """ pygame.quit() self.running = False if b: print("Player XP: {}\nPlayer Level: {}\nPlayer Gems: {}".format( self.player.xp, self.player.level, self.player.gems)) if error: raise error sys.exit() def run(self, scene, title="game"): """ runs the game! """ pygame.init() self.running = True self.level_width, self.level_height = self.get_scene_dimensions(scene) self.window = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) self.camera = Camera(self.level_width, self.level_height, WIN_WIDTH, WIN_HEIGHT) pygame.display.set_caption(title) pygame.key.set_repeat(100, 50) pygame.mouse.set_visible(False) self.load_images() self.player = Player([], (100, 100), self.player_image) self.load_scene(scene) try: while self.running: mouse_pos = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False break elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False break elif event.key == pygame.K_UP: self.player.moving = True elif event.key == pygame.K_SPACE: self.player.shooting = True elif event.type == pygame.KEYUP: if event.key == pygame.K_UP: self.player.moving = False elif event.key == pygame.K_SPACE: self.player.shooting = False self.player.update(self.walls, self.camera.reverse(mouse_pos), self.enemies) self.enemies.update(self.walls, self.player) self.entities.update(self.player) self.camera.update(self.player) self.player.shoot(self.camera.reverse(mouse_pos), self.bullet_image) self.window.blit(self.background_image, self.camera.apply_pos((0, 0))) for spr in self.entities: self.window.blit(spr.image, self.camera.apply(spr)) for en in self.enemies: self.window.blit(en.image, self.camera.apply(en)) for bul in self.player.bullets: self.window.blit(bul.image, self.camera.apply(bul)) self.window.blit(self.player.image, self.camera.apply(self.player)) self.window.blit(self.cursor_image, (mouse_pos[0] - 5, mouse_pos[1] - 5)) pygame.display.flip() self.clock.tick(self.fps) except Exception as e: # this is to make sure the pygame window closes if there is an error # because otherwise the window stops responding and it's hard to close self.end_game(error=e) self.end_game()
def run(self, scene, title="game"): """ runs the game! """ pygame.init() self.running = True self.level_width, self.level_height = self.get_scene_dimensions(scene) self.window = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) self.camera = Camera(self.level_width, self.level_height, WIN_WIDTH, WIN_HEIGHT) pygame.display.set_caption(title) pygame.key.set_repeat(100, 50) pygame.mouse.set_visible(False) self.load_images() self.player = Player([], (100, 100), self.player_image) self.load_scene(scene) try: while self.running: mouse_pos = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False break elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False break elif event.key == pygame.K_UP: self.player.moving = True elif event.key == pygame.K_SPACE: self.player.shooting = True elif event.type == pygame.KEYUP: if event.key == pygame.K_UP: self.player.moving = False elif event.key == pygame.K_SPACE: self.player.shooting = False self.player.update(self.walls, self.camera.reverse(mouse_pos), self.enemies) self.enemies.update(self.walls, self.player) self.entities.update(self.player) self.camera.update(self.player) self.player.shoot(self.camera.reverse(mouse_pos), self.bullet_image) self.window.blit(self.background_image, self.camera.apply_pos((0, 0))) for spr in self.entities: self.window.blit(spr.image, self.camera.apply(spr)) for en in self.enemies: self.window.blit(en.image, self.camera.apply(en)) for bul in self.player.bullets: self.window.blit(bul.image, self.camera.apply(bul)) self.window.blit(self.player.image, self.camera.apply(self.player)) self.window.blit(self.cursor_image, (mouse_pos[0] - 5, mouse_pos[1] - 5)) pygame.display.flip() self.clock.tick(self.fps) except Exception as e: # this is to make sure the pygame window closes if there is an error # because otherwise the window stops responding and it's hard to close self.end_game(error=e) self.end_game()
from Game import Player, Draw, Helper from random import randint as r from Multi import Client from time import time from math import sqrt # Globals screen, clock, running = Helper.setup([1000, 500]) io = Client.createSocket() p, players, uid = Player.player([250, 250], color = [r(0, 255), r(0, 255), r(0, 255)], size = r(5, 30)), [], None sleep, lastUpdated = None, time() timeout, objects = 5, [] lastProj = 0 def tick(*args): global players, lastUpdated, objects lastUpdated = time() players = args[0]["players"] objects = args[0]["objects"] io.emit("tickReply", {"position": p.pos + [p.size, p.size], "color": p.col}) def setup(*args): global sleep, uid sleep = args[0]["sleep"] uid = args[0]["uid"] io.on("tick", tick) io.on("setup", setup) io.wait(1)
from Game import PeggingEngine from Game import Player from Game import PeggingView dealer = Player('John') player = Player('Jim') dealer.Hand = [1,2] player.Hand = [7,8,0] x = PeggingEngine(dealer, player) pview = PeggingView(x) x.Play()
def AddPlayer(self, member): self.players.append( Player(member, self.num_player) ) self.num_player += 1
def setUp(self): self.NUMBER_OF_DECKS = 4 self.admin = Admin.Admin(self.NUMBER_OF_DECKS) simpleLogic = Simple.SimplePlayer() self.player = Player.Player(simpleLogic, "Ethan")
def getPosFromPath(self, path, startPos): aPlayer = Player(startPos) for direction in path: aPlayer.move(direction) return aPlayer.pos
def test_player_construction(self): humanPlayer = Human.HumanPlayer() player = Player.Player(humanPlayer, "Ethan") self.assertEquals(player.name, "Ethan")
frontier_dic[new_state.id] = item if (cost + h)<minimum_found: minimum_found = cost + h if frontier and minimum_found <= (frontier[0][1]+frontier[0][2]): frontier.sort(key=lambda x: x[1] + x[2]) minimum_found = 9999999999 if frontier and not visited_goals and len(frontier[0][3])>len(default_path): _,_,_,default_path = frontier[0] # print("Expanded: %i Visited: %i Frontier: %i Total-t: %.2f" % (expanded_cnt,visited_cnt,len(frontier),time.time()-start_time)) return default_path,None,(visited_cnt,expanded_cnt,duplicated_cnt,improved_cnt) if __name__ == '__main__': from Game import Game, Player from Heuristics import Heuristic from Players import PlanningPlayer game = Game([Player(),Player()]) def goal_test_movement(state): return any([p.position=="karachi" for p in state.players]) def goal_test_curing(state): return all(state.cures.values()) tests = 10 total_time = 0 total_visited = 0 total_expanded = 0 total_duplicated = 0 total_improved = 0 for i in range(tests): game.setup(seed=1337*(i+1))