コード例 #1
0
 def addBoat(self, start, end, locationList):
     size = start[0] - end[0]
     # row offset how long
     if size == 0:
         size = start[1] - end[1]
         # column offset how tall
     self.BoatDict[size] = battleship.Battleship(size, start, end,
                                                 locationList)
     self.boatBuildingNum += 1
コード例 #2
0
 def loadresource(self):
     try:
         self.originobject.update(
             {'board': utility.Utility.loadimage("board.png")})
         # self.originobject['explosion'] = pygame.image.load("explosion.png")
         self.originobject.update(
             {'cross': utility.Utility.loadimage("cross.png")})
         self.originobject.update(
             {'green_cross': utility.Utility.loadimage("green_cross.png")})
         for model in battleship.Battleship.SHIP_TYPE:
             self.originobject['battleship'].update(
                 {model: battleship.Battleship(model, str(model + ".png"))})
     except:
         return -1
     return 0
コード例 #3
0
    def __init__(self, bship, sub1, sub2, destroyer):
        self._game = battleship.Battleship()
        self._board = self._game.get_board()
        self._bship = bship
        self._sub1 = sub1
        self._sub2 = sub2
        self._destroyer = destroyer
        self._root_window = tkinter.Tk()
        self._player_turn = True

        self._canvas = tkinter.Canvas(master=self._root_window,
                                      width=600,
                                      height=600,
                                      background='lightblue')
        self._canvas.bind('<Configure>', self._on_canvas_resized)
        self._canvas.grid(row=1,
                          column=0,
                          sticky=tkinter.N + tkinter.S + tkinter.E + tkinter.W)
        battleship_label = tkinter.Label(
            master=self._root_window,
            text="Welcome to the game of Battleship!",
            font=('Monaco', 20),
            background="#0C89FF")
        battleship_label.grid(row=2,
                              column=0,
                              sticky=tkinter.N + tkinter.S + tkinter.E +
                              tkinter.W)
        self._resized = False
        self._splash_list = []
        self._fire_list = []

        #Battleship images
        self._battleship = tkinter.PhotoImage(file='battleship.gif')
        self._battleship_rotated = tkinter.PhotoImage(
            file='battleship_rotated.png')
        self._sub = tkinter.PhotoImage(file='sub.png')
        self._sub_rotated = tkinter.PhotoImage(file='sub_rotated.png')
        self._dest = tkinter.PhotoImage(file='destroyer.png')
        self._dest_rotated = tkinter.PhotoImage(file='destroyer_rotated.png')
        self._splash = tkinter.PhotoImage(file='splash.png')
        self._fire = tkinter.PhotoImage(file='fire.png')
        self._ocean = tkinter.PhotoImage(file='ocean.png')

        self._canvas.bind('<Button-1>', self._player_move)
コード例 #4
0
ファイル: gui.py プロジェクト: Mammothskier/Battleship
def main():
    game = battleship.Battleship()
    Interface(game)
コード例 #5
0
async def on_message(message):
    #print(message.content)
    if message.author == client.user:
        return
    if str(message.channel.type) == 'private':
        #handle board setup
        #print('ACCESSING GAME ', message.author.id)
        game = active_games[message.author.id]
        if message.content == '!random':
            game.boardSetupRandom(message.author.id)
            game.playersStatus[message.author.id] = True
            await message.author.send('Your board has been set up. Here it is:'
                                      )
            await message.author.send(
                format_board(game.boardsPrivate[message.author.id]))

            if game.playersStatus[game.player1ID] and game.playersStatus[
                    game.player2ID]:
                battleship_channel = discord.utils.get(guild.text_channels,
                                                       name='battleship')
                await battleship_channel.send(
                    f'<@{game.player1ID}> and <@{game.player2ID}>. Your game is ready!'
                )
                await battleship_channel.send(
                    f'<@{game.player1ID}> Here is your tracking board:\n{format_board(game.boardsTracking[game.player1ID])}'
                )
                await battleship_channel.send(
                    f'<@{game.player2ID}> Here is your tracking board:\n{format_board(game.boardsTracking[game.player2ID])}'
                )
                await battleship_channel.send(
                    f'<@{game.player1ID}> You go first!')
        elif message.content == '!board':
            await message.author.send(
                format_board(game.boardsPrivate[message.author.id]))

        return
    if message.channel.name != 'battleship':
        return

    if message.content.startswith('!hit'):
        hitloc = (ord(message.content.split(' ')[1][0]) - 65,
                  int(message.content.split(' ')[1][1]) - 1)
        game = active_games[message.author.id]

        ret = game.hit(message.author.id, hitloc)
        if ret == -1:
            await message.channel.send(
                f'<@{message.author.id}> wait your turn!')
            return

        if ret == 0:
            await message.channel.send(
                f'<@{message.author.id}> missed!\n{format_board(game.boardsTracking[message.author.id])}'
            )
        elif ret == 1:
            await message.channel.send(
                f'<@{message.author.id}> direct hit!\n{format_board(game.boardsTracking[message.author.id])}'
            )
        elif ret == 2:
            await message.channel.send(
                f'<@{message.author.id}> direct hit and SINK!\n{format_board(game.boardsTracking[message.author.id])}'
            )
        elif ret == 3:
            await message.channel.send(
                f'<@{message.author.id}> direct hit and SINK AND GAME OVER!')
            await message.channel.send(f'<@{message.author.id}> wins!')
            await message.channel.send(
                f'<@{game.player1ID}> Here is your final board:\n{format_board(game.boardsPrivate[game.player1ID])}'
            )
            await message.channel.send(
                f'<@{game.player2ID}> Here is your final board:\n{format_board(game.boardsPrivate[game.player2ID])}'
            )
            del active_games[game.player1ID]
            del active_games[game.player2ID]

    if message.content.startswith('!battleship'):
        player_oppID = message.content.split(' ')[1][3:-1]
        user = client.get_user(int(player_oppID))
        if message.author.id in active_games or user.id in active_games:
            await message.channel.send(
                f"<@{message.author.id}> you can't do that! One of you is in an active game. Do !end to end it."
            )
            return

        await user.send(
            f"You've been invited to a game of Battleship by {message.author.name}. Set up your board!\nUse !random for a random board."
        )
        await message.author.send(
            f"You've started a game of Battleship with {user.name}. Set up your board!\nUse !random for a random board."
        )

        game = battleship.Battleship(user.id, message.author.id)
        active_games[user.id] = game
        active_games[message.author.id] = game
        #print('ADDING GAME TO DICT')
        #print(active_games)
        #print(user.id)
        #print(message.author.id)

    if message.content == '!help':
        help_string = """Battleship Help

Commands:
Use !battleship <@user> to initiate a game with a user. Ex. !battleship @dg
Use !hit <coordinates> to launch an attack. Ex. !hit A1
Use !random to generate a random board. (dm)
Use !board to see your board. (dm)
Use !end to end your current game.

You can only have one game going on at once."""

        await message.channel.send(help_string)

    if message.content == '!end':
        game = active_games[message.author.id]
        await message.channel.send(
            f'<@{message.author.id}> has ended the game.')
        await message.channel.send(
            f'<@{game.player1ID}> Here is your final board:\n{format_board(game.boardsPrivate[game.player1ID])}'
        )
        await message.channel.send(
            f'<@{game.player2ID}> Here is your final board:\n{format_board(game.boardsPrivate[game.player2ID])}'
        )
        del active_games[game.player1ID]
        del active_games[game.player2ID]
コード例 #6
0
from __future__ import print_function
import battleship as bs
import os
from time import sleep
import agents

#Select gamemode
print("Select gamemode")
print("0: Training")
print("1: Single player")
print("2: Multi player")
print("3: Competing agents")
gamemode = input("? ")

#Initialize the game
game = bs.Battleship(gamemode)

if(gamemode==0):
    agent1 = None
    agent2 = None
if(gamemode==1):
    agent1 = agents.AgentReal()
    agent2 = agents.AgentRandom()
elif(gamemode==2):
    agent1 = agents.AgentReal()
    agent2 = agents.AgentReal()
elif(gamemode==3):
    agent1 = agents.AgentRandom()
    agent2 = agents.AgentRandom()

game.players[0].getShotLocation = agent1.getShotLocation
コード例 #7
0
# Hyper parameters
LEARNING_RATE = 1  # 1: Only use future Q-value
y = 0.99
eps = 0.1
eps_decay_factor = 0.999

# Track some information per episode
shotcounts = list()
durations = list()

for episode in range(NUM_EPISODES):
    # Initialize game
    if episode % 50 == 0:
        debug(f"Episode {episode}/{NUM_EPISODES}")
    game_start = time.monotonic()
    game = bs.Battleship(0, GRIDSIZE)
    game.players[1].placeShipsRandom()

    eps *= eps_decay_factor

    while game.running:
        current_state = OneHotEncodeGrid(game.players[0].ShotGrid)
        current_q_values = model.predict(np.array([current_state]))[0].reshape(
            GRIDSIZE, GRIDSIZE)

        if np.random.random() < eps:
            # Random action
            valid_r, valid_c = np.where(game.players[0].getValidShots())
            ValidShotIndices = list(zip(valid_r, valid_c))
            shot_r, shot_c = random.choice(ValidShotIndices)
        else: