def __init__(self,players: list[Player],ee, partieRecord: PartieRecord = None ): # self.nb_players = self.ask_nb_players() try: self.round = partieRecord.Tour self.IdPartie = partieRecord.IdPartie self.players = [] for score in partieRecord.scores: self.players.append(Player('',score)) except NameError or AttributeError: self.round = 1 self.players = players self.IdPartie = -1 self.players[0].in_activate() self.dataBase = BDD("yams") self.interface = Interface(self.players, ee) @ee.on("points scored") def next_turn(): self.next_player() @ee.on("save") def save(): self.saveGame()
class Round(): # Deck setup deck = Deck() deck.shuffle() # Dealer setup dealer = Player( 'Dealer', PLAYER_TYPES.get('computer'), ) def __init__(self, pot, player): self.pot = pot self.player = player print(len(self.deck)) self.player.init_hand(self.deck.draw_card(2)) self.dealer.init_hand(self.deck.draw_card(2)) def show_hand(self, showdown=False): """ Shows player and dealer hands """ print('YOUR CARDS:') self.player.show_hand() print(f'SCORE: {self.player.get_score()}') print() print('DEALER CARDS:') self.dealer.show_hand(showdown) if showdown: print(f'SCORE: {self.dealer.get_score()}') print() def check_bust_blackjack(self): """ Checks player's hand for blackjack or bust """ if self.player.status == 1: clear() self.player.bankroll.add_funds(self.pot) print('BLACKJACK!!! YOU WIN!!') print() print('YOUR CARDS:') self.player.show_hand(True) print(f'SCORE: {self.player.get_score()}') print() print(self.player.bankroll) input() return True if self.player.status == -1: clear() print('BUST!!! YOU LOST!!') print() print('YOUR CARDS:') self.player.show_hand(True) print(f'SCORE: {self.player.get_score()}') print() print(self.player.bankroll) input() return True return False def showdown(self): """ Shows final hands, scores and result (win/lose) """ clear() print('SHOWDOWN') self.show_hand(True) dealer_bust = self.dealer.get_score() > 21 dealer_lose = self.player.get_score() >= self.dealer.get_score() if dealer_bust or dealer_lose: self.player.bankroll.add_funds(self.pot) print('YOU WON!') else: print('YOU LOST!') print(self.player.bankroll) def player_round(self): """ Starts player round """ while True: self.player.check_status() if self.player.status != 0: break clear() self.show_hand() hit = input('Do you want another card? (YES/no)') if hit.upper() == 'NO': self.player.check_status() break self.player.add_card(self.deck.draw_card(1).pop()) def computer_round(self): """ Starts computer round """ while self.dealer.get_score() < 21: clear() self.show_hand(True) input('Press any key...') if self.dealer.get_score() > self.player.get_score(): break self.dealer.add_card(self.deck.draw_card(1).pop())
sys.setrecursionlimit(10000) Player.start_year = '2012-01-01' Player.end_year = '2012-12-31' Player.surface = 'hard' for y in ['2012','2013'] serv_bs = [] serv_bs_std = [] retn_bs = [] retn_bs_std = [] for p in top: player = Player(p) print p serv_bs.append(player.set_baseline_3['0:0'].serv_mean) serv_bs_std.append(player.set_baseline_3['0:0'].serv_std) retn_bs.append(player.set_baseline_3['0:0'].retn_mean) retn_bs_std.append(player.set_baseline_3['0:0'].retn_std) print top print serv_bs print serv_bs_std print retn_bs print retn_bs_std n = top_abbr z = serv_bs
import os import pickle from classes.player import Player __author__ = 'krptstc' if __name__ == '__main__': player = None if os.path.exists('data.pfsakana'): pickleInput = open('data.pfsakana', 'rb') loadedData = pickle.load(pickleInput) player = loadedData['player'] else: player = Player() from modules.functions import * from modules.menus import * home()
def set_player(self): self.player = Player("content/entity/man", self) self.player.set_pos(0, 0, 0) self.player.set_move_task() self.player.is_player = True
run_simulation(output, gamestate_copy, target) # ============================================================== # # SECTION: Main # # ============================================================== # if __name__ == "__main__": goal_units = ["zergling", "zergling", "zergling", "zergling"] max_ticks = 16 output = [] player = Player( Race.ZERG, minerals=50, gas=0, goal_units=goal_units, current_units=[], buildings=[], bases=[Base(12, Race.ZERG, "normal", "normal", 2, False, True)], build_order=[], supply=3, required_tech=get_all_required_tech(goal_units) + goal_units, remaining_ticks=max_ticks) gamestate = GameState(remaining_ticks=max_ticks, player=player) # store results in output simulation = run_simulation(output, gamestate, None) # print(simulation) # print(output) # print(len(output)) LOG.info(json.dumps(output))
def __init__(self): self._current_player = 0 self._players = [Player(0), Player(1)] self._board = Board() self._gameUI = GameUI(self._players[0])
from classes.card import Card from classes.deck import Deck from classes.player import Player player_one = Player("One") player_two = Player("Two") new_deck = Deck() new_deck.shuffle() for x in range(26): player_one.add_cards(new_deck.deal_one()) player_two.add_cards(new_deck.deal_one()) game_on = True round_number = 0 while game_on: round_number += 1 print(f"Round {round_number}") if len(player_one.all_cards) == 0: print("Player one, out of cards! Player two wins!") game_on = False break if len(player_two.all_cards) == 0: print("Player two, out of cards! Player one wins!") game_on = False
def main(): player1 = Player('Alice') player2 = Player('Bob') game = Game(generate.tiles(), [player1, player2]) game.start()
from classes.board import Board from classes.player import Player print("Welcome to Tic Tac Toe!") while True: theBoard = Board() player1 = Player() player2 = Player() player1.marker, player2.marker = Player.player_input() print('Player 1 choose ' + player1.marker + ', Player 2 choose ' + player2.marker) print(('Player 1' if theBoard.turn == 1 else 'Player 2') + ' will play first!') theBoard.game_state = input( 'Are you ready to play? Enter Yes or No: ').lower().startswith('y') while theBoard.game_state: if theBoard.turn == 1: theBoard.do_turn(player1) else: theBoard.do_turn(player2) if not input('Do you want to play again? Enter Yes or No: ').upper( ).startswith('Y'): break
def displayLevel(numLevel, window): """Display the level the player has selected """ print("Chargement du niveau " + str(numLevel)) loadLevel = True #While we need to reload the same level (for restart or a death for example) #We reload it while loadLevel == True: #String that will go back to main and let the program knows what to do next #Go to next level? Quit the game? action = "" #We create the object Level and load its elements level = Level(numLevel) #If it couldn't find a level in levelFile, it means the game is finished and #we display the title screen if level.csvPath is None: return "Title_Screen" else: level.loadingLevelForDisplay() #We calculate where should be the center of the game on the screen in order #to display correctly all elements gameWidth = len(level._get_grille()[0]) * 30 firstPixel = centerTheGameOnTheScreen(window.get_width(), gameWidth) #We set a new background image window.fill(pygame.Color("black")) background = pygame.image.load("resources/img/fond.jpg").convert() window.blit(background, (firstPixel, 0)) pygame.display.flip() #We place each element with their pixels position on the screen displayGrille(level, firstPixel, window) #We place the player on the table player = Player() playerPNG = pygame.image.load(player.character.skin).convert_alpha() player.positionRect = playerPNG.get_rect(x=level.start[0], y=level.start[1]) window.blit(playerPNG, (firstPixel + player.positionRect.x * 30, player.positionRect.y * 30)) pygame.display.flip() continuer = 1 #We display the level while the player hasn't finished it while continuer: #We display background and elements of the level again window.fill(pygame.Color("Black")) #We load the background image window.blit(background, (firstPixel, 0)) #We load the table of elements with their graphics displayGrille(level, firstPixel, window) #We load the player character (donkey kong) playerPNG = pygame.image.load( player.character.skin).convert_alpha() window.blit(playerPNG, (firstPixel + player.positionRect.x * 30, player.positionRect.y * 30)) #If the player walked on a scroll, we display its message level.checkPlayerOnScroll(player, window) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: action = "Quit_the_game" loadLevel = False continuer = 0 #If the player presses a key, we check if he can move elif event.type == KEYDOWN: if event.key == K_r: continuer = 0 elif event.key == K_LEFT or event.key == K_RIGHT or event.key == K_UP or event.key == K_DOWN: #If the player will move on a cell where there is a box potentialBox = level.checkPlayerBoxes(player, event) if potentialBox is not None: box = potentialBox if box.canMove(player, level, event): player.move(level, event) else: player.move(level, event) #If the player dies, he goes back to the starting point of the current level if level.checkPlayerDies(player): continuer = 0 #If player walks on the finish line, he goes to next level if level.checkEndLevel(player): continuer = 0 loadLevel = False action = "Next_level" return action
from classes.player import Player, bcolors from classes.weapon import Weapon from classes.spell import Spell from classes.item import Item pj1 = Player("Rhogar", 12, 45, 18, 16, 13, 14, 9, 7, 16) pj2 = Player("Berto", 30, 30, 12, 12, 10, 18, 10, 10, 10) sword = Weapon(6, "Sword", 1) healingSpell = Spell(12, 7, 5) fireball = Spell(6, 1, 12) advantager = Item(1, 'common', 1) advantager.use(pj1, pj2) def menu(): print("Acciones") print("1. Usar espada") print("2. Curar") print("3. Usar bola de fuego") print("Elije una acción:", end="") return input() while (pj1.hp > 0 and pj2.hp > 0): '''Turno jugador''' action = menu() print(action) if (int(action) == 1): if (pj1.hit(pj2.armor)): dmg = sword.attack() pj2.hp -= dmg
# if '1:1' in Player.cached_players[p].set_impact_3_ts.keys(): # serv.append(Player.cached_players[p].set_impact_3_ts['1:1'].serv_mean) # retn.append(Player.cached_players[p].set_impact_3_ts['1:1'].retn_mean) # print '1:1' # print serv # print retn # # print np.nanmean(serv) # print np.nanmean(retn) # # print np.nanstd(serv) # print np.nanstd(retn) # # Player('Andy Murray') Player('Novak Djokovic') Player.calculate_all_ts() for p in Player.cached_players: if -1 in Player.cached_players[p].game_baseline.keys(): if Player.cached_players[p].match_baseline.serv_counts > 10: if Player.cached_players[p].game_baseline[-1].serv_counts > 50: if Player.cached_players[ p].match_baseline.serv_mean < Player.cached_players[ p].game_baseline[-1].serv_mean: if Player.cached_players[ p].match_baseline.retn_mean < Player.cached_players[ p].game_baseline[-1].retn_mean: if Player.cached_players[
match_baseline_s = [] match_impact_s = [] set_baseline_s = [] set_impact_s = [] match_baseline_r = [] match_impact_r = [] set_baseline_r = [] set_impact_r = [] Player.end_year = '2012-12-31' Player.start_year = '2012-01-01' Player.clean_cached_players() p = Player(player) Player.calculate_all_ts() match_baseline_s.append(p.match_baseline_ts.serv_mean) match_impact_s.append(p.match_impact_ts.serv_mean) set_baseline_s.append(p.set_baseline_3_ts[set_level].serv_mean) set_impact_s.append(p.set_impact_3_ts[set_level].serv_mean) match_baseline_r.append(p.match_baseline_ts.retn_mean) match_impact_r.append(p.match_impact_ts.retn_mean) set_baseline_r.append(p.set_baseline_3_ts[set_level].retn_mean) set_impact_r.append(p.set_impact_3_ts[set_level].retn_mean) Player.end_year = '2013-12-31' Player.start_year = '2013-01-01' Player.clean_cached_players()
def test_tie_breaker(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) set_game = Set(player_one, player_two) self.assertEqual(set_game.tie_breaker(), False)
def castling_move(self, castling): # player turn var to check the turn player_turn = str if self.identifier % 2 == 0: player_turn = Player(0) else: player_turn = Player(1) move_validator = int # get the ori and destination square for white king (king side castling) ori_square_white_king = 'e1' destination_square_white_king = 'g1' # get the original index and destination index to update the board state in the txt file ori_white_king_index = self.get_file_index(ori_square_white_king) destination_white_king_index = self.get_file_index( destination_square_white_king) # get the ori and destination square for white king (queen side castling) destination_square_white_king_qs = 'c1' # get the original index and destination index to update the board state in the txt file (Queen Side) destination_white_king_index_qs = self.get_file_index( destination_square_white_king_qs) # get the ori and destination square for black king (king side) ori_square_black_king = 'e8' destination_square_black_king = 'g8' # get the original index and destination index to update the board state in the txt file ori_black_king_index = self.get_file_index(ori_square_black_king) destination_black_king_index = self.get_file_index( destination_square_black_king) # get the ori and destination square for black king (queen side) destination_square_black_king_qs = 'c8' # get the original index and destination index to update the board state in the txt file (Queen Side) destination_black_king_index_qs = self.get_file_index( destination_square_black_king_qs) # get the ori and destination square for white rook if we castle king side ori_square_white_rook_ks = 'h1' destination_square_white_rook_ks = 'f1' # get the original index and destination index to update the board state in the txt file ori_white_rook_ks_index = self.get_file_index(ori_square_white_rook_ks) destination_white_rook_ks_index = self.get_file_index( destination_square_white_rook_ks) # get the ori and destination square for white rook if we castle queen side ori_square_white_rook_qs = 'a1' destination_square_white_rook_qs = 'd1' # get the original index and destination index to update the board state in the txt file (Queen Side) ori_white_rook_qs_index = self.get_file_index(ori_square_white_rook_qs) destination_white_rook_qs_index = self.get_file_index( destination_square_white_rook_qs) # get the ori and destination square for black rook if we castle king side ori_square_black_rook_ks = 'h8' destination_square_black_rook_ks = 'f8' # get the original index and destination index to update the board state in the txt file ori_black_rook_ks_index = self.get_file_index(ori_square_black_rook_ks) destination_black_rook_ks_index = self.get_file_index( destination_square_black_rook_ks) # get the ori and destination square for black rook if we castle king side ori_square_black_rook_qs = 'a8' destination_square_black_rook_qs = 'd8' # get the original index and destination index to update the board state in the txt file ori_black_rook_qs_index = self.get_file_index(ori_square_black_rook_qs) destination_black_rook_qs_index = self.get_file_index( destination_square_black_rook_qs) # get white king piece in its ori square ori_white_king = self.get_piece(ori_square_white_king) # get black king piece in its ori square ori_black_king = self.get_piece(ori_square_black_king) # get white rook piece in its ori square on king side (ks) ori_white_rook_ks = self.get_piece(ori_square_white_rook_ks) # get white rook piece in its ori square on king side (qs) ori_white_rook_qs = self.get_piece(ori_square_white_rook_qs) # get black rook piece in its ori square on king side (ks) ori_black_rook_ks = self.get_piece(ori_square_black_rook_ks) # get black rook piece in its ori square on king side (qs) ori_black_rook_qs = self.get_piece(ori_square_black_rook_qs) # get the original matrix x and y of white king for the 2d list in order to move the pieces axis_x_ori_white_king = ord(ori_square_white_king[0]) - 97 axis_y_ori_white_king = 8 - int(ori_square_white_king[1]) # get the original matrix x and y of black king for the 2d list in order to move the pieces axis_x_ori_black_king = ord(ori_square_black_king[0]) - 97 axis_y_ori_black_king = 8 - int(ori_square_black_king[1]) # get the original matrix x and y of white rook for the 2d list in order to move the pieces axis_x_ori_white_rook_ks = ord(ori_square_white_rook_ks[0]) - 97 axis_y_ori_white_rook_ks = 8 - int(ori_square_white_rook_ks[1]) # get the original matrix x and y of white rook for the 2d list in order to move the pieces (Queen Side) axis_x_ori_white_rook_qs = ord(ori_square_white_rook_qs[0]) - 97 axis_y_ori_white_rook_qs = 8 - int(ori_square_white_rook_qs[1]) # get the original matrix x and y of black rook for the 2d list in order to move the pieces axis_x_ori_black_rook_ks = ord(ori_square_black_rook_ks[0]) - 97 axis_y_ori_black_rook_ks = 8 - int(ori_square_black_rook_ks[1]) # get the original matrix x and y of black rook for the 2d list in order to move the pieces (Queen Side) axis_x_ori_black_rook_qs = ord(ori_square_black_rook_qs[0]) - 97 axis_y_ori_black_rook_qs = 8 - int(ori_square_black_rook_qs[1]) # get the destination matrix x and y of white king for the 2d list in order to move the pieces axis_x_destination_white_king = ord( destination_square_white_king[0]) - 97 axis_y_destination_white_king = 8 - int( destination_square_white_king[1]) # get the destination matrix x and y of white king for the 2d list in order to move the pieces (Queen Side) axis_x_destination_white_king_qs = ord( destination_square_white_king_qs[0]) - 97 axis_y_destination_white_king_qs = 8 - int( destination_square_white_king_qs[1]) # get the destination matrix x and y of black king for the 2d list in order to move the pieces axis_x_destination_black_king = ord( destination_square_black_king[0]) - 97 axis_y_destination_black_king = 8 - int( destination_square_black_king[1]) # get the destination matrix x and y of black king for the 2d list in order to move the pieces (Queen Side) axis_x_destination_black_king_qs = ord( destination_square_black_king_qs[0]) - 97 axis_y_destination_black_king_qs = 8 - int( destination_square_black_king_qs[1]) # get the destination matrix x and y for the 2d list in order to move the pieces axis_x_destination_white_rook_ks = ord( destination_square_white_rook_ks[0]) - 97 axis_y_destination_white_rook_ks = 8 - int( destination_square_white_rook_ks[1]) # get the destination matrix x and y for the 2d list in order to move the pieces (Queen Side) axis_x_destination_white_rook_qs = ord( destination_square_white_rook_qs[0]) - 97 axis_y_destination_white_rook_qs = 8 - int( destination_square_white_rook_qs[1]) # get the destination matrix x and y for the 2d list in order to move the pieces axis_x_destination_black_rook_ks = ord( destination_square_black_rook_ks[0]) - 97 axis_y_destination_black_rook_ks = 8 - int( destination_square_black_rook_ks[1]) # get the destination matrix x and y for the 2d list in order to move the pieces (Queen Side) axis_x_destination_black_rook_qs = ord( destination_square_black_rook_qs[0]) - 97 axis_y_destination_black_rook_qs = 8 - int( destination_square_black_rook_qs[1]) # Castling on King Side if castling.upper() == 'O-O': if str(player_turn) == 'white' and self.castle_white_king_side(): # move the king self.chess_board[axis_y_destination_white_king][ axis_x_destination_white_king] = str(ori_white_king) self.chess_board[axis_y_ori_white_king][ axis_x_ori_white_king] = '.' # move the rook on king side self.chess_board[axis_y_destination_white_rook_ks][ axis_x_destination_white_rook_ks] = str(ori_white_rook_ks) self.chess_board[axis_y_ori_white_rook_ks][ axis_x_ori_white_rook_ks] = '.' # update king move in txt file self.update_board_file(ori_white_king_index, destination_white_king_index) # update rook move in txt file self.update_board_file(ori_white_rook_ks_index, destination_white_rook_ks_index) print('-- Valid Move --') print(f'{player_turn} just castled!') move_validator = self.player_turn(0) elif str(player_turn) == 'black' and self.castle_black_king_side(): # move the king self.chess_board[axis_y_destination_black_king][ axis_x_destination_black_king] = str(ori_black_king) self.chess_board[axis_y_ori_black_king][ axis_x_ori_black_king] = '.' # move the rook on king side self.chess_board[axis_y_destination_black_rook_ks][ axis_x_destination_black_rook_ks] = str(ori_black_rook_ks) self.chess_board[axis_y_ori_black_rook_ks][ axis_x_ori_black_rook_ks] = '.' # update king move in txt file self.update_board_file(ori_black_king_index, destination_black_king_index) # update rook move in txt file self.update_board_file(ori_black_rook_ks_index, destination_black_rook_ks_index) print('-- Valid Move --') print(f'{player_turn} just castled!') move_validator = self.player_turn(0) else: print('-- Invalid Move --') print('Cannot castle if there is pieces between rook and king') move_validator = self.player_turn(-1) # Castling on Queen Side elif castling.upper() == 'O-O-O': if str(player_turn) == 'white' and self.castle_white_queen_side(): self.chess_board[axis_y_destination_white_king_qs][ axis_x_destination_white_king_qs] = str(ori_white_king) self.chess_board[axis_y_ori_white_king][ axis_x_ori_white_king] = '.' # move the rook on king side self.chess_board[axis_y_destination_white_rook_qs][ axis_x_destination_white_rook_qs] = str(ori_white_rook_qs) self.chess_board[axis_y_ori_white_rook_qs][ axis_x_ori_white_rook_qs] = '.' # update king move in txt file self.update_board_file(ori_white_king_index, destination_white_king_index_qs) # update rook move in txt file self.update_board_file(ori_white_rook_qs_index, destination_white_rook_qs_index) print('-- Valid Move --') print(f'{player_turn} just castled!') move_validator = self.player_turn(0) elif str( player_turn) == 'black' and self.castle_black_queen_side(): self.chess_board[axis_y_destination_black_king_qs][ axis_x_destination_black_king_qs] = str(ori_white_king) self.chess_board[axis_y_ori_black_king][ axis_x_ori_black_king] = '.' # move the rook on king side self.chess_board[axis_y_destination_black_rook_qs][ axis_x_destination_black_rook_qs] = str(ori_black_rook_qs) self.chess_board[axis_y_ori_black_rook_qs][ axis_x_ori_black_rook_qs] = '.' # update king move in txt file self.update_board_file(ori_black_king_index, destination_black_king_index_qs) # update rook move in txt file self.update_board_file(ori_black_rook_qs_index, destination_black_rook_qs_index) print('-- Valid Move --') print(f'{player_turn} just castled!') move_validator = self.player_turn(0) else: print('-- Invalid Move --') print('Cannot castle if there is pieces between rook and king') move_validator = self.player_turn(-1) # update the board if the player made a successful move self.board = self.get_single_list(self.chess_board) # print the board self.print_board() # validate the move, if the move_validator int is not 0. then its not a valid move if move_validator == 0: self.identifier += 1 return True return False
def _add_player(self): name = input("saisissez le nom du joueur : ") self.players.append(Player(name)) self.player_count += 1
cWhite = (255, 255, 255) cBlack = (0, 0, 0) # Inicializar juego pygame.init() pygame.display.set_caption("PONG!") iconImage = pygame.image.load("assets/icon.png") pygame.display.set_icon(iconImage) # Configurar ventana de juego screenWidth = 800 screenHeight = 600 screen = pygame.display.set_mode((screenWidth, screenHeight)) # Crear jugadores players = [Player([50, 50], (pygame.K_w, pygame.K_s)), Player([718, 50])] # Crear puntaje para jugadores score = Score(players) # Crear pelota ball = Ball() # Sonido de puntaje scoreSound = pygame.mixer.Sound("assets/score.wav") # Juego running = True while running: # Renderizar fondo de pantalla screen.fill(cBlack)
def __init__(self, filepath): self.__maze_list = [] self.__player = None self.__nbItem = 0 ####################### # Variables declaration ####################### nbCorridor = 0 nbPlayer = 0 nbEnd = 0 nbGuardian = 0 ##################### # Initialing the maze ##################### if os.path.isfile(filepath): # Open file with open(filepath) as fp: # For each line on the text file for x, line in enumerate(fp): maze_line = [] ################################# # Getting lines element on memory ################################# for y, character in enumerate(line): if (character == 'X'): maze_line.append(Wall()) elif (character == 'G'): maze_line.append(Guardian()) nbGuardian += 1 elif (character == 'E'): maze_line.append(End()) nbEnd += 1 elif (character == ' '): maze_line.append(Corridor()) nbCorridor += 1 elif (character == 'P'): self.__player = Player(x, y) maze_line.append(self.__player) nbPlayer += 1 # Adding the line on memory if nbPlayer > 1: raise ValueError( 'Erreur : Votre niveau contient trop de joueurs !') elif nbGuardian > 1: raise ValueError( 'Erreur : Votre niveau contient trop de gardiens !' ) elif nbEnd > 1: raise ValueError( 'Erreur : Votre niveau contient trop de sorties') else: self.__maze_list.append(maze_line) ################ # Item placement ################ items = [Needle(), Tube(), Ether()] # With this attribute, the Maze already know how much items exist and how much is required self.__nbItem = len(items) randomCorridors = self.randomItem(len(items)) if randomCorridors is not None: for i, (line, col) in enumerate(randomCorridors): self.__maze_list[line][col] = items[i] else: raise FileNotFoundError('Aucun fichier existant sur le chemin:' + filepath)
def TPay_to_player(self): Player1 = Player() Player1.money = 1000 Bank.Pay_to_player(Player1, 100) unittest.assertTrue(Player1.money == 1100)
def __init__(self): self.display = Display(self, (const.WIN_WIDTH, const.WIN_HEIGHT)) self.player = Player(self)
def TBuy_Lot(self): L = Lot() P = Player() Bank.Buy_Lot(L, P) unittest.assertTrue(L.Owner == P)
def main(): """ Main Program """ # Call this function so the Pygame library can initialize itself pygame.init() # Create a 500x500 sized screen screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE) pygame.display.set_caption("my-py-game") # Create the player paddle object player = Player(64, 64) # List of moving sprites moving_sprites = pygame.sprite.Group() moving_sprites.add(player) # List of all sprites all_sprites_list = pygame.sprite.Group() # List of all bullets bullet_list = pygame.sprite.Group() level_changed = True current_level_x = 0 current_level_y = 0 font = pygame.font.Font(None, 30) clock = pygame.time.Clock() done = False while not done: # --- Event Processing --- for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # if event.type == pygame.VIDEORESIZE: # old_screen_saved = screen # screen = pygame.display.set_mode((event.w, event.h), # pygame.RESIZABLE) # # On the next line, if only part of the window # # needs to be copied, there's some other options. # screen.blit(old_screen_saved, (0, 0)) # del old_screen_saved if event.type == pygame.MOUSEBUTTONDOWN: # Fire a bullet if the user clicks the mouse button # Get the mouse position pos = pygame.mouse.get_pos() mouse_x = pos[0] mouse_y = pos[1] # Create the bullet based on where we are, and where we want to go. bullet = Bullet(player.rect.centerx, player.rect.centery, mouse_x, mouse_y) # Add the bullet to the lists all_sprites_list.add(bullet) bullet_list.add(bullet) moving_sprites.add(bullet) if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player.changespeed(-PLAYER_SPEED, 0) player.set_direction('left') if event.key == pygame.K_d: player.changespeed(PLAYER_SPEED, 0) player.set_direction('right') if event.key == pygame.K_w: player.changespeed(0, -PLAYER_SPEED) if event.key == pygame.K_s: player.changespeed(0, PLAYER_SPEED) if event.type == pygame.KEYUP: if event.key == pygame.K_a: player.changespeed(PLAYER_SPEED, 0) if event.key == pygame.K_d: player.changespeed(-PLAYER_SPEED, 0) if event.key == pygame.K_w: player.changespeed(0, PLAYER_SPEED) if event.key == pygame.K_s: player.changespeed(0, -PLAYER_SPEED) # --- Game Logic --- if level_changed: if current_level_x == 0 and current_level_y == 0: # print('Entering level 1') current_level = Level(1) else: # print('Entering level 2') current_level = Level(2) current_level.draw_bg_tiles(screen) current_level.draw_walls(screen) pygame.display.flip() level_changed = False # Dirty rects are all the rects that need to be updated at the end of this frame dirty_rects = [] # get tiles intersecting player bg_to_draw = [] for bg_tile in current_level.bg_tiles: if bg_tile.rect.colliderect(player.rect): bg_to_draw.append(bg_tile) for bullet in bullet_list: if bg_tile.rect.colliderect(bullet.rect): bg_to_draw.append(bg_tile) # add those tiles to dirty rects dirty_rects.extend([bg_tile.rect for bg_tile in bg_to_draw]) dirty_rects.append(player.rect) player.move(current_level.wall_tiles) # Changing between levels if player.rect.y < -TILE_WIDTH / 2 and current_level_y == 0: level_changed = True current_level_y += 1 player.rect.y = SCREEN_HEIGHT - TILE_WIDTH / 2 - 1 if player.rect.y > SCREEN_HEIGHT - TILE_WIDTH / 2 and current_level_y > 0: level_changed = True current_level_y -= 1 player.rect.y = -TILE_WIDTH / 2 + 1 for bullet in bullet_list: bullet.update(current_level.wall_tiles) # --- Drawing --- # draw walls and player for bg_tile in bg_to_draw: bg_tile.draw_to_screen(screen) for bullet in bullet_list: screen.blit(bullet.image, bullet.rect) screen.blit(player.image, player.rect) # print(dirty_rects) if SHOW_FPS: fps = font.render(str(int(clock.get_fps())), True, pygame.Color('white')) fps_bg_image = pygame.Surface([32, 32]) fps_bg_image.fill(BLACK) screen.blit(fps_bg_image, (0, 0)) screen.blit(fps, (0, 0)) dirty_rects.append(fps_bg_image.get_rect()) pygame.display.update(dirty_rects) clock.tick(60) pygame.quit()
def TGet_from_player(self): Player1 = Player() Player1.money = 1000 Bank.Get_from_player(Player1, 100) unittest.assertTrue(Player1.money == 900)
def setUp(self): self.gestures = ["Rock", "Paper", "Scissors"] self.player_1 = Player("Bob", self.gestures)
except TypeError: clear_console() print('Entry out of range. Min 2 player - Max 4 players') # Assign players names print('Insert players names\n') count = 0 while count < players_num: player_name = input('Player {}: '.format(count + 1)) if player_name == '': player_name = 'Player {}'.format(count + 1) # Create player players.append(Player(player_name)) count += 1 clear_console() """ CREATE PLAYERS - END """ # Creating decks main_deck = Deck() stock_deck = Deck() # Cleaning stock stock_deck.clear() # Hand out / distribute cards hand_out_cards(players, main_deck) """ START THE GAME"""
def setUp(self): gestures = ["Rock", "Paper", "Scissors"] self.player_1 = Player("Bob", gestures) self.player_2 = Player("Adam", gestures) self.game_state = Game(self.player_1, self.player_2)
def move_piece(self, move): # player turn var to check the turn player_turn = str if self.identifier % 2 == 0: player_turn = Player(0) else: player_turn = Player(1) move_validator = int # so if the move is a2-a3 it will be split as an array like this ['a2', 'a3'] piece_move = move.split('-') original_square = piece_move[0] destination_square = piece_move[1] # get the original index and destination index to update the board state in the txt file ori_index = self.get_file_index(original_square) destination_index = self.get_file_index(destination_square) # get the piece on targeted square piece_in_before = self.get_piece(original_square) piece_in_destination = self.get_piece(destination_square) # check the color of the piece that being moved and the target piece_color = self.check_piece_color(piece_in_before) piece_target_color = self.check_piece_color(piece_in_destination) # get the original matrix x and y for the 2d list in order to move the pieces axis_x_original = ord(original_square[0]) - 97 axis_y_original = 8 - int(original_square[1]) # get the destination matrix x and y for the 2d list in order to move the pieces axis_x_destination = ord(destination_square[0]) - 97 axis_y_destination = 8 - int(destination_square[1]) # check of the move target is an empty square if piece_in_before == '.' and piece_in_destination == '.': print('-- Invalid Move --') print('There is no pieces that can be move there') move_validator = self.player_turn(-1) elif piece_in_destination == '.' or None: # check if the player turn is black, the player cannot move the white pieces # this statement checks if the player turn color is the same color as the pieces that he wanted to move if str(player_turn) == piece_color.lower(): self.chess_board[axis_y_destination][axis_x_destination] = str( piece_in_before) self.chess_board[axis_y_original][axis_x_original] = '.' self.update_board_file(ori_index, destination_index) print('-- Valid Move --') move_validator = self.player_turn(0) else: print('-- Invalid Move --') print(f'{player_turn} cannot move {piece_color} pieces') move_validator = self.player_turn(-1) else: # check if the piece that being moved targeted the same color if piece_color == piece_target_color: print('-- Invalid Move --') print(f'{player_turn} cannot capture {piece_color} pieces') move_validator = self.player_turn(-1) # if its different color killed the target else: self.chess_board[axis_y_destination][axis_x_destination] = str( piece_in_before) self.chess_board[axis_y_original][axis_x_original] = '.' self.update_board_file(ori_index, destination_index) print(f'EZ KILL from {piece_color}') move_validator = self.player_turn(0) # update the board if the player made a successful move self.board = self.get_single_list(self.chess_board) # print the board self.print_board() # validate the move, if the move_validator int is not 0. then its not a valid move if move_validator == 0: self.identifier += 1 return True return False
import pygame, sys, json from pprint import pprint from pygame import * from classes.player import Player with open('map.json') as data_file: data = json.load(data_file) print(len(data["map"][0])) joueur = Player((300, 200)) pygame.init() tileswidthNumber = 50 tilesHeightNumber = 50 tilesHeightSize = 16 tilesWidthSize = 16 screenWidth = tilesWidthSize * tileswidthNumber screenHeight = tilesHeightSize * tilesHeightNumber fenetre = pygame.display.set_mode((screenWidth, screenHeight)) #Icone image_icone = "DawnLike/Commissions/Icons.png" icone = pygame.image.load(image_icone) pygame.display.set_icon(icone) #Titre titre_fenetre = "Super jeux !" pygame.display.set_caption(titre_fenetre) clock = pygame.time.Clock()
def main(): run = True lost = False lives = 5 level = 0 lostCount = 0 bulletSpeed = 4 enemyVel = 1 enemies = [] waveLenght = 5 playerVel = 5 # SET UP PLAYER COORDS player = Player(375, 630) clock = pygame.time.Clock() def redrawWindow(): screen.blit(config.BG, (0, 0)) # TEXTs livesLabel = config.mainFont.render(f"Lives: {lives}", 1, (255, 255, 255)) levelLabel = config.mainFont.render(f"Level: {level}", 1, (255, 255, 255)) # Draw lives left screen.blit(livesLabel, (10, 10)) # Draw score screen.blit(levelLabel, (config.WIDTH - levelLabel.get_width() - 10, 10)) # draw enemies for enemy in enemies: enemy.draw(screen) # draw player player.draw(screen) if lost: lostLabel = config.lostFont.render("You Lost!!!", 1, (255, 0, 0)) screen.blit(lostLabel, (config.WIDTH / 2, 350)) # update window pygame.display.update() # MainLoop while run: clock.tick(config.FPS) redrawWindow() if lives <= 0 or player.health <= 0: lost = True lostCount += 1 if lost: if lostCount > config.FPS * 5: run = False else: continue if len(enemies) == 0: level += 1 waveLenght += 5 for i in range(waveLenght): enemy = Enemy(random.randrange(50, config.WIDTH - 100), random.randrange(-1500, -100), secrets.choice(config.enemyColor)) enemies.append(enemy) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # it will recognize more than 1 action keys = pygame.key.get_pressed() if (keys[pygame.K_a] or keys[pygame.K_LEFT]) and player.x + playerVel > 0: player.x -= playerVel if (keys[pygame.K_d] or keys[pygame.K_RIGHT] ) and player.x + playerVel + player.getWidth() < config.WIDTH: player.x += playerVel if (keys[pygame.K_w] or keys[pygame.K_UP]) and player.y - playerVel > 0: player.y -= playerVel if ( keys[pygame.K_s] or keys[pygame.K_DOWN] ) and player.y + playerVel + player.getHeight() + 15 < config.HEIGHT: player.y += playerVel if keys[pygame.K_SPACE]: player.shoot() for enemy in enemies[:]: enemy.move(enemyVel) enemy.moveBullets(bulletSpeed, player) # SZANSA ZE STRZELI if random.randrange(0, 4 * config.FPS) == 1: enemy.shoot() # SPRAWDZA CZY TRAFILO GRACZA if config.collide(enemy, player): player.health -= 10 enemies.remove(enemy) # JESLI INVADER PRZEJDZIE PRZEZ CALA WYSOKOSC OKNA TO GRACZ TRACI ZYCIE elif enemy.y + enemy.getHeight() > config.HEIGHT: lives -= 1 enemies.remove(enemy) player.moveBullets(bulletSpeed, enemies)