def gameLoop(): player = Player(50, 280, 100) autofireTimer = 14 enemyFireTimer = 0 enemies = Enemies() enemies.spawnWave() projectiles = Projectiles() enemies.enemies[0].fireProjectile(projectiles, player.posx, player.posy) moon = pygame.font.Font(pygame.font.match_font('moon'), 16) while 1: dtime = clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pressed = pygame.key.get_pressed() autofireTimer = processInput(pressed, player, projectiles, autofireTimer) if player.posx < 0: player.posx = 0 elif player.posx > windowWidth - 80: player.posx = windowWidth - 80 if player.posy > windowHeight - 70: player.posy = windowHeight - 70 elif player.posy < 0: player.posy = 0 player.checkCollisions(projectiles, enemies) projectiles.update() enemyFireTimer += 1 enemies.update(projectiles) #checking for collisions happens here enemies.checkAndSpawn() enemies.checkAndFire(projectiles, player.posx, player.posy, enemyFireTimer) if player.lives <= 0: break with Profiler() as p: drawInterface(screen, player, enemies, moon) player.draw(screen) projectiles.draw(screen) enemies.draw(screen) pygame.display.flip() 1000 // dtime
def start_game(self): no_winner = True players = [] for i in range(self.player_amount): player = Player("Player-{}".format(i), "Color-{}".format(i)) self.game_board.register_player(player) players.append(player) # game loop logger.info("Starting new game") while no_winner: for player in players: # increment player turns player.turns += 1 logger.info("Player {}, Turn {}:".format( player.name, player.turns)) logger.debug( "Player data before turn: start figures: {}, finished figures: {}" .format(reveal_name(player.start_figures), reveal_name(player.finished_figures))) # grab players figures from cemetery player.grab_figures_from_cemetery(self.game_board) # check for player's figures on board if player.has_figures_on_board(self.game_board): if self.roll() == 6 and len(player.start_figures) != 0: player.place_figure(self.game_board) player.move_figure(self.game_board, self.roll()) # player has no figure on board else: # three chances to roll a 6 for i in range(3): if self.roll() == 6: # place new figure player.place_figure(self.game_board) # move figure player.move_figure(self.game_board, self.roll()) break # count finished figures to evaluate win condition finished_figures = [ figure for figure in player.finished_figures if hasattr(figure, "name") ] if len(finished_figures) == 4: no_winner = False logger.info( "Player {} won the game after {} turns!".format( player.name, player.turns)) break logger.debug( "Player data after turn: start figures: {}, finished figures: {}" .format(reveal_name(player.start_figures), reveal_name(player.finished_figures))) # debug output of board fields logger.debug("Board fields after turn: {}".format( self.game_board.display_board()))
def add_player(self, name, gender): if(not gender in self.players()): self._players[gender] = [ ] # Append our Players to their specific gender category self._players[gender].append(Player.Player(name, gender, len(self.players()[gender])))
def Game(): pygame.init() display_width = 700 display_height = 700 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Pacman') clock = pygame.time.Clock() dead = False win = False #starting position of the player var = 0 for i in range(len(level)): for j in range(len(level[i])): if level[i][j] == 2: var = 1 break if var == 1: break x = j * 34 + 2 y = i * 34 + 2 x_change = 0 y_change = 0 #starting position of the enemy enemypos = [] var = 0 enemyarr = [] dotcount = 0 print(len(level), len((level[0]))) for i in range(len(level)): for j in range(len(level[i])): if level[i][j] == 3: enemypos += [[i, j]] enemyarr += [[i, j]] if level[i][j] == 0: dotcount += 1 if level[i][j] == 2: playerpos = [j, i] print(playerpos) print(playerpos) for i in range(len(enemypos)): enemypos[i][0], enemypos[i][ 1] = enemypos[i][1] * 34 + 2, enemypos[i][0] * 34 + 2 pl = Player.Player() e = Enemy.Enemy() m = Map.Map(level) score = 0 while not dead and not win: t = time.time() for event in pygame.event.get(): dead, x_change, y_change = pl.movePlayer(x_change, y_change, event) gameDisplay.fill(white) graph = m.renderMap(display_width, display_height, gameDisplay, level) #check whether position to be moving in is valid score, dead, x_change, y_change = m.checkCollision( score, x_change, y_change, x, y, level) #move player x += x_change y += y_change # print(x, y) # print(playerpos) playerpos[0] += x_change // 34 playerpos[1] += y_change // 34 # print(enemyarr) # e.moveEnemy(enemyarr, graph, playerpos[1], playerpos[0]) pl.renderPlayer(x, y, gameDisplay) e.renderEnemy(enemypos, gameDisplay) pygame.display.update() clock.tick(30) if score == dotcount: win = True pygame.quit() quit()
# -*- coding: utf-8 -*- """ Created on Tue Dec 29 18:21:16 2020 @author: Samuel """ from classes import Card from classes import Player from classes import Deck player1 = Player(input("Type your name, player1: ")) player2 = Player(input("Type your name, player2: ")) decker = Deck() decker.shuffle() for cd in range(26): player1.increase(decker.deal()) player2.increase(decker.deal()) game_on = True round = 0 while game_on: round += 1 print("Round", round) if (len(player2.allcards) > len(player1.allcards)) and round >= 10000: print("Rounds up!", player1.name, "loses and", player2.name, "wins") game_on = False break
from classes import Player, Enemy, Obstacle, Bullet, Trap, Fire, Tank, Ninja, Door from rooms import Room filepath = os.path.dirname(__file__) pygame.init() screen = pygame.display.set_mode((800, 600), flags=pygame.SCALED | pygame.RESIZABLE) pygame.display.set_caption("Dungeon Crawler") # Player playerX = 400 playerY = 480 player = Player(playerX, playerY) playerX_change = 0 playerY_change = 0 # crate crateX = 400 crateY = 300 crates = [] crate1 = Obstacle(crateX, crateY) spikes = Trap(80, 80, "spikes") x = 300 y = 480 # Enemy enemies = [] """
def start_game(player1, player2, player3, player4, player1color, player2color, player3color, player4color): screen = Screen(900, 900, 90) screen.start_board_display() player1 = Player(player1, player1color) player1.initialize_pieces(screen) player2 = Player(player2, player2color) player2.initialize_pieces(screen) player3 = Player(player3, player3color) player3.initialize_pieces(screen) player4 = Player(player4, player4color) player4.initialize_pieces(screen) board = Board(screen) # board.draw() running = True while running: board.draw() player1.L5.draw() screen.display_update(board.board_rectangle) pygame.display.update(board.board_rectangle) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False
from classes import Agent, Player, Monster from tracker import Tracker import os def printAgents(agents): for agent in agents: print('{}'.format('-'*40)) print("{} || HP: {}/{} | AC: {} | Init: {} | Alive: {} | Concious: {} | FDS: {}\n".format(agent.name, agent.current_hp, agent.total_hp, agent.armor_class, agent.init, agent.alive, agent.concious, agent.failed_death_saves)) print("Active Status Effects: {}".format(agent.status_effects)) print('{}'.format('-'*40)) p1 = Player('Joshua Weber','Rogue','Dwarf',20,12,3) p2 = Player('Julie Weber','Paladin','Halfling',30,17,1) m1 = Monster('Werewolf','Humanoid','x',30,12,2) players = [p1,p2] monsters = [m1] game = Tracker(players,monsters) printAgents(players) p1.current_hp -= 8 printAgents(players) p1.takeDeathSave() printAgents(players) print(isinstance(p1, Player)) x = {'a':1, 'b':10, 'c':3} x.pop('a') print('{}'.format('-_-'*20))
def principal(nomecolocado): game_roda = True while game_roda: # Sorteia uma música para o jogo a = random.randint(0, 10) if a % 2 == 0: pygame.mixer.music.load(path.join(snd_dir, 'top_gear.wav')) pygame.mixer.music.set_volume(1) else: pygame.mixer.music.load(path.join(snd_dir, 'top_gear0.wav')) pygame.mixer.music.set_volume(1) # Carrega a fonte para desenhar o score. score_font = assets["score_font"] # Cria um carrinho. O construtor será chamado automaticamente. O for é para a animação da roda carro = [] for i in range(4): carrinho = 'finally{}.png'.format(i) player_img = pygame.image.load(path.join(img_dir, carrinho)).convert() player_img = pygame.transform.scale(player_img, (58, 75)) player_img.set_colorkey(WHITE) carro.append(player_img) player = Player(carro) # Cria todos os sprites e adiciona o player em tal all_sprites = pygame.sprite.Group() all_sprites.add(player) # Cria um grupo só dos carrinhos inimigos. O for é para a animação das rodas mobs = pygame.sprite.Group() inimigo = [] for i in range(4): filename = 'inimigo{}.png'.format(i) inimigo_img = pygame.image.load(path.join(img_dir, filename)).convert() inimigo_img = pygame.transform.scale(inimigo_img, (58, 75)) inimigo_img.set_colorkey(WHITE) inimigo.append(inimigo_img) # Cria grupo para as moedas coin = pygame.sprite.Group() # Cria um grupo para as caixas box = pygame.sprite.Group() #Cria grupo para os flocos flocos = pygame.sprite.Group() #Cria um grupo para o laser laser = pygame.sprite.Group() # Cria carrinhos e adiciona no grupo mobs for i in range(4): m = Mob(inimigo) all_sprites.add(m) mobs.add(m) #Cria as moedas imagem_coin = [] for i in range(9): filename = 'Gold_0{}.png'.format(i) Coin_img = pygame.image.load(path.join(img_dir, filename)).convert() Coin_img = pygame.transform.scale(Coin_img, (35, 35)) Coin_img.set_colorkey(WHITE) imagem_coin.append(Coin_img) # Adiciona as moedas nos c = Coin(imagem_coin) all_sprites.add(c) coin.add(c) # Função para criar o floco de neve (FUNÇÃO POIS SÓ QUER UM POR VEZ) def chama_floco(): f = Floco(assets["flocos_img"]) all_sprites.add(f) flocos.add(f) # Chama a função que é usada posteriormente também chama_floco() estanevando = False estanevando_tempo = 0 speedx = 0 timee = 0 clock.tick(FPS) pygame.mixer.music.play(loops=-1) velocidade = 0 aceleracao = 0.75 background_y_cima = -HEIGHT background_y = 0 # Define quantos tiros a pessoa começa e quantos pontos contagemdetiros = 3 score = 0 # Um if para caso a pessoa aperte RESTART não precise colocar o nome novamente if nomecolocado == "": # Pegar o nome colocado pela pessoa chamando a função da tela inicial nomecolocado = tela_inicial(screen) # Loop principal running = True while running: # Ajusta a velocidade do jogo clock.tick(FPS) # Para o x parar de acelerar (derrapagem) quando se pega a neve em algum momento estanevando_tempo -= 1 if estanevando_tempo == 1: estanevando_tempo = 0 speedx = 0 estanevando = False # Probabilidade de sortear caixinha if random.randrange(1, 700) == 1: b = Box(assets["box_img"]) all_sprites.add(b) box.add(b) # Probabilidade de sortear moeda if random.randrange(1, 500) == 1: c = Coin(imagem_coin) all_sprites.add(c) coin.add(c) # Processa os eventos (mouse, teclado, botão, etc). for event in pygame.event.get(): # Verifica se foi fechado. if event.type == pygame.QUIT: running = False # Verifica se apertou alguma tecla. if event.type == pygame.KEYDOWN: # Dependendo da tecla, altera a velocidade. fator = 0 if estanevando or estanevando_tempo > 0: fator = 2 if event.key == pygame.K_LEFT: speedx = -5 + fator if event.key == pygame.K_RIGHT: speedx = 5 + fator # Se for um espaço, atira! (caso tenha tiro) if contagemdetiros > 0: if event.key == pygame.K_SPACE: laserr = Laser(assets['laser_img'], player.rect.centerx, player.rect.top) all_sprites.add(laserr) laser.add(laserr) pew_sound.play() contagemdetiros -= 1 # Verifica se soltou alguma tecla. if event.type == pygame.KEYUP: fator = 0 if estanevando or estanevando_tempo > 0: fator = 2 # Dependendo da nevasca, altera a velocidade. if event.key == pygame.K_LEFT: speedx = fator if event.key == pygame.K_RIGHT: speedx = fator # Aponta a velocidade em x do player (carro) player.speedx = speedx # Verifica se jogador encostou a parede. Se encostar, morre. if player.rect.right > 519: boom_sound.play() running = False if player.rect.left < 89: boom_sound.play() running = False # Atualiza a acao de cada sprite. all_sprites.update() # Verifica se houve colisão entre Laser e carrinhos hits = pygame.sprite.groupcollide(mobs, laser, True, True) for hit in hits: # O carrinho é destruido e precisa ser recriado destroy_sound.play() m = Mob(inimigo) all_sprites.add(m) mobs.add(m) score += 5 # Verifica se houve colisão entre os carrinhos hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle) if hits: boom_sound.play() # Precisa esperar senão fecha duma vez time.sleep(0.5) running = False # Verifica se houve colisão com a moeda. Se houve, soma pontos hits = pygame.sprite.spritecollide(player, coin, True, False) if hits: moeda.play() score += 10 # Verifica se houve colisão com o misterybox. Se houve, soma pontos e ativa laser (ou soma) hits = pygame.sprite.spritecollide(player, box, True, False) for hit in hits: Ta_Da.play() score += 5 contagemdetiros += 3 # Verifica se houve colisão entre player e floco de neve hits = pygame.sprite.spritecollide(player, flocos, True, False) if hits: # Ativa o modo nevasca estanevando = True estanevando_tempo = 120 speedx = 1 for i in range(30): n = Nevasca(assets["flocos2_img"]) all_sprites.add(n) chama_floco() # Velocidade do player. Vai aumentando e estabiliza em 18 if velocidade < 18: velocidade += aceleracao # A cada loop, redesenha o fundo e os sprites background_y_cima += velocidade background_y += velocidade if background_y >= HEIGHT: background_y = 0 background_y_cima = -HEIGHT background_rect_cima.y = background_y_cima background_rect.y = background_y screen.blit(background, background_rect_cima) screen.blit(background, background_rect) all_sprites.draw(screen) # Desenha o score, por tempo timee += 1 pont = (timee // FPS) + score text_surface = score_font.render("{:01d}".format(pont), True, BLACK) text_rect = text_surface.get_rect() text_rect.midtop = (WIDTH - 300, 10) screen.blit(text_surface, text_rect) if contagemdetiros > 0: text_surface = score_font.render( "SPACE:{:01d} ESPECIAIS".format(contagemdetiros), True, BLACK) text_rect = text_surface.get_rect() text_rect.midtop = (WIDTH / 2, HEIGHT - 130) screen.blit(text_surface, text_rect) # Depois de desenhar tudo, inverte o display. pygame.display.flip() # Chamando a função para ver se a pessoa fez a maior pontuação maior_pontuacao(pont, nomecolocado) # Chamando para aparecer na tela se for o maior pontuador maior_pontuacao(pont, nomecolocado) # Chama a tela final para mostrar a pontuação da pessoa tela_mostra_pontuacao(screen, nomecolocado, pont) # Matando os mobs e o player para fazê-lo novamente quando voltar o loop for mobs in all_sprites: mobs.kill() player.kill()
Známé nedostatky: Na žádné jsem nenarazil, ale v takhle obsáhlém kódu se jich určitě dost najde. Styl: Nelíbí se mi printování všude možně. Ideální by byla třída řešící GUI, kde by byla možnost printovat do terminálu a výstup přepisovat místo vypisování pod sebe. Některé třídy mají podle linteru příliš mnoho atributů a parametrů v konstruktorech. Názvy proměnných jsou někdy krátké (xp, hp, ep). """ if __name__ == '__main__': PROMPT1 = "What theme do you wish to play? Fantasy (f) or School (s) themed?: " PROMPT2 = "Choose easy (e), medium (m) or hard (h) difficulty: " REGEX1 = "^[fs]$" REGEX2 = "^[emh]$" PLAYER_NAME = Middleware.string("Choose your name: ") THEME = Middleware.string(PROMPT1, REGEX1) DIFFICULTY = Middleware.string(PROMPT2, REGEX2) GAMEPLAN = Gameplan(THEME, DIFFICULTY) GAMEPLAN.set_up_rooms() PLAYER = Player(PLAYER_NAME, GAMEPLAN.get_skills(amount=2), GAMEPLAN.get_weapon(rarity="Uncommon")) # redisribute the first 4 atribute points print("Where do you wish to redistribute your first 5 atribute points? ") print(PLAYER.get_stats(True)) for _ in range(5): PLAYER.increase_stat() print(PLAYER.get_stats(True)) GAMEPLAN.play(PLAYER)
"grochowska", "dworzec gdanski", "obozowa", "kasa spoleczna", "gorczewska", "wolska", "bezplatny parking", "mickiewicza", "szansa", "slowackiego", "plac wilsona", "dworzec wschodni", "swietokrzyska", "krakowskie przedmiescie", "wodociagi", "nowy swiat", "idz do wiezienia", "plac trzech krzyzy", "marszalkowska", "kasa spoleczna", "aleje jerozolimskie", "dworzec centralny", "szansa", "belwederska", "domiar podatkowy", "aleje ujazdowskie" ] szanse = 12 kasy_spoleczne = 12 print("przed dev_game") dev_game = Game(5, "dev_game", 123, 1, szanse, kasy_spoleczne) #probna gra dla jednego uzytkownika print("pod dev_game") gracz1 = Player(1, "Stas", (255, 0, 0), "gierka") print("po graczu") dev_game.players.append(gracz1) print("gracze z dev_game to: ", dev_game.players) nieruchomosci = {} for i in range(40): nieruchomosci[str(i)] = [ None, 0 ] #pierwszy argument to nazwa gracza, drugi to ilosc domkow zielony = (0, 199, 20) czerwony = (255, 0, 0) niebieski = (36, 178, 255) pomaranczowy = (231, 68, 0) zolty = (252, 242, 0) fioletowy = (120, 0, 94)
from classes import Box, Objective, Player import sys, pygame from pygame.locals import * from classes import Box, Objective, Player, whiteBox import random score = 0 score2 = 0 pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((1024, 720)) player = Player() player2 = Player() player.box.rect.center = (996, 690) whiteBox1 = whiteBox() whiteBox2 = whiteBox() whiteBox1.box.rect.center = (260, 80) whiteBox2.box.rect.center = (660, 80) objectives = [] objectives.append(Objective()) objectives.append(Objective()) objectives.append(Objective()) objectives.append(Objective()) objectives.append(Objective()) objectives.append(Objective()) objectives.append(Objective())
def game_loop(): room = pygame.image.load("Living RoomWithStuff.png") # Living Room.jpg") menu = pygame.image.load("BoxWithElements.png").convert_alpha() # Menu is 1025 x 196 ########################### start_time = pygame.time.get_ticks( ) # Time from the beginning of execution cycle_time = pygame.time.get_ticks( ) # Time of each cycle or loop iteration time_counter = 0 # Player Sprite declaration ############## player_position = vector2(352, 114) player_sprite = Player("WalkingSheet.png", player_position) # Object declaration spray = Objects("Object_Spray.png", vector2(200, 430)) tape = Objects("Object_Tape.png", vector2(300, 330)) dog_toy = Objects("Object_DogToy.png", vector2(400, 530)) # Stores all objects into object_list object_list = [spray, tape, dog_toy] # Path declaration, 6 points for dog to travel too path_list = [ Path(vector2(750, 300), vector2(40, 40)), Path(vector2(110, 370), vector2(40, 40)), Path(vector2(304, 420), vector2(40, 40)), Path(vector2(750, 300), vector2(40, 40)), Path(vector2(620, 100), vector2(40, 40)), Path(vector2(250, 250), vector2(40, 40)) ] # Sets object status as active for first puppy path change_point(path_list) # Puppy declaration and setup puppy_position = path_list[0].pos puppy_speed = vector2(0, 0) puppy_sprite = Puppy("DogSpriteSpreadfinal.png", puppy_position, puppy_speed) # Game loop setup frame_clock = pygame.time.Clock() FPS = 60 game_running = True while game_running: frame_clock.tick(FPS) # get user events pygame.event.pump() for evt in pygame.event.get(): # print(evt) # Prints all key and mouse events if evt.type == pygame.QUIT: pygame.quit() sys.exit() elif evt.type == pygame.KEYDOWN and evt.key == pygame.K_ESCAPE: pygame.quit sys.exit() sprinting = False player_sprite.moving = False # Not sure if this is correct ######## if evt.type == pygame.KEYDOWN: if evt.key == pygame.K_w: # Up player_sprite.moving = True elif evt.key == pygame.K_s: player_sprite.moving = True elif evt.key == pygame.K_a: player_sprite.moving = True elif evt.key == pygame.K_d: player_sprite.moving = True elif evt.key == pygame.K_SPACE: sprinting = True # Pressed keys are assigned an action keys_pressed = pygame.key.get_pressed() # Movement speed increase with 'sprint' if keys_pressed[pygame.K_w]: player_sprite.timer = 0 player_sprite.side = 3 player_sprite.move(0, -4, sprinting) if keys_pressed[pygame.K_s]: player_sprite.timer = 0 player_sprite.side = 0 player_sprite.move(0, 4, sprinting) if keys_pressed[pygame.K_a]: player_sprite.timer = 0 player_sprite.side = 2 player_sprite.move(-4, 0, sprinting) if keys_pressed[pygame.K_d]: player_sprite.timer = 0 player_sprite.side = 1 player_sprite.move(4, 0, sprinting) # SIMULATION --------------------------- # UPDATE simulation end = pygame.time.get_ticks() delta_time = end - cycle_time cycle_time = end # Checks if player is touching any objects for obj in object_list: player_sprite.update(obj, delta_time) # Finds active spot for puppy to travel too for path in path_list: if path.status == 'active': puppy_sprite.target = path.pos path.status = 'idle' path.color = object_color_idle break # Moves towards active target if puppy_sprite.move(delta_time): # Set new active area when destination reached print("Reached point") change_point(path_list) # Game Timer functions counting_time = pygame.time.get_ticks() - start_time counting_seconds = int(counting_time % 60000 / 1000) # print(counting_seconds) # Using get_ticks, counting seconds currently times game if counting_seconds != time_counter: time_counter += 1 # If the timer has exceeded 59 seconds, game over screen if counting_seconds == 59: game_running = False game_over(path_list) # DRAW SECTION (from back to front)################## screen.blit(room, (0, 0)) # Draws each object to room for path in path_list: path.draw(screen) for obj in object_list: obj.draw(screen) # Puppy sprite is not allowing the room to be redrawn puppy_sprite.draw(screen) player_sprite.draw(screen) screen.blit(menu, (0, 572)) pygame.display.flip()
def blackJackConsole(): playing = True while playing: dealer = Dealer() player = Player() player.selectStartingAmount() lap = True while player.money > 0 and lap == True: player.lost_round = False round = Round() dealer.resetCards() player.resetCards() player.makeABet() newLine() player.takeCards(round, num=2) dealer.takeCards(round) dealer.showCardsAndPoints() player.showCardsAndPoints() player.askForAnotherCard() while player.another_card: player.takeCards(round) dealer.showCardsAndPoints() player.showCardsAndPoints() player.another_card = False if player.points[0] > 21: player.lostBecauseToManyPoints() else: player.askForAnotherCard() newLine() if not player.lost_round: dealer.takeEndCards(round) dealer.showCardsAndPoints() player.showCardsAndPoints() if player.points[0] > dealer.points or dealer.points > 21: player.wins() elif player.points[0] < dealer.points: player.loses() elif player.points[0] == dealer.points: itsATie(player) if player.money > 0: lap = askForNewRound() if not lap: player.showEndResult() playing = False else: playing = lostRoundAskForNew() if player.starting_money != 0: print('\nThank you for playing. See you next time!') print('\nIcon made by "Flat Icon" from www.flaticon.com') input("Press Enter to exit..")
#!/usr/bin/env python3 from __future__ import annotations import random from classes import Card, Player, Dealer, GameState, Deck NUM_DECKS_IN_GAME = 6 STARTING_CASH = 200 MIN_BET = 5 MAX_SPLITS = 4 deck = Deck(NUM_DECKS_IN_GAME) discard_pile = Deck(0) player1 = Player(STARTING_CASH) dealer = Dealer() state = GameState.DEAL_CARDS players = [player1]
# DB from sqllite.sqlCommands import * from sqllite.sqllite import * import collections from pathlib import Path from wikipedia import wikisearch import asyncio # Jinja templates file_loader = FileSystemLoader('web/templates') env = Environment(loader=file_loader) # Player player = Player() # Wiki 'popups' list wiki_list = wikisearch.wiki_page_search() count = 0 # Loads from local db def load(): tracks, artists, albums = db_load_all_songs() nowPlaying = player.get_last_session() player.update(nowPlaying) player.display() return [nowPlaying, tracks, albums, artists]
Writes the games into a MongoDB collection named "blackjack.games" for later analysis """ from datetime import datetime from classes import DAO, Player, Deck MONGO_URI = "mongodb://localhost" # MongoDB connection string SAMPLES = 1000 # number of games to play THRESHOLD = 15 # score under which Player will draw 1 card NB_DECKS = 4 # number of decks to use. Decks are reshuffled when half the cards have been drawn START_TIME = datetime.now() mongo = DAO(MONGO_URI) p_human = Player() p_casino = Player() c_deck = Deck(NB_DECKS) for i in range(SAMPLES): p_human.draw_card(c_deck) p_casino.draw_card(c_deck) p_human.draw_card(c_deck) p_casino.draw_card(c_deck) if p_human.blackjack: if p_casino.blackjack: p_human.gain = 0 # Casino and Player both have a blackjack, it's a deuce else: p_human.gain = 2 # Player alone has a Blackjack, double win else:
from classes import Player, Dealer match_won = False t1 = input('Team 1 name: ') t2 = input('Team 2 name: ') t1_pnames = input(f'"{t1}" players: ') t2_pnames = input(f'"{t2}" players: ') p1 = Player(t1_pnames.split(', ')[0], t1) p2 = Player(t2_pnames.split(', ')[0], t2) p3 = Player(t1_pnames.split(', ')[1], t1) p4 = Player(t2_pnames.split(', ')[1], t2) players = [p1, p2, p3, p4] d = Dealer(players) while not match_won: order = d.order() d.dealing(order) d.declare_round_trump() d.resolve_announcement_conflicts(order) d.score_round() d.check_for_won_games() match_won = d.check_for_match_win() # TODO: If 2 wins match_won = TRUE
def main(): print_in_frame = printing(print) clear() # parameters affecting the difficulty start_money = 7 number_of_islands = 10 # initialization of a player and team player = Player(money=start_money) team = Team() game = Game(player, team) game.greet_player() transition() game.ask_name() clear() game.choose_difficulty_level() clear() game.print_introduction() transition() win, lose, ext = False, False, False n_current_island = 1 while not (win or lose or ext): game.initialize_islands() print_in_frame(player.inform, 'На очереди остров ' + str(n_current_island) + '.', sep='\n') transition() # oracle go_oracle = game.ask_about_oracle() clear() if go_oracle == '1': game.talk_with_oracle() if player.money < 1: lose = True break transition() # tavern game.action_in_tavern() transition() # strike print_in_frame(team.inform, 'Вперед, на остров!', sep='\n') transition() game.try_get_chest() # check if the game should be continued print_in_frame(EXIT_QUESTION) ext_ans = get_correct_answer('1', '2') clear() if ext_ans == '2': ext = True # check win or lose team.reset_command() if player.money < 1: lose = True elif game.n_current_island == number_of_islands + 1: win = True # game over with open('records.txt', 'a') as f_out: today = datetime.datetime.today() f_out.write( today.strftime("%d-%m-%Y %H:%M") + ' | ' + 'Player: ' + game.player_name + ', ' + 'coins: ' + str(player.money) + ', islands passed: ' + str(n_current_island - 1) + '\n') print(player.inform) if win: print_in_frame(WINNING) elif lose: print_in_frame(LOSING) else: print('Конец игры.')
money_show = [0] tree1 = pygame.image.load('tree1.xcf') tree1 = pygame.transform.scale(tree1, (int(screen_width / 8), int(screen_height / 8))) bg = pygame.image.load('grass.png') bg = pygame.transform.scale(bg, (screen_width, screen_height)) gold_pic = pygame.image.load('gold.png') gold_pic = pygame.transform.scale(gold_pic, (gold_w, gold_h)) max_hp = 100 + (hp_lvl - 1) * 50 min_speed = 100 * int(screen_height / 100) * delay_time / 1000 player_speed = min_speed + (speed_lvl - 1) * min_speed / 8 player_pos = [int(screen_width / 2), screen_height - 200] player_size = [int(screen_height / 20), int(2 * screen_height / 25)] player = Player(player_size, player_speed, max_hp, max_hp, None) soldier_pic = [ pygame.image.load('zinvor1.png'), pygame.image.load('zinvor2.png'), pygame.image.load('zinvor3.png'), pygame.image.load('zinvor2.png') ] pics = [] for i in range(4): pics.append( pygame.transform.scale(soldier_pic[i], (player_size[0], player_size[1]))) player.pic = pics
def add_player(self, name, gender): if (not gender in self.players()): self._players[gender] = [] self._players[gender].append( Player.Player(name, gender, len(self.players()[gender])))
def player_GET(url=keywords.url): r = requests.get(url + "/api/player") result = json.loads(r.text) return Player(result)
from classes import Player, Bullet import levels # Colours BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) pygame.init() # Adding sprites to groups all_sprites_list = pygame.sprite.Group() player = Player(WHITE) all_sprites_list.add(player) all_sprites_list bullet_group = pygame.sprite.Group() clock = pygame.time.Clock() stamina = 150 # Screen Settings size = (1500, 750) screen = pygame.display.set_mode(size) pygame.display.set_caption("Test1") # Loop until the user clicks the close button. done = False
def phasedout_is_valid_play(play, player_id, table, turn_history, phase_status, hand, discard): """phasedout_is_valid_play returns validity of "play" given game status.""" curr_player = Player(player_id, phase_status[player_id], hand) stats = Table(table, turn_history, phase_status, discard) return stats.check_play(play, curr_player)
def __init__(self): self.player = Player() self.party_list = BSTree() self.mates += 1 self.party_list.insert(self.player)
from classes import Player from classes import PackOfCards from classes import BlackJackGame my_player = Player("John") my_pack = PackOfCards(number=3) my_game = BlackJackGame(my_player, my_pack) try: my_game.play_a_game() except: print("Try again, something went wrong!")
from classes import Player usr_name = input("What's your name? ") usr_lastName = input("What's your last name? ") usr_age = int(input("How old are you? ")) usr_position = input("What's your position? ") usr_team = input("What's your team? ") object1 = Player(usr_name, usr_lastName, usr_age, usr_position, usr_team) object1.printStats() object2 = Player(object1.name, object1.lastName, object1.age, object1.position, object1.team) object2.printStats() object3 = object1 object3.age = 18 object3.team = "Real Madrid" object3.printStats()
def test_initialization(self): dealer = Dealer([Player("Niki", "Mecheta"), Player( "Vanko", "Mecheta"), Player("Koko", "Pandi"), Player("Kiro", "Pandi")]) self.assertEqual(dealer.result_dict, {'game 1': {'round 1': {}}})
if event.key == pygame.K_SPACE: Player.speed = -10 if event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: Player.speed = 5 screen.fill() # Logica do background screen.backgroung_position -= 2 if screen.backgroung_position * -1 == screen.backgroung_limit: screen.backgroung_position = 0 # Criando o jogador player = Player(45, 45) player.draw(screen.obj) Player.y += Player.speed # Criando os muros image_wallup = pygame.image.load('img/img_wallup.png') image_walldown = pygame.image.load('img/img_walldown.png') upper_wall = Wall(0) upper_wall.draw(screen.obj, image_wallup) bottom_wall = Wall(Wall.height + Wall.distance) bottom_wall.draw(screen.obj, image_walldown) # Criando o score
if not enemy: continue else: battle_flag = battle(actor, enemy) if battle_flag == 1: print("Game Over...") input() print("Please Play Again") input() exit() else: continue print("""How to Move: ^ | w <-asd-> | v Control+Z to Quit""") input() tmp = input("Your Name?: ") player = Player(tmp, 100, [1, 2]) player.set_init_parameter(30, 70, 70, 80) base(player)
def main(): # начальные приготовления storage = Storage() ships = storage.items players = storage.player ship_coordinates_list.clear() # для создания игроков и кораблей можно было бы и отдельную функцию написать # но я не успел, в итоге дублирование кода, что не хорошо # созадем первого игрока player_1_field = field_generation() # создаем поле боя для первого игрока COUNT = 0 len_of_ships_list = len(storage.items) player = 'robot1' # input_function('Игрок 1 - Ваше имя: ') #human only! for i in NUMBER_OF_SHIPS: ship = Ships.construct(player, construct_ships(i, len_of_ships_list)) storage.items.append(ship) len_of_ships_list = len([ship for ship in ships if ship.name is player]) render_field_after_ships_placement(player_1_field, storage.items[COUNT]) #print(player_1_field) COUNT += 1 converted = convert_to_list(ship_coordinates_list) storage.player.append(Player.construct(player, 1, converted)) #выводим имя и поле с расставленными кораблями игрока 1 print('Расстановка кораблей ', players[0].name) render_field(player_1_field) # создаем второго игрока ship_coordinates_list.clear() ship_halo_coordinates.clear() player_2_field = field_generation() # поле боя для второго игрока player = 'robot2' # input_function('Игрок 2 - Ваше имя: ') len_of_ships_list = len([ship for ship in ships if ship.name is player]) for i in NUMBER_OF_SHIPS: ship = Ships.construct(player, construct_ships(i, len_of_ships_list)) storage.items.append(ship) len_of_ships_list = len([ship for ship in ships if ship.name is player]) render_field_after_ships_placement(player_2_field, storage.items[COUNT]) COUNT += 1 converted = convert_to_list(ship_coordinates_list) storage.player.append(Player.construct(player, 2, converted)) #выводим имя и поле с расставленными кораблями игрока 2 print('Расстановка кораблей игрока ', players[1].name) render_field(player_2_field) input_function('For start - press Enter.') # все возможные ходы игрока robot1 player_one_positions = field_positions_generation() # все возможные ходы игрока robot2 player_two_positions = field_positions_generation() # перемешиваем списки ходов random.shuffle(player_two_positions) random.shuffle(player_one_positions) game_state = True flag_player_1 = True flag_player_2 = False # идея логики игры в том, что есть два игрока, у которых есть набор координат. # игроки поочередно обмениваются вопросами, есть ли в их наборе определенные координаты # если запрашиваемые координаты отсутсвуют, то - игрок "не попал", если присутствуют - то "попал" # игра продолжается до тех пор, пока в списке хотя бы из одного игроков не кончатся координаты # можно было все запихнуть в функцию, что правильно, опять дублирование кода while game_state is True: while flag_player_1 is True and flag_player_2 is False and len(players[1].pset) != 0: # выбор координаты для выстрела i = random.choice(player_one_positions) # проверка есть ли эта координата в списке координат кораблей игрока 2 if i in players[1].pset: # если есть, то # 1) удаляем ее из списка координат игрока 2 # 2) удаляем ее из списка возможных выстрелов игрока 1 # 3) обновляем поле игрока 2 # 4) стреляем еще раз print(players[0].name, i, 'Попал!') shoot_popal(player_2_field, i[0], i[1]) players[1].pset.remove(i) player_one_positions.remove(i) flag_player_1 = True if len(players[1].pset) == 0: # проверяем длину строки с координатами игрока 2 после попадания, # если она нулевая, значит игрок 1 победил # выводим поля с отмеченными выстрелами и подбитыми кораблями game_state = False flag_player_1 = False flag_player_2 = False print('\nИгрок ', players[0].name, 'победил.\nСвое поле:') render_field(player_1_field) # свое поле print('Поле соперника: ') render_field(player_2_field) break elif i not in players[1].pset: # если нет, то удаляем координату из списка возможных выстрелов игрока 1 # и переход хода print(players[0].name, i, 'Мимо!') shoot_mimo(player_2_field, i[0], i[1]) player_one_positions.remove(i) flag_player_2 = True # переход хода flag_player_1 = False # для второго игрока делаем все то же самое что и для первого while flag_player_2 is True and flag_player_1 is False and len(players[0].pset) != 0: r = random.choice(player_two_positions) if r in players[0].pset: print(players[1].name, r, 'Попал!') shoot_popal(player_1_field, r[0], r[1]) players[0].pset.remove(r) player_two_positions.remove(r) flag_player_2 = True if len(players[0].pset) == 0: game_state = False flag_player_1 = False flag_player_2 = False print('\nИгрок ', players[1].name, 'победил.\nСвое поле: ') render_field(player_2_field) # свое поле print('Поле соперника: ') render_field(player_1_field) break # чужое elif r not in players[0].pset: print(players[1].name, r, 'Мимо!') shoot_mimo(player_1_field, r[0], r[1]) player_two_positions.remove(r) flag_player_2 = False flag_player_1 = True print('Конец игры!')