Exemple #1
0
 def __init__(self, lst_plrs):
     """ Initialise the Game, incl. the Board, Pieces and Players
     :lst_plrs: list of tuples of str_name and str_type. eg. [("A", "KB"), ("B", "Rolf")] """
     self._board = B.Hboard()
     self._players = [P.player(tup_pl) for tup_pl in lst_plrs]  # Make players from the nemes and types
     self._current_player = 0
     self.random_next_player()  # Shuffle who starts...
     self.winner = None
     self.done = False
Exemple #2
0
 def load_players(self):
   self.players = []
   con = sql.connect('darts.db')
   with con:
     cur = con.cursor()
     cur.execute("SELECT Id FROM Players")
     data = cur.fetchall()
     for pt in data:
       self.players.append(players.player(pt[0]))
Exemple #3
0
def initialize(N):
    adj_mat = np.zeros((N, N))
    player_arr = []

    for Ind in range(N):
        player_arr.append(
            players.player())  # player initialization is defined inside class
    player_arr = np.array(player_arr).copy()

    #player_arr contains array of the player objects
    #adj_mat is the adjacency matrix
    return (adj_mat, player_arr)
Exemple #4
0
	def trigger(self, cn, command, text):
		p = player(cn)
		if self.command_handlers.has_key(command):
			for func in self.command_handlers[command]:
				try:
					func(cn, text)
				except UsageError, e:
					try:
						usages = command_info[command].usages
					except KeyError:
						usages = []
					p.message(error('Invalid Usage of #' + command + ' command. ' + str(e)))
					for usage in usages:
						p.message(info('Usage: ' + command + ' ' + usage))
				except StateError, e:
					p.message(error(str(e)))
				except ArgumentValueError, e:
					p.message(error('Invalid argument. ' + str(e)))
Exemple #5
0
 def new_player(self):
   # get new player name
   self.input_window = NewPlayer()
   
   if (self.input_window.name != None and self.input_window.name != ""):
   
     # add player to database
     self.players.append(players.player())
     self.players[-1].set_name(self.input_window.name)
     self.players[-1].export_data()
     
     # update list of players
     self.display_players()
     
     # add player to game
     self.ui.listWidget_2.addItem(self.players[-1].get_name())
     self.game_players.append(self.players[-1])
     
   # get rid of input_window
   self.input_window = None
#!/usr/bin/python

import players
import games

bob = players.player(1)
nathan = players.player(2)

game = games.game()
game.add_player(bob)
game.add_player(nathan)
game.play_game()
Exemple #7
0
from cards import card
from players import player

class table():
    def __init__(self,players):
        self._players=players
        i=0
        c=len(players)

        for p in self._players:
            p.num=i
            i+=1
            p.nums=c

    def updata(self,data):
        i=0
        for p in self._players:
            temp=[]
            for name in data[i]:
                temp.append(card(name))
            p.handcard=temp



p1=player('p1',0,3,['common_ones','common_ones','common_ones','common_ones'])
p2=player('p2',1,3,['common_ones','common_ones','common_ones','common_ones'])
p3=player('p3',2,3,['common_ones','common_ones','common_ones','common_ones'])

t=table([p1,p2,p3])

print('1')
Exemple #8
0
        except ValueError:
            return False
        if input[2].lower() == 'down' or input[2].lower() == 'right':
            pass
        else:
            return False

    # def playInst(self):


# Boards
myBoard = gameboard()
hitBoard = gameboard()

# Players
human = player(0)
computer = player(1)

# Game interaction.
menu = menu()

# Instructions and intro
menu.intro()
menu.placementInst()

# Setting fleet.
human.storeShips(menu.placeShips(myBoard))

# Check for hit.
myBoard.placeMarker(human.checkHit('A1'))
Exemple #9
0
import random
import players
import decisions
singleDeck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4
currentDeck = singleDeck.copy()
currentDeck = currentDeck * 6
random.shuffle(currentDeck)

global runningcount
runningcount = 0
player1 = players.player(10000)
dealer = players.dealer()
playerList = [player1, dealer]


def drawCard():
    global runningcount
    card = currentDeck.pop(random.randint(0, len(currentDeck) - 1))
    if card < 7:
        runningcount += 1
    elif card > 9:
        runningcount -= 1
    return card


def startHand():
    for g in range(2):
        for x in range(len(playerList)):
            playerList[x].hand.append(drawCard())

Exemple #10
0
# Agents Matchup 3: [depth = 3, policy = dijkstra] vs.  [depth = 4, policy = dijkstra]

print("[Initalized Player Matchup: Experiment 1]")
print("[---------------------------------------------------------]")
res_lst_1 = []
res_elo_1 = []
res_elo_2 = []
res_elo_1.append(player1_ratings.mu)
res_elo_2.append(player2_ratings.mu)

n_games = 25  # number of games
size = 5  # board size
board = HexBoard(size)  # init board

player_1_lst = [
    player(agent='AI', color=HexBoard.BLUE, policy="random"),
    player(agent='AI', color=HexBoard.BLUE, policy="random"),
    player(agent="AI",
           color=HexBoard.BLUE,
           policy="alphabeta",
           eval="dijkstra",
           depth=3)
]

player_2_lst = [
    player(agent="AI",
           color=HexBoard.BLUE,
           policy="alphabeta",
           eval="dijkstra",
           depth=3),
    player(agent="AI",
Exemple #11
0
				return False
		except ValueError:
			return False
		if input[2].lower() == 'down' or input[2].lower() == 'right':
			pass
		else:
			return False

	# def playInst(self):

# Boards
myBoard = gameboard()
hitBoard = gameboard()

# Players
human = player(0)
computer = player(1)

# Game interaction.
menu = menu()

# Instructions and intro
menu.intro()
menu.placementInst()

# Setting fleet.
human.storeShips(menu.placeShips(myBoard))

# Check for hit.
myBoard.placeMarker(human.checkHit('A1'))
Exemple #12
0




if __name__=='__main__':
    import players
    import matplotlib.pyplot as plt
    import networkx as nx
    
    N=15
    adj_mat=np.zeros((N,N))
    player_arr=[]
    
    #Creating Players from players module
    for i in range(N):
        player_arr.append(players.player())
    player_arr=np.array(player_arr).copy()
    
    for i in range(20):
        #setting random payoff
        [player_arr[k].set_payoff(np.random.random()*4) for k in range(N)]
        
        update_and_decide(adj_mat, player_arr)
        
        [print('player', l, 'satisfaction', player_arr[l].satisfaction) for l in range(N)]
        print('\n\n')
        G=nx.from_numpy_matrix(adj_mat)
        nx.draw(G, with_labels=True)
        plt.show()
Exemple #13
0
def main():
    # creating boards for player1 and player2
    board1 = create_board()
    board2 = create_board()

    # input players' name
    player1_name = input('First players name: ')
    player2_name = input('Second players name: ')

    # creating ships on player1's board
    ship1_ver1 = gen_random_ship(board1, 4, "ver")
    ship1_ver2 = gen_random_ship(board1, 3, "ver")
    ship1_hor1 = gen_random_ship(board1, 2, "hor")
    ship1_hor2 = gen_random_ship(board1, 3, "hor")

    # creating ships on player2's board
    ship2_ver1 = gen_random_ship(board2, 4, "ver")
    ship2_ver2 = gen_random_ship(board2, 3, "ver")
    ship2_hor1 = gen_random_ship(board2, 3, "hor")
    ship2_hor2 = gen_random_ship(board2, 2, "hor")

    print_board(board1)

    while True:
        print("\033[1;34;40m \n")
        print(ship1_ver1)
        print(ship1_ver2)
        print(ship1_hor1)
        print(ship2_ver1)
        print(ship2_ver2)
        print(ship2_hor2)

        # board, guessing, hit count for player1
        player(board1, player1_name)
        print_board(board1)
        if hit_ship(board1, ship1_ver1, 4, "ver") \
           or hit_ship(board1, ship1_ver2, 3, "ver") \
           or hit_ship(board1, ship1_hor1, 2, "hor") \
           or hit_ship(board1, ship1_hor2, 3, "hor"):
            print("It was a boat")

        # end play for player1
        if all_fleet_hit(board1, 12):
            answer = input(
                "{} WIN. Game over \n New game? Y/N".format(player1_name))
            if answer == "Y":
                main()
            else:
                exit()

        # board, guessing, hit count for player2
        print("\033[0;32;47m \n")
        print_board(board2)
        player(board2, player2_name)
        print_board(board2)
        if hit_ship(board2, ship2_ver1, 4, "ver") \
           or hit_ship(board2, ship2_ver2, 3, "ver") \
           or hit_ship(board2, ship2_hor2, 2, "hor")\
           or hit_ship(board2, ship2_hor1, 3, "hor"):
            print("It was a boat")

        # end play for player2
        if all_fleet_hit(board2, 12):
            answer2 = input(
                "{} WIN. Game over \n New game? Y/N".format(player2_name))
            if answer2 == "Y":
                main()
            else:
                exit()
#!/usr/bin/python

import players

print "Starting test."

for i in xrange(1,4):
  person = players.player(i)
  person.display_player_info()
Exemple #15
0
import poker
import players as p
import helper_functions as hf
from names import names

PLAYERS			= 3
STRATEGY		= None
START_MONEY 	= 300
HANDS_TO_PLAY	= 5000
table 			= poker.table()

for i in range(0, PLAYERS):
	name 		= hf._choose_name(names)
	strategy	= hf._choose_strategy()
	money		= START_MONEY
	table.add_player(p.player(name, strategy, money))
	
hand_number = 1

while hand_number < HANDS_TO_PLAY:
	table.new_hand()
	table.deck.shuffle()
	table.move_blinds()
	table.take_blinds()
	
	if len(table.players) < 2:
		break
	else:
		for p in table.players:
			p.cards.append(table.deck.pop())
		for p in table.players:
Exemple #16
0
def main():
    lounge = room('lounge')
    player_one = player('Lincoln')
    player_two = player('Sunny')
    # player_three = player('David')
    player_one.join(lounge)
    player_two.join(lounge)
    # player_three.join(lounge)
    randomCard(lounge, 'Lincoln', 7)
    # randomCard(lounge, 'David', 3)
    randomCard(lounge, 'Sunny', 7)
    lounge.lastCard = lounge.cards_not_used[randint(
        -1, len(lounge.cards_not_used)-1)]
    while analyseCard(lounge.lastCard)[1] == '+2' or analyseCard(lounge.lastCard)[1] == '+4' or analyseCard(lounge.lastCard)[1] == 'Reverse' or analyseCard(lounge.lastCard)[1] == 'Skip':
        lounge.lastCard = lounge.cards_not_used[randint(
            -1, len(lounge.cards_not_used)-1)]
    lounge.currentColour = analyseCard(lounge.lastCard)[0]
    lounge.currentType = analyseCard(lounge.lastCard)[1]
    lounge.plusCount = 0
    import os

    # try:
    #     while True:
    #         try:
    #             p = lounge.players[lounge.playTurn[lounge.currentPlayer]]
    #         except KeyError:
    #             raise GameCompleted
    #         Tips='Press . for more card'
    #         accepted=False
    #         while not accepted:
    #             os.system('cls')
    #             print('Now',p.pid,'is playing:')
    #             print('Last card:',lounge.currentColour,analyseCard(lounge.lastCard)[3])
    #             for c in p.allCards():



    try:
        while lounge:
            y = False
            p = False
            alreadyM = False
            unable = False
            Tip = 'Press . for more card.'
            chosen = []
            while y == False:
                try:
                    x = lounge.playTurn[lounge.currentPlayer]
                    x = lounge.players[x]
                except:
                    raise GameCompleted
                os.system('cls')
                print('Now', x.pid, 'is playing...')
                lasta = analyseCard(lounge.lastCard)
                print('Last card:', lounge.currentColour, lasta[3])
                print('You have', len(x.allCards()), 'cards:')
                for z in x.allCards():
                    print(z, x.cards[z].ccolour,
                          x.cards[z].cdescription, end='', sep='\t')
                    if z in chosen:
                        print('\tCHOSEN:'+str(chosen.index(z)+1))
                    else:
                        print('')
                if Tip != '':
                    print('* '+Tip)
                    Tip = 'Press . for more card or press enter to submit.'
                if lounge.plusCount > 0:
                    print('* Pending +'+str(lounge.plusCount) +
                          '. Choose a +2 or +4 to avoid it.')
                i = input('>')
                if i == '':
                    if len(chosen) == 0:
                        Tip = 'Please choose at least 1 card or press . for more card.'
                        unable = True
                        continue
                    if not x.play(chosen):
                        Tip = 'Unable to play those cards. Please try other cards.'
                        unable = True
                        chosen = []
                    else:
                        chosen = []
                        continue
                if i == '.':
                    if alreadyM:
                        cards.applyPlus(lounge,x)
                        lounge.nextPlayer()
                        break
                    alreadyM = True
                    Tip = 'Press . if you still can not make a selection.'
                    randomCard(lounge, x, 1)
                    y = False
                    continue
                if i in x.allCards():
                    if i in chosen:
                        chosen.remove(i)
                    else:
                        chosen.append(i)
                elif len(i) == 2 and i in [ll[:2] for ll in x.allCards()]:
                    for ii in x.allCards():
                        if ii[:2] == i:
                            if ii in chosen:
                                chosen.remove(ii)
                            else:
                                chosen.append(ii)
                else:
                    if unable == False:
                        Tip = 'You do not own that card.'
                    unable = False
    except GameCompleted:
        print('Game Ended')
Exemple #17
0
import poker
import players
import strategies

print('=== program started ===\n')
t = poker.table()
a = int(input('enter player number: '))
for i in range(0, a):
	name = input('enter player{0} name: '.format(i))
	start_money = input('enter player{0} start amount of money: '.format(i))
	dbg_p = players.player(name, start_money, strategies.random_)
	t.add_player(dbg_p)
print('=== players added ===')

round_number = 1

while len(t.players) > 1:
	print('=== ROUND ' + str(round_number) + ' ===')
	t.take_new_deck()
	t.deck.shuffle()
	t.move_blinds()
	t.take_blinds()

	if len(t.players) < 2:
		break
	else:
		for p in t.players:
			p.cards.append(t.deck.pop())
			p.cards.append(t.deck.pop())
			print('DEBUG: {0}\'s cards: {1}'.format(p.name, p.cards))
Exemple #18
0
    from players import player
    import networkx as nx
    import matplotlib.pyplot as plt

    '''
    #1st config
    p1=player(action=1)
    p2=player(action=0)
    p3=player(action=1)
    p4=player(action=0)
    player_arr=np.array([p1,p2,p3,p4])
    adj_mat=np.array([[0,1,0,1],[1,0,1,0],[0,1,0,1],[1,0,1,0]])
    '''

    #2nd config
    p1=player(action=1)
    p2=player(action=0)
    p3=player(action=1)
    p4=player(action=0)
    p5=player(action=0)
    player_arr=np.array([p1,p2,p3,p4,p5])
    adj_mat=np.array([[0,1,0,1,1],[1,0,1,0,1],[0,1,0,1,1],[1,0,1,0,1],[1,1,1,1,0]])

    pgg(adj_mat,player_arr)

    G=nx.from_numpy_matrix(adj_mat)
    col_map=[]
    for p in player_arr:
        if p.action==1:
            col_map.append('blue')
        else:
Exemple #19
0
import poker
import players as p
import helper_functions as hf
from names import names

PLAYERS = 3
STRATEGY = None
START_MONEY = 300
HANDS_TO_PLAY = 5000
table = poker.table()

for i in range(0, PLAYERS):
    name = hf._choose_name(names)
    strategy = hf._choose_strategy()
    money = START_MONEY
    table.add_player(p.player(name, strategy, money))

hand_number = 1

while hand_number < HANDS_TO_PLAY:
    table.new_hand()
    table.deck.shuffle()
    table.move_blinds()
    table.take_blinds()

    if len(table.players) < 2:
        break
    else:
        for p in table.players:
            p.cards.append(table.deck.pop())
        for p in table.players:
Exemple #20
0
#Funcao para atuazilzar todas as classes na tela
def redrawGameWindow():
    win.blit(sprites.bg, (0, 0))  #posicao do background na tela
    text = font.render('Score: ' + str(man.score), 1,
                       (0, 0, 0))  #mostra o score na tela
    win.blit(text, (390, 10))  #posicao do score na tela
    man.draw(win)  #atualiza o player na tela
    goblin.draw(win)  #atualiza o inimigo na tela
    for bullet in bullets:
        bullet.draw(win)  #atualiza os projeteis na tela
    stage1.draw(win, screenWidth, screenHeight)
    pygame.display.update()  #atualiza a janela


font = pygame.font.SysFont('comicsans', 30, True)  #escolha a fonte de texto
man = players.player(20, screenHeight - 64 - 20, 64,
                     64)  #inicia o objeto player
goblin = enemies.enemy(50, screenHeight - 64 - 3, 64, 64,
                       200)  #inicia o objeto inimigo
shootLoop = 0  #coloca um delay entre o disparo de dois projeteis
bullets = []  #vetor que ira armazenas os projeteis
run = True

stage1 = platforms.stage_platforms(0, 0, 1)

#Main loop
while run:
    clock.tick(27)  #FPS

    #Verifica se o inimigo esta vivo ou nao
    if goblin.visible:
        #Implementa a colisao entre o player e o inimigo
Exemple #21
0
import players
import rooms
import map_file
import inspect

player1 = players.player()

#commands = {'move':players.move()} # Not used. Looking for good implementation of commands

user_in = None
room_dict = {}
coord_dict = {}

for name, obj in inspect.getmembers(map_file):
	if isinstance(obj,rooms.room):
		room_dict[obj.title] = obj
		coord_dict[str(obj.coords)] = obj #lists do not work as keywords so convert to str

print room_dict


### Main loop ###

while user_in != 'quit':
 	current_room = player1.get_room(coord_dict) #coord_dict[str(player1.location)] #Call the key coords as a string
 	current_room.set_stage() #should probably only be done if the room changes to avoid too much text

 	user_in = raw_input('Enter a command: ')

 	if user_in == 'move':
 		old_location = player1.location