def pickTargetTerminator(droid,AI):
    targetDroids = findDroids(droid.x,droid.y,2,1-AI.playerID,AI.droids)
    if (len(targetDroids) > 0):
        for targetDroid in targetDroids:
            if targetDroid.variant == TURRET:
                return targetDroid.x,targetDroid.y
        for targetDroid in targetDroids:
            if targetDroid.variant == HANGAR:
                return targetDroid.x,targetDroid.y
        for targetDroid in targetDroids:
            if targetDroid.variant == HACKER:
                return targetDroid.x,targetDroid.y
        lowest = targetDroids[0]
        lowestrating = targetDroids[0].armor*targetDroids[0].healthLeft
        for targetDroid in targetDroids:
            if lowestrating > targetDroid.armor*targetDroid.healthLeft:
                lowest = targetDroid
                lowestrating = targetDroid.armor*targetDroid.healthLeft
        return lowest.x,lowest.y
    else:
        targetDroids = findDroids(droid.x,droid.y,AI.getMapHeight()+AI.getMapWidth(),1-AI.playerID,AI.droids)
        if (len(targetDroids) > 0):
            for targetDroid in targetDroids:
                if targetDroid.variant == HANGAR:
                    return targetDroid.x,targetDroid.y
            
            return targetDroids[0].x,targetDroids[0].y
        else:
            #return droid.x+ 4*(-2*AI.playerID+1),droid.y
            return AI.getMapWidth()/2, AI.getMapHeight()/2
Beispiel #2
0
    def get(self):
        try:
            stage = json.loads(self.request.get("stage"))
            aiChar = pieces["aiChar"]
            playerChar = pieces["playerChar"]
            board = Board(stage)

            logging.info("Stage: {}".format(stage))
            logging.info("AIChar: {}".format(aiChar))
            logging.info("Player Char: {}".format(playerChar))
            logging.info("Turn count {}".format(len(board)))
            logging.info("Game Board:\n"+str(board))

            over,winner = board.gameOver()
            output = {"over":over,
                      "winner":winner,
                      "aiMove":-1,}
            if not over:
                aiMove = AI.takeTurn(board, aiChar, playerChar, self.easyMode)
                board.makeMove(*(list(aiMove)+[aiChar]))
                logging.info("\n"+str(board))
                output["over"], output["winner"] = board.gameOver()
                output["aiMove"] = ((aiMove[0]*3)+aiMove[1])

            if output["over"]:
                AI.reshuffle()

            self.write(json.dumps(output))
        except:
            self.render("bad.html")
def pickTargetRepair(droid,AI):
  possibleDroids = findDroids(droid.x,droid.y,4,AI.playerID,AI.droids)
  for targetDroid in possibleDroids:
    if targetDroid.armor != targetDroid.maxArmor and targetDroid.variant == TURRET:
      return targetDroid.x,targetDroid.y
  for targetDroid in possibleDroids:
    if targetDroid.armor != targetDroid.maxArmor and targetDroid.variant == TERMINATOR:
      return targetDroid.x,targetDroid.y  
  #for targetDroid in possibleDroids:
   # if targetDroid.armor != targetDroid.maxArmor:
    #  return targetDroid.x,targetDroid.y
  possibleDroids = findDroids(droid.x,droid.y,AI.getMapHeight()+AI.getMapWidth(),AI.playerID,AI.droids)
  for targetDroid in possibleDroids:
    if targetDroid.armor != targetDroid.maxArmor and targetDroid.variant == TURRET:
      return targetDroid.x,targetDroid.y
  for targetDroid in possibleDroids:
    if targetDroid.armor != targetDroid.maxArmor and targetDroid.variant == TERMINATOR:
      return targetDroid.x,targetDroid.y
  #for targetDroid in possibleDroids:
  #  if targetDroid.armor != targetDroid.maxArmor:
  #    return targetDroid.x,targetDroid.y
  for targetDroid in possibleDroids:
    if targetDroid.armor != targetDroid.maxArmor:
      return targetDroid.x,targetDroid.y
  return -1,-1    
Beispiel #4
0
def AI_setup(module):
    AI.minimax('reset')
    response = input("Will you go first (X), or second (O)? ")
    assert response == 'X' or response == 'O', "Invalid input, please try again."
    if response == 'X':
        AI.AI_player, AI.minimax_dict = 2, {1: min, 2: max}
    else:
        AI.AI_player, AI.minimax_dict = 1, {1: max, 2: min}
def pickTargetClaw(droid,AI):
    targetDroids = findDroids(droid.x,droid.y,5,1-AI.playerID,AI.droids)
    if (len(targetDroids) > 0):
        for targetDroid in targetDroids:
            if targetDroid.variant == ARCHER:
                return targetDroid.x,targetDroid.y
        return targetDroids[0].x,targetDroids[0].y
    else:
        targetDroids = findDroids(droid.x,droid.y,AI.getMapHeight()+AI.getMapWidth(),1-AI.playerID,AI.droids)
        if (len(targetDroids) > 0):
            return targetDroids[0].x,targetDroids[0].y
        else:
            #return droid.x+ 4*(-2*AI.playerID+1),droid.y
            return AI.getMapWidth()/2, AI.getMapHeight()/2
Beispiel #6
0
 def processCardPlay(self,screen):
     while self.playable():
         if not self.auto and self.getNextSeat().human:
             card=self.getUserCard(screen)
         else:
             card=AI.chooseCard(self)
         self.playCard(screen,card)
Beispiel #7
0
def AIMove(board, type) :
    global moveList
    global outputFile
    global maxDepth

    #move = AI.decideMoveMinMax(board, maxDepth, type)
    move = AI.decideMoveAlphaBeta(board, maxDepth, type)

    boardNum = int(move[0])
    pos = int(move[2])
    boardRotate = move[4]
    rotateDir = move[5]

    board.addPiece(boardNum, pos, type)

    winCheck = board.checkWin()
    if (winCheck == -1) :
        if (rotateDir.lower() == 'l') :
            board.shiftLeft(int(boardRotate))
        else :
            board.shiftRight(int(boardRotate))
    moveList.append(move)
    outputFile.write(str(board) + "\n")
    outputFile.write(str(moveList) + "\n")

    print("AI move: " + str(move))
Beispiel #8
0
def play():
    global white, black
    user_pos = int(request.args.get("id", ""))
    if user_pos not in white and user_pos not in black:
        white.append(user_pos)
        AI_pos = AI.play(white, black)
        black.append(AI_pos)
        return str(AI_pos)
    else:
        return "-1"
def pickTargetHacker(droid,AI):
  possibleDroids = findDroids(droid.x,droid.y,4,1-AI.playerID,AI.droids)
  for targetDroid in possibleDroids:
    if targetDroid.hackedTurnsLeft == 0 and targetDroid.variant == CLAW:
      return targetDroid.x,targetDroid.y  
  for targetDroid in possibleDroids:
    if targetDroid.hackedTurnsLeft == 0 and targetDroid.variant == TERMINATOR:
      return targetDroid.x,targetDroid.y
  for targetDroid in possibleDroids:
    if targetDroid.hackedTurnsLeft == 0 and (targetDroid.variant != HANGAR and targetDroid.variant != WALL and targetDroid.variant != TURRET):
      return targetDroid.x,targetDroid.y      
  possibleDroids = findDroids(droid.x,droid.y,AI.getMapHeight()+AI.getMapWidth(),1-AI.playerID,AI.droids)
  for targetDroid in possibleDroids:
    if targetDroid.hackedTurnsLeft == 0 and targetDroid.variant == CLAW:
      return targetDroid.x,targetDroid.y  
  for targetDroid in possibleDroids:
    if targetDroid.hackedTurnsLeft == 0 and targetDroid.variant == TERMINATOR:
      return targetDroid.x,targetDroid.y
  for targetDroid in possibleDroids:
    if targetDroid.hackedTurnsLeft == 0 and (targetDroid.variant != HANGAR and targetDroid.variant != WALL and targetDroid.variant != TURRET):
      return targetDroid.x,targetDroid.y
  return -1,-1
Beispiel #10
0
def play():
  global white, black
  user_pos = int(request.args.get('id',''))
  if user_pos not in white and user_pos not in black:
    white.append(user_pos)
    AI_pos = AI.play(black, white)
    if AI_pos < 0:
      black.append(-AI_pos-1)
    else:
      black.append(AI_pos)
    print 'B: ', black
    print 'W: ', white
    return str(AI_pos)
  else:
    return '-1024'
def pickTargetArcher(droid,AI):
    targetDroids = findDroids(droid.x,droid.y,5,1-AI.playerID,AI.droids)
    if (len(targetDroids) > 0):
        for targetDroid in targetDroids:
            if targetDroid.variant == HACKER:
                return targetDroid.x,targetDroid.y
        lowest = targetDroids[0]
        lowestrating = targetDroids[0].armor*targetDroids[0].healthLeft
        for targetDroid in targetDroids:
            if lowestrating > targetDroid.armor*targetDroid.healthLeft:
                lowest = targetDroid
                lowestrating = targetDroid.armor*targetDroid.healthLeft
        return lowest.x,lowest.y
    else:
        targetDroids = findDroids(droid.x,droid.y,AI.getMapHeight()+AI.getMapWidth(),1-AI.playerID,AI.droids)
        # if (len(targetDroids) > 0):
            # for targetDroid in targetDroids:
                # if (targetDroid.variant == TERMINATOR) and ((droid.owner == 0 and  targetDroid.x > droid.x) or (droid.owner == 1 and  targetDroid.x < droid.x)):
                    # return targetDroid.x + 2*(2*AI.playerID-1),targetDroid.y
            # return AI.getMapWidth()/2, AI.getMapHeight()/2
        if (len(targetDroids) > 0):
            return targetDroids[0].x,targetDroids[0].y
        else:
            return AI.getMapWidth()/2, AI.getMapHeight()/2
Beispiel #12
0
def testAI() :
    global maxDepth
    test = Board()

    # diagonal win configs
    
    test.addPiece(1, 1, 'w')
    test.addPiece(1, 5, 'b')
    test.addPiece(1, 2, 'w')

    """
    test.addPiece(1, 9, 'b')
    test.addPiece(4, 1, 'b')
    test.addPiece(4, 5, 'b')
    test.addPiece(4, 9, 'b')

    test.addPiece(2, 3, 'b')
    test.addPiece(2, 5, 'b')
    test.addPiece(2, 7, 'b')
    test.addPiece(3, 3, 'b')
    test.addPiece(3, 5, 'b')
    test.addPiece(3, 7, 'b')
    """

    test2 = test.copyBoard()

    test2.addPiece(1, 1, 'w')
    print(test)
    #print(test2)

    #AIMove(test, 'b')

    print(test)
    print(test.heuristicValue())
    AI.decideMoveAlphaBeta(test, maxDepth, 'b')
    print("Done!")
Beispiel #13
0
def makeObstacle(obstacleChoice, position, size, image, direction = 'left'):
    if (obstacleChoice == 'Spikes'):
        return AI.spikes(position, size, image)
    elif (obstacleChoice == 'Log'):
        return AI.treeLog(position, size, image)
    elif (obstacleChoice == 'Giant rock'):
        return AI.giantRock(position, size, image, direction)
    elif (obstacleChoice == 'Banana peel'):
        return AI.bananaPeel(position, size, image)
    elif (obstacleChoice == 'Snake'):
        return AI.snake(position, size, image)
    elif (obstacleChoice == 'Bird'):
        return AI.bird(position, size, image)
    elif (obstacleChoice == 'Spider'):
        return AI.spider(position, size, image)
    elif (obstacleChoice == 'Mud'):
        return AI.mud(position, size, image)
    elif (obstacleChoice == 'Tidal wave'):
        return AI.tidalWave(position, size, image)
    else:
        return AI.Obstacle((0,0), (0,0), pygame.Surface((0, 0)))
Beispiel #14
0
 def main(self):
     for i in range(len(self.citizens)):
         if self.citizens[i].villageRole == 'Lumberjack':
             if self.citizens[i].toGive == None:
                 self.citizens[i].AI = AI.lumberJack
             if self.citizens[i].toGive == None:
                 if self.citizens[i].inv.findItemAmount(6) >= 80:
                     closeCraft = self.findClosestVillager((self.citizens[i].column,self.citizens[i].row),'Crafter')
                     if closeCraft != None:
                         self.citizens[i].AI = AI.give
                         self.citizens[i].AIGoal = closeCraft
                         self.citizens[i].toGive = 6
         elif self.citizens[i].villageRole == 'Builder':
             if self.citizens[i].toTake == (None,None):
                 self.citizens[i].AI = AI.builder
             if len(self.mustBuild) > 0:
                 if self.citizens[i].currentBuildingProject == None:
                     self.citizens[i].mustBuild = self.mustBuild[0]
                     del(self.mustBuild[0])
             if self.citizens[i].currentBuildingProject != None:
                 if AI.hasResources(self.citizens[i],self.citizens[i].currentBuildingProject) == False:
                     if self.citizens[i].requiredResources == []:
                         blues = Blueprints.blueprintList()
                         blue = blues.getBlueprint(self.citizens[i].currentBuildingProject)
                         req = blue.getRequiredResources()
                         for r in range(len(req)):
                             if self.citizens[i].inv.findItemAmount(req[r][0]) < req[r][1]:
                                 self.citizens[i].requiredResources.append((req[r][0],req[r][1] - self.citizens[i].inv.findItemAmount(req[r][0])))
                     else:
                         if self.citizens[i].toTake == (None,None):
                             chests = self.storage
                             for l in range(len(chests)):
                                 if len(self.citizens[i].requiredResources) > 0:
                                     if chests[l].inv.findItemAmount(self.citizens[i].requiredResources[0][0]) >= self.citizens[i].requiredResources[0][1]:
                                         self.citizens[i].toTake = (self.citizens[i].requiredResources[0][0],self.citizens[i].requiredResources[0][1])
                                         self.citizens[i].AIGoal = chests[l]
                                         self.citizens[i].AI = AI.take
                                         del(self.citizens[i].requiredResources[0])
                                         break
         elif self.citizens[i].villageRole == 'Crafter':
             if self.citizens[i].inv.findItemAmount(6) >= 80:
                 self.citizens[i].crafting.craftItem(8,20)
                 self.citizens[i].crafting.craftItem(9,1)
                 self.citizens[i].crafting.craftItem(10,1)
                 self.transferToNearestChest(self.citizens[i],8,40)
                 self.transferToNearestChest(self.citizens[i],9,1)
                 self.transferToNearestChest(self.citizens[i],10,1)
                 self.transferToNearestChest(self.citizens[i],6,20)
Beispiel #15
0
def press(num):
    '''
    Comando de los botones. Desactiva las posiciones del tablero donde se presento el movimiento.
    :param num: referencia a la posicion del tablero donde se presenta el movimiento.
    :type num: integer
    '''
    global a
    global count
    global first
    button = buttonList[num]
    button.config(text=str(a[count%2]), state=DISABLED)
    AI.posJuego(num, first)
    count+=1
    if first==False and not AI.isOver() and AI.freeSpace():
        first = True
        press(AI.nextMove())
    elif not AI.freeSpace() or AI.isOver():
        colorButton(AI.poswin)
        info.config(text= "Fin Partida! Juego para "+a[(count-1)%2])
        tkMessageBox.showinfo("FIN PARTIDA", message(first, AI.isOver()))
        end()
    else: first = False
Beispiel #16
0
                AI_plays = input("Play with an AI player? (Y/N) ")
                assert AI_plays == 'Y' or AI_plays == 'N', "Invalid input, please try again."
                break
            except AssertionError as e:
                print(e)

        if AI_plays == 'Y':
            try_loop(AI_setup, AI)

        board, player = Classicboard(), 1
        print(board)

        while board.winner is None:
            if AI_plays == 'Y' and player == AI.AI_player:
                print("\n")
                move = AI.minimax(board, AI.AI_player)[1]
                print(move[0], move[1])
                board.change(move[0], move[1], plyr[AI.AI_player])
            else:
                try_loop(prompt_for_move)

            if board.winner is None:
                print(board)
                player = 3 - player

    elif response == 'next-gen':
        board, player = Bigboard(), 1
        print(board)

        try_loop(prompt_for_board)
Beispiel #17
0
def main(args):
    AI.InitAI()
    winner = tictactoe()
    printboard()
    print("the winner is " + winner + "\n")
    return 0
Beispiel #18
0
    def SmartZoneEvent(self, direction, id, robot, chassis):
        if id == 1:
            if direction == 1:
                AI.SuperAI.SmartZoneEvent(self, direction, id, robot, chassis)
        elif id == 2:
            if robot > 0:
                if direction == 1:
                    # if not already well-positionned : move servo motor :
                    servoangle = self.GetMotorAngle(self.motor)
                    if servoangle < (self.maxangle - self.delta):
                        self.Input("Servo", 0, -self.servospeed)
                    elif servoangle > (self.maxangle + self.delta):
                        self.Input("Servo", 0, self.servospeed)
                    #else: self.Input("Servo", 0, 0)
        elif id == 3:
            if robot > 0:
                if direction == 1:
                    # if not already well-positionned : move servo motor :
                    servoangle = self.GetMotorAngle(self.motor)
                    if servoangle > (self.minangle + self.delta):
                        self.Input("Servo", 0, self.servospeed)
                    elif servoangle < (self.minangle - self.delta):
                        self.Input("Servo", 0, -self.servospeed)
                    #else: self.Input("Servo", 0, -self.servospeed)

        return True


AI.register(OmniServo)
Beispiel #19
0
            for trigger in self.trigger2:
                self.Input(trigger, 0, 1)

            for i in range(0, 8):
                yield 0

    def LostComponent(self, id):
        # if we lose all our weapons, stop using the Engage tactic and switch to Shove
        if id in self.weapons: self.weapons.remove(id)

        if not self.weapons and not self.sweapons and not self.tweapons and not self.qweapons:
            self.top_speed = 100
            tactic = [x for x in self.tactics if x.name == "Engage"]
            if len(tactic) > 0:
                self.tactics.remove(tactic[0])

                self.tactics.append(Tactics.Shove(self))
                self.tactics.append(Tactics.Charge(self))

        return AI.SuperAI.LostComponent(self, id)

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)


AI.register(Smashbox)
Beispiel #20
0
 def __init__(self, world, ent_xml_data, ent_config):
     Actor.__init__(self, world, ent_xml_data, ent_config)
     self.sensor = AI.Sensor(world, self)
     self.maxForce = 1000
     self.message_queue = []
Beispiel #21
0
                      if isLegal(i, j, turn)]


initBoard()

turn = b  # turn indicator b or w(Black Or White), black goes first
whiteCanPlay = True  # if white is not stuck
blackCanPlay = True  # if black is not stuck

# legal check
playerTile = input(
    "Choose your chess color.  Type 'b' for black and white otherwise.  Black goes first: "
)
playerTile = b if playerTile == 'b' else w

bestNetwork = AI.loadNetworks(AI.structure, generation)[0]

while whiteCanPlay or blackCanPlay:

    validMoves = generateValidMovesList()

    if len(validMoves) == 0:
        print()
        if turn == w:
            whiteCanPlay = False
        if turn == b:
            blackCanPlay = False
    else:
        if turn == w:
            whiteCanPlay = True
        if turn == b:
Beispiel #22
0
    def InvertHandler(self):
        # fire weapon once per second (until we're upright!)
        while 1:
            for trigger in self.triggers:
                self.Input(trigger, 0, 1)

            for i in range(0, 8):
                yield 0

    def LostComponent(self, id):
        # if we lose all our weapons, stop using the Engage tactic and switch to Shove
        if id in self.weapons: self.weapons.remove(id)

        if not self.weapons:
            self.RemoveTactic("Engage")

            self.tactics.append(Tactics.Shove(self))
            self.tactics.append(Tactics.Charge(self))

        return AI.SuperAI.LostComponent(self, id)

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)


AI.register(OmniSwitch)
Beispiel #23
0
running_reward = None

#---------define the placeholder--------
# image shape is 512,288,3
#convert shape is 64,36,1

states_batch_pl = tf.placeholder(tf.float32, shape=[None, 64, 36, 1])
actions_batch_pl = tf.placeholder(tf.float32, shape=[None, 1])
discount_rewards_batch_pl = tf.placeholder(tf.float32, shape=[None, 1])

#---------define the loss and train_op--------
gamma = 0.9
decay_rate = 0.9

#network = AI.policy_network(states_batch_pl)
sampling_prob = AI.policy_network(states_batch_pl)
loss = rein.cross_entropy_reward_loss(sampling_prob, actions_batch_pl,
                                      discount_rewards_batch_pl)
logloss = rein.loss(logits=sampling_prob, actions=actions_batch_pl)

train_op = tf.train.RMSPropOptimizer(learning_rate=0.1,
                                     decay=0.9).minimize(loss)

#---------train---------
env = gym.make('FlappyBird-v0')

with tf.Session() as sess:
    init = tf.initialize_all_variables()
    sess.run(init)

    update_batch = 70  #when times > update_batch update my weights
Beispiel #24
0
            self.RegisterSmartZone("weapon3", 4)
            self.RegisterSmartZone("weapon4", 5)

        return bReturn

    def SmartZoneEvent(self, direction, id, robot, chassis):
        if id == 1:
            if direction == 1:
                AI.SuperAI.SmartZoneEvent(self, direction, id, robot, chassis)
        elif id == 2:
            if robot > 0:
                if direction == 1:
                    self.Input("Fire1", 0, 1)
        elif id == 3:
            if robot > 0:
                if direction == 1:
                    self.Input("Fire2", 0, 1)
        elif id == 4:
            if robot > 0:
                if direction == 1:
                    self.Input("Fire3", 0, 1)
        elif id == 5:
            if robot > 0:
                if direction == 1:
                    self.Input("Fire4", 0, 1)

        return True


AI.register(OmniMultiZone)
import json, numpy, decimal
est = 1
'''if est==1:
    est=2
  else:
    est=1'''

while 1:
    #try:
    import AI
    rawdata = AI.talk(str(input("You: ")), est)
    answsheet = json.load(open("answ.json"))
    probs = list(rawdata.values())
    totalprob = 0
    for i in probs:
        totalprob = totalprob + i
    for i in range(0, len(probs)):
        probs[i] = decimal.Decimal(probs[i]) / totalprob
        print(probs)
    print(answsheet[numpy.random.choice(list(rawdata.keys()), p=probs)])
#except Exception as E:
# print(E)
Beispiel #26
0
def game(player1, player2):
    if type(player1) == Q.QLearning:
        if os.path.exists('./data/first_win_rate.pickle'):
            with open('./data/first_win_rate.pickle', 'rb') as f:
                win_rate = pickle.load(f)
        else:
            win_rate = []

    if type(player2) == Q.QLearning:
        if os.path.exists('./data/first_win_rate.pickle'):
            with open('./data/second_win_rate.pickle', 'rb') as f:
                win_rate = pickle.load(f)
        else:
            win_rate = []
    b = 0
    w = 0
    cnt = 1

    board = B.Board()
    player = P.Player()
    random_ai = R.RandomAI()
    color = BLACK
    while True:
        for i in range(100):
            w = 0
            b = 0
            for j in range(100):
                board.init()
                while not board.is_end():
                    color = board.get_color()
                    if color == BLACK:
                        status = turn(board, player1, player2, 0)
                    else:
                        status = turn(board, player2, player1, 0)
                    if status == "game-set":
                        break
                    # 盤面の表示
                    # print('after -------------->')
                    # board.show_board()

                win = board.who_won()
                if win == BLACK:
                    # print('black win')
                    b += 1
                elif win == WHITE:
                    # print('white win')
                    w += 1

            if type(player1) == Q.QLearning:
                win_rate.append(b / 100)
            else:
                win_rate.append(w / 100)

            print('black {} win'.format(b))
            print('white {} win'.format(w))

        if type(player1) == Q.QLearning:
            with open('./data/first_move_4x4.pickle'.format(cnt), 'wb') as f:
                pickle.dump(player1, f)
            with open('./data/first_win_rate.pickle', 'wb') as f:
                pickle.dump(win_rate, f)

        if type(player2) == Q.QLearning:
            with open('./data/second_move_4x4.pickle', 'wb') as f:
                pickle.dump(player2, f)
            with open('./data/second_win_rate.pickle', 'wb') as f:
                pickle.dump(win_rate, f)

        cnt += 1
Beispiel #27
0
            with open('./data/second_move_4x4.pickle', 'wb') as f:
                pickle.dump(player2, f)
            with open('./data/second_win_rate.pickle', 'wb') as f:
                pickle.dump(win_rate, f)

        cnt += 1
        # plt.plot(win_rate)
        # plt.show()


if __name__ == '__main__':
    x = 3  #int(input('先手: ナイーブ=1, ランダム=2, QL=3  > '))
    if x is 1:
        player1 = N.NaiveAI()
    elif x is 2:
        player1 = R.RandomAI()
    elif x is 3:
        if os.path.exists('./data/first_move.pickle'):
            with open('./data/first_move.pickle', 'rb') as f:
                player1 = pickle.load(f)
        else:
            player1 = Q.QLearning(BLACK)

    x = 2  #int(input('後手: ナイーブ=1, ランダム=2, QL=3  > '))
    if x is 1:
        player2 = N.NaiveAI()
    elif x is 2:
        player2 = R.RandomAI()
    elif x is 3:
        if os.path.exists('./data/second_move.pickle'):
            with open('./data/second_move.pickle', 'rb') as f:
Beispiel #28
0
	child.append(tree03, 2)

count = 0
for child in tree.children:
	for branch in child.children:
		tree001 = AI.Tree(1, 2, 0, 0, 100)
		tree002 = AI.Tree(1, 2, 0, 0, 100)
		tree003 = AI.Tree(1, 2, 0, 0, 100)
		branch.append(tree001, 0)
		branch.append(tree002, 1)
		branch.append(tree003, 2)
		for leaf in branch.children:
			leaf.value = count
			count += 1

finalValue = AI.minimax(tree, True)

print("final value of root:", finalValue)

j = [1, 2, 3, 4, 5, 6]
a = j

a[0] += 1

v = 4
w = v

v += 1

print(v, w)
Beispiel #29
0
            if len(targets) > 0 and self.reloadTime <= 0:
                try:
                    trigger = self.triggerIterator.next()
                except StopIteration:
                    self.triggerIterator = iter(self.triggers)
                    trigger = self.triggerIterator.next()

                self.Input(trigger, 0, 1)
                self.reloadTime = self.reloadDelay

        return AI.SuperAI.Tick(self)

    def InvertHandler(self):
        # fire all weapons once per second (until we're upright!)
        while 1:
            for trigger in self.triggers:
                self.Input(trigger, 0, 1)

            for i in range(0, 8):
                yield 0

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)


AI.register(PokerPlus)
            return json.dumps(
                brain.inst.parse_text(user_data.q, user_data.device))


class myAI(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))


if __name__ == "__main__":
    #app = web.application(urls, globals())
    settings.SERVER_STARTTIME = datetime.now()
    settings.REQUESTS = 0

    log.info('')
    log.info('')
    log.info('')
    log.info('')
    log.info("****************************************")
    log.info("***          Starting Janet v{}     ***".format(VERSION))
    log.info("****************************************")
    log.info('')
    log.info('')
    log.info("Started {}".format(settings.SERVER_STARTTIME))

    AI.init()

    app = myAI(urls, globals())
    app.run(port=8888)
Beispiel #31
0
    def nextStep(self,text):
        if consts.godmode:
            self.myCell.lifeTimeLeft=self.myCell.lifeTime
            self.myCell.foodLeft=self.myCell.food
        if text!="Empty":
            consts.askingQuestion=False
            ##parse input
        self._counter+=1

        ##change season

        if not consts.recording:
            if self._counter%(consts.framerate*60)==0:
                consts.season=(consts.season+1)%4
        ##handle input
        inputlist=self.getInput()
        for item in inputlist:
            if (item=="Left" or item=="Right") and (("Left" in self.__kinput) or ("Right" in self.__kinput)):
                continue
            elif (item=="c" and ("c" in self.__kinput)):
                continue
            elif (item=="m" and ("m" in self.__kinput)):
                continue
            else:
                self.__kinput.append(item)
        for item in self.__kinput:
            if not consts.mouse_control:
                if item=="Left" or item=="OLeft":
                    self.myCell.changeAngle(-1)
                if item=="Right" or item=="ORight":
                    self.myCell.changeAngle(1)
        self.myCell.changeAngle(0)
        if "Up" in self.__kinput:
            self.myCell.move()
        ##handle food and life
        self.myCell.checkTarget()
        self.myCell.checkEat(self.foodList)
        self.myCell.consumeFood(self._counter)
        self.myCell.consumeLife(self._counter)
        self.myCell.consumeEggTime(self._counter)
        self.myCell.checkRIP()
        if self.myCell.timeToHurt!=0:
            self.myCell.timeToHurt-=1
        input=[]
        for cell in self.cellList:
            input=AI.nextStep(self.myCell,self.cellList,self.foodList,cell)
            for item in input:
                if item=="OLeft":
                    cell.changeAngle(-1)
                if item=="ORight":
                    cell.changeAngle(1)
                if "Up" == item:
                    cell.move()
                if "a" == item:
                    if cell.timeToLayLeft==0 and cell.lastMother!=None:
                        self.cellEggs.append(cell.layEgg())
                        cell.lastMother=None
                        cell.target=None
                if "c" ==item:
                    if cell.mode=="m":
                        cell.mode="c"
                    else:
                        cell.mode="m"

            cell.checkEat(self.foodList)
            cell.consumeFood(self._counter)
            cell.consumeLife(self._counter)
            cell.consumeEggTime(self._counter)
            cell.checkTarget()
            cell.checkRIP()
            if cell.timeToHurt!=0:
                cell.timeToHurt-=1
            if cell.dead:
                self.cellList.remove(cell)


        if "a" in inputlist:
            if self.myCell.timeToLayLeft==0 and self.myCell.lastMother!=None:
                self.myEggs.append(self.myCell.layEgg(True))
                self.myCell.lastMother=None

        if "c" in inputlist: ##carnivore or mating
            if self.myCell.mode=='m':
                self.myCell.mode='c'
            else:
                self.myCell.mode='m'
        if "m" in inputlist: ##load/save menu
            self.LoadSaveMenu()
        ##check egg hatching
        for egg in self.cellEggs:
            egg.consumeHatch(self._counter)
        for egg in self.myEggs:
            egg.consumeHatch(self._counter)
        self.growCellEggs()
        self.growPlayerEggs()



        ##check for carnivore eating and mating
        allCells=[]
        noCollision=True
        for cell in self.cellList:
            allCells.append(cell)
        allCells.append(self.myCell)
        for cell in allCells:
            for otherCell in allCells:
                collision=math.sqrt(((cell.location.x-otherCell.location.x)**2)+((cell.location.y-otherCell.location.y)**2))<cell.rad+otherCell.rad
                if (cell.ID!=otherCell.ID) and (collision): ##not the same cell
                    noCollision=False
                    if cell.mode=='c': ##carnivore
                        if otherCell.timeToHurt<=0:
                            otherCell.timeToHurt=consts.framerate
                            otherCell.lifeTimeLeft-=cell.strength
                            if otherCell.lifeTimeLeft<=0: ##only eat if you killed him
                                cell.foodLeft+=otherCell.foodLeft
                                otherCell.lifeTimeLeft=0
                                otherCell.dead=True
                                print str(cell.ID), "Ate", str(otherCell.ID)
                            else: ##cant eat
                                print str(cell.ID), "hurt", str(otherCell.ID), "but did not kill him."
                            ##cell eat practicle
                            if cell.lastCollision!=otherCell and otherCell.lastCollision!=cell: ##only if its not a false collision
                                graphics.practicleList.append(classes.practicle(cell.location,(240,165,36),practicle_radius))
                                cell.lastCollision=otherCell
                    if cell.mode=='m': ##mate
                        if otherCell.mode=='m': ##mate too
                            cell.lastMother=otherCell
                            otherCell.lastMother=cell
                            ##cell eat practicle
                            if cell.lastCollision!=otherCell and otherCell.lastCollision!=cell: ##only if its not a false collision
                                graphics.practicleList.append(classes.practicle(cell.location,(240,36,131),practicle_radius))
                                cell.lastCollision=otherCell
            if noCollision: ##the cell has not colided, reset the last collision
                cell.lastCollision=cell.ID+self._counter


        ##check if its phase 2
        if consts.counter/consts.framerate>consts.timeUntilPhase2 and self.p2spaceLimiter.active==False:
            self.p2spaceLimiter.activate()
        self.p2spaceLimiter.grow()
        if self.p2spaceLimiter.active:
            completeCellList=[]
            for cell in self.cellList:
                completeCellList.append(cell)
            completeCellList.append(self.myCell)
            for cell in completeCellList:
                if  not math.sqrt(((cell.location.x-self.p2spaceLimiter.loc.x)**2)+((cell.location.y-self.p2spaceLimiter.loc.y)**2))<cell.rad+self.p2spaceLimiter.radius:
                    cell.lifeTimeLeft-=self.p2spaceLimiter.hurt
                    graphics.practicleList.append(classes.practicle(cell.location,(255,0,0),7))

        #grow more food
        """
        0-Summer 75%
        1-Autumn 50%
        2-winter 25%
        3-spring 100%
        """

        if consts.season==0:
            if self._counter%(consts.framerate/6)==0:
                self.putFood()
        elif consts.season==1:
            if self._counter%(consts.framerate/4)==0:
                self.putFood()
        elif consts.season==2:
            if self._counter%(consts.framerate/2)==0:
                self.putFood()
        elif consts.season==3:
            if self._counter%(consts.framerate/8)==0:
                self.putFood()

        consts.counter=self._counter
        self.__kinput=[]

        if self.myCell.dead:
            choice=None
            while choice!="Okay":
                choice = graphics.askBoard("Prompt","You have died :(\n\nYou lived " + str(consts.counter/consts.framerate)+" seconds.")
            pygame.event.post(pygame.event.Event(pygame.QUIT))

        ##deduct practicle time
        if (self._counter%(consts.framerate*0.125)):
            for practicle in graphics.practicleList:
                if practicle.radius==1:
                    graphics.practicleList.remove(practicle)
                else:
                    practicle.radius-=1
        import requests
        testdata=""
        if self._counter%30==0:
            for cell in self.cellList:
                #print cell.location.x
                #print cell.location.y
                testdata+=str(cell.location.x/float(consts.screenwidth)*100)+"@"+str(cell.location.y/float(consts.screenheight)*100)+"|";
            r = requests.post("http://www.avuka.net/P_live.php", data={"cells":testdata})
Beispiel #32
0
 def __init__(self):
     self.currentBoard = startingBoard
     self.ai = mai.AI(self)
     self.movesOutFile = None
     self.predictionsOutFile = None
Beispiel #33
0
 def __init__(self):
     self.surface = pygame.display.set_mode(Game.SIZE)
     self.clock = pygame.time.Clock()
     self.ai=AI.ArtificialIntelligence()
Beispiel #34
0
    def InvertHandler(self):
        # fire all weapons once per second (until we're upright!)
        while 1:
            for trigger in self.triggers2:
                self.Input(trigger, 0, 1)

            for i in range(0, 8):
                yield 0

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)

    def SmartZoneEvent(self, direction, id, robot, chassis):
        if id == 1 and self.weapons:
            if robot > 0:
                if direction == 1:
                    self.compinzone = 1
                    if chassis:
                        self.botinzone = 1
                if direction == -1:
                    self.compinzone = 0
                    if chassis:
                        self.botinzone = 0
        return True

AI.register(ServoClamp)
Beispiel #35
0
        return found

# WIP, convert this into array for support of more wheel sides

    def Throttle(self, throttle):
        # if we're car steering and we're not moving much, throttle up
        if self.bCarSteering and self.last_turn_throttle != 0:
            speed = self.GetSpeed()
            if speed > 0 and speed < self.top_speed / 3: throttle = self.last_throttle + 10
            elif speed < 0 and speed > -self.top_speed / 3: throttle = self.last_throttle - 10

        throttle = min(max(throttle, -100), 100)

        if self.bInvertible and self.IsUpsideDown(): throttle = -throttle

        self.set_throttle = throttle
        self.Input('Forward', 0, throttle)
        self.DebugString(0, "Throttle = " + str(int(throttle)))

    def Turn(self, turning):
        turning = min(max(turning, -100), 100)

        if self.bInvertible and self.IsUpsideDown(): turning = -turning

        self.set_turn_throttle = turning
        self.Input('LeftRight', 0, -turning)
        self.Input('LeftRight', 1, turning)
        self.DebugString(1, "Turning = " + str(int(turning)))

AI.register(FBSFlame)
Beispiel #36
0
    def __init__(self, parent, landed):
        """
        Intialise the game...
        """
        self.parent = parent
        self.lose = False

        self.score = 0
        self.level = 0
        if BATCH_AMOUNT > 1:
            self.delay = 10  #batch mode
        else:
            self.delay = 10  #ms

        #lookup table
        self.shapes = [
            square_shape, t_shape, l_shape, reverse_l_shape, z_shape, s_shape,
            i_shape
        ]

        self.thresholds = level_thresholds(500, NO_OF_LEVELS)

        self.status_bar = status_bar(parent)
        self.status_bar.pack(side=TOP, fill=X)
        #print "Status bar width",self.status_bar.cget("width")
        print self.score
        self.status_bar.set(
            "Rows Cleared: %d\t Level: %d \t Round: %d \t Avg: %d \t Highest: %d"
            % (self.score / 100, self.level + 1, amount_played + 1, average,
               high_score / 100))

        self.board = Board(parent,
                           landed,
                           scale=SCALE,
                           max_x=MAXX,
                           max_y=MAXY,
                           offset=OFFSET)
        ##load in previous game
        if self.board.landed != None:
            newlanded = copy.deepcopy(self.board.landed)
            for key, value in self.board.landed.iteritems():
                print value
                self.board.landed[key] = Block(
                    self.board.add_block(key, "blue"), key).id
            for key, value in self.board.landed.iteritems():
                print value
            #self.board.landed = newlanded

        self.board.pack(side=BOTTOM)

        self.parent.bind("p", self.p_callback)
        self.parent.bind("f", self.f_callback)
        self.parent.bind("<Up>", self.faster)
        self.parent.bind("<Down>", self.slower)
        #DISABLE KEY EVENT HANDLERS  ---- MARK LARSEN
        if len(sys.argv) > 1 and sys.argv[1] == 'human':
            self.parent.bind("<Left>", self.left_callback)
            self.parent.bind("<Right>", self.right_callback)
            self.parent.bind("<Up>", self.up_callback)
            self.parent.bind("<Down>", self.down_callback)
            self.parent.bind("a", self.a_callback)
            self.parent.bind("s", self.s_callback)
        #MAKE AI INSTEAD
        self.shapes = [
            square_shape, t_shape, l_shape, reverse_l_shape, z_shape, s_shape,
            i_shape
        ]
        self.badshapes = [fly_shape, longT_shape, square_shape]
        if sys.argv[1] == 'GBFS':
            self.ai = AI.GBFS(self)
        elif sys.argv[1] == 'DLBFS':
            self.ai = AI.DLBFS(self)
        elif sys.argv[1] == 'minimax1':
            self.ai = AI.Minimax1(self)
            self.ai.shapeList = self.shapes
        elif sys.argv[1] == 'minimax2':
            self.ai = AI.Minimax2(self)
            self.ai.shapeList = self.shapes
        elif sys.argv[1] == 'frankenminimax1':
            self.ai = AI.Minimax1(self)
            self.ai.shapeList = self.badshapes
        elif sys.argv[1] == 'frankenminimax2':
            self.ai = AI.Minimax2(self)
            self.ai.shapeList = self.badshapes
        self.shape = self.get_next_shape()
        ##MARK LARSEN, store a class variable that holds the next shape.
        ##since get_next_shape() actually handled the drawing for the shape too, we should make a separate method for the self.nextShape that draws the piece off to the side of the grid. Get_next_shape() draws it at the top of the grid.
        ##We'll also need to update this class variable in the handle_move function where the piece meets the bottom and a the next piece starts to come.
        self.nextShape = self.get_next_next_shape()
        self.board.output()

        self.after_id = self.parent.after(self.delay, self.move_my_shape)

        ##make the first move
        self.ai.make_and_time_move(self.board.gridList,
                                   self.shape,
                                   self.nextShape,
                                   first=True)
Beispiel #37
0
 def reset(self):
     self._resetLocation()
     self.knowledge = AI.KnowledgeBase(self.world, self)
     self.health = 100
     self.drop()
Beispiel #38
0
print("Finally, there are some action cards that lower your gluttony level")
print("These actions are:")
print("Exercise: -2  Laxative: -3")
print("")
print("Now that you know the rules, it's time to play!")
print("Good luck!")
print(" ")
username = input("Enter your name: ")
print("----------------------------------------")
print(" ")


#################################GAME#################################
while True:
    player_playing_card, player_hand, player_deck = player.player_main(player_hand, player_deck)
    ai_playing_card, ai_hand, ai_deck = AI.ai_main(ai_hand, ai_deck)

    player_gluttony, ai_gluttony = gluttony.gluttony_math(
        ai_playing_card, player_playing_card, ai_gluttony, player_gluttony
    )

    print("----------------------------------------")
    print("AI used " + str(ai_playing_card))
    print(" ")
    print("      " + str(username) + "'s gluttony level: " + str(player_gluttony))
    print("      AI's gluttony level: " + str(ai_gluttony))
    print("----------------------------------------")

    if ai_gluttony >= 30 or len(ai_deck) <= 0:
        print("You win!")
        break
Beispiel #39
0
# setup a logger that logs to stdout and file
logging.basicConfig(format='%(levelname)s %(asctime)s: %(message)s',
                    filename='ai_server.log',
                    datefmt='%Y/%m/%d %H:%M:%S',
                    level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler())
logger = logging.getLogger("AIServer")

# global ai result variable.
# set by worker thread "calculate_next_move",
# read by ai_retrieve requests.
# initialize to something that is a valid backup input in most cases,
# so eventual ai-retrieve-deadlocks can be resolved with a restart of this server.
ai_result = None
# global handle to actual AI
Artificial = AI.AI()
LastActions = []

slack_oauth = ""  #insert slack oauth here

#global previous_execption variable to cut down on spam
previous_posted_message = ""


def post_slack_errormsg(battle_state, traceback_last):
    #post the AI exception to slack
    #To use, generate a slack oauth and paste it into the slack_oauth variable
    global previous_posted_message

    if slack_oauth == "":
        return
Beispiel #40
0
    def frameUpdateVR(self):
        if self.frameNum == 0:
            self.players[self.selchar]["fCam"] = True

        sc = self.selchar

        scale = 1.48
        offY = -0

        self.cmp.waitGetPoses(self.VRposes, None)
        HMD_pose = self.VRposes[openvr.k_unTrackedDeviceIndex_Hmd]

        mat = np.array(HMD_pose.mDeviceToAbsoluteTracking.m)

        self.pos = mat[:, 3] * scale
        self.pos[0] *= -1
        self.pos[1] += -self.players[sc]["cheight"] + offY
        self.pos += self.players[sc]["b1"].offset[:3]

        self.vMat = np.array(mat[:, :3])
        self.vMat = np.transpose(self.vMat)
        self.vMat[::2] = self.vMat[::-2]
        self.vMat[1:] = self.vMat[:0:-1]
        self.vMat[:, 1] *= -1
        self.vMat[:, 2] *= -1
        self.vMat = np.array(self.vMat, order='C')

        self.vv = self.vMat[0]

        if len(self.CONTROLLERS) > 0:
            CTR_pose = self.VRposes[self.CONTROLLERS[0]]

            mat = np.array(CTR_pose.mDeviceToAbsoluteTracking.m)
            vMat = np.array(mat[:, :3])
            vMat = np.transpose(vMat)
            vMat[::2] = vMat[::-2]
            vMat[1:] = vMat[:0:-1]
            vMat[:, 1] *= -1
            vMat[:, 2] *= -1

            forward = vMat[0]

            d = AI.follow(forward, np.zeros(3), 1, 1, 0)
            if self.players[sc]["fCam"]:
                self.players[sc]["cr"] = d[1]
            vh = d[2]

            i = self.vrsys.getControllerState(self.CONTROLLERS[0])[1]
            x, y = i.rAxis[0].x, i.rAxis[0].y  # Touchpad
            self.players[sc]["moving"] = round(y)
            self.players[sc]["cv"] = -3 * x

            if i.ulButtonPressed & 4:  # Grip
                self.jump()
            if i.ulButtonPressed & 2:  # Upper menu
                if self.frameNum & 3 == 0:
                    self.players[sc]["fCam"] = not self.players[sc]["fCam"]

            if (i.ulButtonPressed > 1000) and (x * x + y * y == 0):  # Trigger
                if self.frameNum & 7 == 0:
                    self.tgControl()

        if len(self.CONTROLLERS) > 1:
            if self.frameNum & 1:
                CTRL = self.CONTROLLERS[1]
                CTR_pose = self.VRposes[CTRL]
                i = self.vrsys.getControllerState(self.CONTROLLERS[1])[1]
                x, y = i.rAxis[0].x, i.rAxis[0].y

                if (y > 0.8): self.fire("blank", vh=vh)
                if (x > 0.8): self.fire("red", vh=vh)
                if (y < -0.8): self.fire("orange", vh=vh)
                if (x < -0.8): self.fire("black", vh=vh)

                if i.ulButtonPressed & 4:
                    self.gesture(self.selchar, 0)
                if i.ulButtonPressed & 2:
                    self.gesture(self.selchar, 2)
                if (i.ulButtonPressed > 1000) and (x * x + y * y == 0):
                    self.gesture(self.selchar, 3)
Beispiel #41
0
    def runm(self):

        time.Clock()
        from os.path import dirname, join

        here = dirname(__file__)
        scr = display.set_mode((600, 560))
        print(menu.__doc__)
        f = font.Font(join('data/FEASFBRG.ttf'), 45)
        f1 = font.Font(join('data/FEASFBRG.ttf'), 25)
        f2 = font.Font(join('data/FEASFBRG.ttf'), 15)  #'data/321impact.ttf'
        mainmenu = f.render('ANGRY SNAKES', 1, (255, 255, 255))
        r = mainmenu.get_rect()
        r.centerx, r.top = 300, 120
        #scr.blit(image.load(join('data/bg.png')),(0,0)) if time.get_ticks()&1 else scr.fill(-1)
        background_main = image.load('data/bg.png').convert()
        scr.blit(background_main, (0, 0))
        bg = scr.copy()
        scr.blit(mainmenu, r)
        display.flip()

        menu1 = {
            "menu": ['PLAY', 'ABOUT', 'EXIT'],
            "font1": f1,
            "pos": 'center',
            "color1": (154, 180, 61),
            "light": 6,
            "speed": 200,
            "lag": 20
        }
        menu2 = {
            "menu": [
                '1 PLAYER', '2 PLAYERS VS', '2 PLAYERS CO-OP',
                '2 PLAYERS NETWORK', 'BACK'
            ],
            "font1":
            f1,
            "font2":
            f,
            "pos":
            'center',
            "color1": (154, 180, 61),
            "light":
            5,
            "speed":
            200,
            "lag":
            20
        }  #"pos":'center',"color1":(50,100,150),"light":5,"speed":0,"font1":f1,"font2":f,"justify":0}
        menu3 = {
            "menu": ['AI-1', 'AI-2'],
            "pos": (50, 250),
            "color1": (154, 180, 61),
            "light": 5,
            "speed": 0,
            "font1": f1,
            "font2": f,
            "justify": 0
        }
        menu4 = {
            "menu": ['BACK'],
            "pos": (20, 450),
            "color1": (154, 180, 61),
            "light": 5,
            "speed": 0,
            "font2": f1,
            "justify": 0
        }
        menu5 = {
            "menu": ['SERVER', 'CLIENT'],
            "pos": (50, 250),
            "color1": (154, 180, 61),
            "light": 5,
            "speed": 0,
            "font1": f1,
            "font2": f,
            "justify": 0
        }

        menus = (menu1, menu2, menu4, menu5)
        playlist = [menu1, menu2, menu4, menu5]

        resp = "re-show"
        while resp == "re-show":
            resp = menu(**menu1)[0]

        if resp == 'ABOUT':
            webbrowser.open("http://194.225.238.146/~kharazi/")

            display.update(scr.blit(bg, r, r))

            display.update(
                scr.blit(
                    f2.render('@author: vahid kharazi', 1, (200, 200, 200)),
                    (200, 450)))
            display.update(
                scr.blit(f2.render('*****@*****.**', 1, (200, 200, 200)),
                         (205, 470)))
            display.update(
                scr.blit(f2.render('Winter 1390', 1, (200, 200, 200)),
                         (235, 490)))

            #   scr.blit(background_main,(0,0))
            display.update(
                scr.blit(f.render('***ABOUT***', 1, (255, 255, 255)),
                         (200, 120)))
            resp = menu(**menu4)[0]

        if resp == 'BACK':
            scr.blit(background_main, (0, 0))
            display.update(
                scr.blit(f.render('ANGRY SNAKES', 1, (255, 255, 255)),
                         (185, 120)))
            resp = menu(**menu1)[0]

        if resp == 'PLAY':
            display.update(scr.blit(bg, r, r))
            display.update(
                scr.blit(f.render('PLAY', 1, (255, 255, 255)), (255, 120)))
            resp = menu(**menu2)[0]
    # if resp == 'OPTION':
    #    fileopen=open('data/option.csv')
        if resp == '1 PLAYER':

            mysnake = singleplayer.Snake()
            mysnake.run()

        if resp == '2 PLAYERS VS':

            mysnake = snake.Snake()
            mysnake.run()

        if resp == '2 PLAYERS CO-OP':
            display.update(scr.blit(bg, r, r))
            display.update(
                scr.blit(f.render('AI', 1, (255, 255, 255)), (30, 120)))
            resp = menu(**menu3)[0]

        if resp == '2 PLAYERS NETWORK':
            display.update(scr.blit(bg, r, r))
            display.update(
                scr.blit(f.render('NETWORK', 1, (255, 255, 255)), (30, 120)))
            resp = menu(**menu5)[0]

        if resp == 'BACK':
            scr.blit(background_main, (0, 0))
            display.update(
                scr.blit(f.render('ANGRY SNAKES', 1, (255, 255, 255)),
                         (185, 120)))
            resp = menu(**menu1)[0]

        if resp == 'CLIENT':
            import input
            myinput = input.input()
            myinput.runclient()

        #    import clientside
    #     myclient=clientside.Snake()
    #   myclient.run()
        if resp == 'SERVER':
            import input
            myinput = input.input()
            myinput.runserver()

    #        import serverside
    #      myclient=serverside.Snake()
    #       myclient.run()
        if resp == 'AI-1':
            fi1 = open('data/ai.txt', 'w')
            fi1.write('1')
            fi1.close()
            import AI
            mysnake = AI.Snake()
            mysnake.run()
        if resp == 'AI-2':
            fi2 = open('data/ai.txt', 'w')
            fi2.write('2')
            fi2.close()
            import AI
            mysnake = AI.Snake()
            mysnake.run()
Beispiel #42
0
def startGame(settings, restart, code, load, loadData):
	def drawInterface():
		guesses = settings["guesses"]
		colourNo = settings["colours"]
		pegNo = settings["pegs"]
		colourList = settings["colourList"]
		
		# Draw interface frame layout
		#================================================
		frame = GUI.Frame(gameScr, relief=GUI.RAISED, borderwidth=1, bg="white")
		frame.pack(fill=GUI.BOTH, expand=1)
		
		# Draw game board
		#================================================
		hintWidth = 8 + int((pegNo + 1) / 2) * 12
		gridWidth = 50 * pegNo + hintWidth
		cvsGrid = GUI.Canvas(frame, width=gridWidth, height=((guesses + 1) * 50 + guesses), bg="white")
		cvsGrid.pack(side=GUI.RIGHT)
		gridPegs = []
		hintPegs = []
		row = 0
		while row < guesses + 1:
			gridPegs.append([])
			hintPegs.append([])
			col = 0
			while col < pegNo:
			
				# Draw rows of pegs
				#================================================
				xPos = 50 * col + 3
				yPos = 50 * row + row + 3
				gridPegs[row].append(cvsGrid.create_oval(xPos, yPos, xPos + 44, yPos + 44, fill="black"))
				
				# Draw hint pegs
				#================================================
				if row < guesses:
					hintX = 50 * pegNo + 6 + int(col / 2) * 12
					if col % 2 == 0:
						hintY = 50 * row + 15 + row
					else:
						hintY = 50 * row + 27 + row
					hintPegs[row].append(cvsGrid.create_oval(hintX, hintY, hintX + 8, hintY + 8, fill="black"))
					
				# Separate rows with lines
				#================================================
				if row != 0:
					cvsGrid.create_line(0, yPos - 3, gridWidth, yPos - 3)
				col += 1
			row += 1
		
		# Draw common interface buttons
		#================================================
		btnQuit = GUI.Button(gameScr, text="Quit Game", fg="red", command=quitGame)
		btnQuit.pack(side=GUI.RIGHT)
		btnMenu = GUI.Button(gameScr, text="Back to Menu", command=openMenu)
		btnMenu.pack(side=GUI.RIGHT)
		btnRestart = GUI.Button(gameScr, text="Restart Game", command=restartGame)
		btnRestart.pack(side=GUI.RIGHT)
		btnNew = GUI.Button(gameScr, text="New Game", command=newGame)
		btnNew.pack(side=GUI.RIGHT)
		
		# Draw human codebreaker buttons
		#================================================
		if settings["mode"] == 1:
			for i in range(0, colourNo):
				btnColour = GUI.Button(frame, text=colourList[i], bg=colourList[i], width=12, height=5, command=lambda a=colourList[i]: selectPeg(a))
				btnColour.pack(anchor=GUI.W)
			btnDel = GUI.Button(frame, text="Undo", width=12, command=undo)
			btnDel.pack(anchor=GUI.W)
			btnSave = GUI.Button(gameScr, text="Save Game", command=lambda a=settings, b=gameEnded: file.saveGame(a, b))
			btnSave.pack(side=GUI.RIGHT)
		
		# Draw CPU codebreaker buttons
		#================================================
		if settings["mode"] == 2:
			btnAI = GUI.Button(gameScr, text="Start AI", fg="blue", command=lambda a=settings, b=GUI, c=gameScr, d=gameEnded, e=selectPeg: AI.startAI(a, b, c, d, e))
			btnAI.pack(side=GUI.RIGHT)
		
		# Set up canvas objects for manipulation
		#================================================
		settings["grid"] = gridPegs
		settings["hints"] = hintPegs
		settings["canvas"] = cvsGrid
		
		# Resume a loaded game
		#================================================
		if load == True:
			loadGrid = loadData[0]
			loadHints = loadData[1]
			for row in range(0, settings["guesses"]):
				for col in range(0, settings["pegs"]):
					settings["canvas"].itemconfig(settings["grid"][row][col], fill=loadGrid[row][col])
					settings["canvas"].itemconfig(settings["hints"][row][col], fill=loadHints[row][col])
		
	def quitGame():
		if tkMessageBox.askyesno("Quit", "Are you sure you want to quit this game?"):
			sys.exit()
			
	def restartGame():
		if not settings["AIstarted"]:
			if tkMessageBox.askyesno("Restart", "Are you sure you want to restart this game?"):
				settings["restart"] = True
				gameScr.destroy()
		else:
			tkMessageBox.showinfo("Start AI", "Please wait for the AI to finish guessing.")
			
	def newGame():
		if not settings["AIstarted"]:
			if tkMessageBox.askyesno("New", "Are you sure you want to start a new game?"):
				gameScr.destroy()
		else:
			tkMessageBox.showinfo("Start AI", "Please wait for the AI to finish guessing.")	
	def undo():
		if not gameEnded() and not settings["col"] == 0:
			canvas = settings["canvas"]
			row = settings["row"]
			col = settings["col"] - 1
			if col >= 0:
				canvas.itemconfig(settings["grid"][row][col], fill="black")
				settings["col"] -= 1
		elif gameEnded():
			tkMessageBox.showinfo("Undo", "You can't undo once the game has ended.")
		elif settings["col"] == 0 and settings["row"] == 0:
			tkMessageBox.showinfo("Undo", "There is nothing to undo!")
		else:
			tkMessageBox.showinfo("Undo", "You can't undo a finished guess, that's cheating!")
			
	def selectPeg(pegColour):
		canvas = settings["canvas"]
		if not gameEnded():
			row = settings["row"]
			col = settings["col"]
			canvas.itemconfig(settings["grid"][row][col], fill=pegColour)
			settings["col"] += 1
			if settings["col"] == settings["pegs"]: # If the row has been filled
				correct = checkRow()
				if correct == False:
					settings["row"] += 1
					settings["col"] = 0
				else:
					endGame(True)
		else:
			tkMessageBox.showinfo("Game Over", "You have already guessed the code.")
		if settings["row"] == settings["guesses"]:
			endGame(False)
			return
		
	def gameEnded():
		canvas = settings["canvas"]
		if canvas.itemcget(settings["grid"][settings["guesses"]][0], "fill") == "black" and settings["row"] != settings["guesses"]: # If the game is still going
			return False
		else:
			return True
		
	def checkRow():
		rowNo = settings["row"]
		canvas = settings["canvas"]
		correct = True
		hints = []
		code = settings["code"][:]
		
		# First, check correct positions
		#================================================
		p = 0
		while p < settings["pegs"]:
			pegColour = canvas.itemcget(settings["grid"][rowNo][p], "fill")
			if pegColour == settings["code"][p]:
				hints.append(0) # 0 means colour is in correct position
				code[p] = "used" # Set the colour to used so we don't use it for hints again
			else:
				correct = False
			p += 1
			
		# Next, check correct colours in wrong positions
		#================================================
		p = 0
		while p < settings["pegs"]:
			pegColour = canvas.itemcget(settings["grid"][rowNo][p], "fill")
			if pegColour in code and pegColour != settings["code"][p]:
				hints.append(1) # 1 means colour exists but is not in correct position
				i = 0
				while i < settings["pegs"]:
					if code[i] == pegColour:
						code[i] = "used"
						break
					i += 1
			p += 1
		hints.sort()
		
		# Fill in the hint pegs
		#================================================
		h = 0
		while h < len(hints):
			if hints[h] == 0:
				canvas.itemconfig(settings["hints"][rowNo][h], fill="red")
			elif hints[h] == 1:
				canvas.itemconfig(settings["hints"][rowNo][h], fill="white")
			h += 1
		return correct
		
	def endGame(win):
		canvas = settings["canvas"]
		code = settings["code"]
		p = 0
		while p < settings["pegs"]:
			canvas.itemconfig(settings["grid"][settings["guesses"]][p], fill=code[p])
			p += 1
		if win == True:
			tkMessageBox.showinfo("Win", "Congratulations, you found the code in " + str(settings["row"] + 1) + " guesses!")
		else:
			tkMessageBox.showinfo("Lose", "Sorry, you've used all of your " + str(settings["guesses"]) + " guesses!")
	
	def openMenu():
		if not settings["AIstarted"]:
			if tkMessageBox.askyesno("Menu", "Are you sure you want to leave this game and return to the menu?"):
				settings["menu"] = True
				gameScr.destroy()
		else:
			tkMessageBox.showinfo("Start AI", "Please wait for the AI to finish guessing.")
	
	# Set up variables
	#====================================================
	settings["colourList"] = ["red", "green", "blue", "yellow", "purple", "orange", "pink", "white"]
	settings["guesses"] = 12
	settings["restart"] = False
	settings["menu"] = False
	settings["AIstarted"] = False
	if load == False:
		settings["row"] = 0
		settings["col"] = 0
	
	# Draw interface
	#====================================================
	gameScr = GUI.Tk()
	drawInterface()
	
	# Generate/reload the answer
	#====================================================
	if restart == True:
		settings["code"] = code
	elif load == False:
		settings["code"] = AI.codeMaker(settings["pegs"], settings["colours"], settings["colourList"])
	
	gameScr.mainloop()
	
	# Return instructions for menu when game is stopped
	#================================================
	return (settings["restart"], settings["code"], settings["menu"])
Beispiel #43
0
def main(argv):
	"""The main arguments occur.

	All variables are initialized and set to the respective values, whether an integer or a class definition.
	All mouse motion is tracked once clicked, given statements for the click event
	such as selecting which level of game to play, sound on/off, and exiting the game execute.
	Once a game is selected, the board loads with instructions for placing pieces  on the board.
	The game starts as soon as the last piece(patrol boat) is placed on the player's board.
	Once a ship has been sunk, a message will display saying that respective ship has been destroyed
	and if the final ship is sunk, a winning message will dispaly.
	A new game can be started at any time using the F keys to select which level of play, turn on/off sound, or
	to return to the main menu as well as quit the game.
	All actions on the boards are set to be logged in a seperate text file for documentation and debugging.

	"""
	screen = init()
	print ("Drawing main menu.")
	title(screen)
	gamemode = 0
	global gamedifficulty
	global soundon
	gamestarted = False
	spacetaken = 0
	direction = 0
	turn = 0
	temp = 0
	shipmessage =''
	hit = pygame.mixer.Sound('resources\hit.ogg')
	miss = pygame.mixer.Sound('resources\miss.ogg')
	music = pygame.mixer.Sound('resources\TheLibertyBellMarch.ogg')

	# Continuous music
	music.play(loops = -1) 

	#get current hostname
	enteredip = list(getIP())
	while 1:
		mouseClicked = False
		for event in pygame.event.get():
			pressed = pygame.key.get_pressed()
			# If the user clicks the x at the top of the window
			if event.type == pygame.QUIT: 
				gamemode = 4

			# If the user presses F1
			elif pressed[pygame.K_F1]:
				gamemode = 1
				gamestarted = False
				gamedifficulty = 0
			# If the user presses F2
			elif pressed[pygame.K_F2]:
				gamemode = 1
				gamestarted = False
				gamedifficulty = 1
			# If the user presses F3
			elif pressed[pygame.K_F3]:
				gamemode = 1
				gamestarted = False
				gamedifficulty = 2
			# If the user presses F4
			elif pressed[pygame.K_F4]:
				gamemode = 2
				gamestarted = False

			# If the user presses F5
			elif pressed[pygame.K_F5]:
				gamemode = 0
				gamestarted = False

			#If the user presses F6
			elif pressed[pygame.K_F6]:
				if (soundon == 1):
					pygame.mixer.pause()
					soundon = 0
				elif (soundon == 0):
					pygame.mixer.unpause()
					soundon = 1
				
			#If the user presses F12
			elif pressed[pygame.K_F12]:
				gamemode = 4

			# If the mouse is moved, record the current coordinates
			elif event.type == MOUSEMOTION:
				mousex, mousey = event.pos

			# If the mouse is clicked, say so and record the current coordinates
			elif event.type == MOUSEBUTTONUP:
				mousex, mousey = event.pos
				mouseClicked = True

			# Blanket catch for any other key press, keep this at the end!
			elif event.type == KEYDOWN:
				if event.key == K_BACKSPACE:
					enteredip = enteredip[0:-1]
				elif event.key == K_RETURN:
					pass
				elif (event.key >= 48 and event.key <= 57) or event.key == 46:
					enteredip.append(chr(event.key))

		# If we're in gamemode 0, show the titlescreen
		if (gamemode == 0):
			gamemode = title(screen, mousex, mousey, mouseClicked)
			if gamemode != 0:
				continue

		# If we're in gamemode 1, show the game screen
		if (gamemode == 1):
			if not gamestarted:
				print ("Starting a new game")
				single(screen)
				place = 0
				spacetaken = 0
				turn = 0
				playerboard = board()
				playerattackboard = board()
				cpuboard = board()
				cpuattackboard = board()
				comp = AI()
				comp.placeships(shiparray, cpuboard)
				gamestarted = True
			if (place == 0):
				singleinstructions(screen, 'Please place the Aircraft Carrier on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500)
			elif (place == 1):
				singleinstructions(screen, 'Please place the Battleship on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500)
			elif (place == 2):
				singleinstructions(screen, 'Please place the Submarine on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500)
			elif (place == 3):
				singleinstructions(screen, 'Please place the Destroyer on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500)
			elif (place == 4):
				singleinstructions(screen, 'Please place the Patrol Boat on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500)
			elif (place == 5):
				singleinstructions(screen, 'Please select spot on attack board to start game', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500)
			#else:
				#singleinstructions(screen, '', '', 475, 500)
			drawboards(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2)
			boxx2, boxy2 = whatbox(mousex, mousey, XMARGIN2)
			# user places ships on board
			if (boxx2 != None and boxy2 != None) and mouseClicked:
				if (place < 5):
					checkplace = 0
					spacepressed = pressed[pygame.K_SPACE]
					if not (spacepressed):
						hold = boxy2
						if ((shiparray[place]+boxy2) < 11):
							if (checkplace == 0):
								for y in range(shiparray[place]): 
									if ((playerboard.returnpiece(boxx2,hold)) != 0):
										checkplace = 1
									else:
										hold = hold + 1
							for y in range(shiparray[place]): 
								if (checkplace == 1):
									break
								else:
									playerboard.setpiece(shiparray[place],boxx2,boxy2)
									boxy2 = boxy2 + 1
									if (y == (shiparray[place]-1)):
										place = place + 1
					elif (spacepressed):
						hold = boxx2
						if ((shiparray[place]+boxx2) < 11):
							if (checkplace == 0):
								for x in range(shiparray[place]): 
									if ((playerboard.returnpiece(hold,boxy2)) != 0):
										checkplace = 1
									else:
										hold = hold + 1
							for x in range(shiparray[place]): 
								if (checkplace == 1):
									break
								else:
									playerboard.setpiece(shiparray[place],boxx2,boxy2)
									boxx2 = boxx2 + 1
									if (x == (shiparray[place]-1)):
										place = place + 1
			boxx, boxy = whatbox(mousex, mousey, XMARGIN)
			# game ready to play
			if (place >= 5):
				if (turn == 0):
					if (boxx != None and boxy != None) and mouseClicked:
						place = place + 1
						temp = cpuboard.checkforhitormiss(boxx,boxy)
						if (temp == 9):
							blah = 0
						else:
							playerattackboard.setpiece(temp,boxx,boxy)
							log_message('Player Move', playerattackboard.returnboard())
							
							if (temp == 7):
								printstatus(screen, 'Miss')
								miss.play(loops = 0)
							else:
								printstatus(screen, 'Hit')
								hit.play(loops = 0)
							if (checkforwin(playerattackboard)):
								printstatus(screen, 'You win!')
								turn = -1
							else:
								checkforshipsunk(playerattackboard, temp, screen)
								turn = 1
				elif (turn == 1):
					if (gamedifficulty == 0):
						comp.attack(playerboard, cpuattackboard)
						log_message('Easy CPU Move', cpuattackboard.returnboard())

					elif (gamedifficulty == 1):
						comp.attack2(playerboard, cpuattackboard)
						log_message('Harder CPU Move', cpuattackboard.returnboard())

					elif (gamedifficulty == 2):
						comp.attack3(playerboard, cpuattackboard)
						log_message('Hardest CPU Move', cpuattackboard.returnboard())

					if (checkforwin(cpuattackboard)):
						printstatus(screen, 'Computer Wins!')
						turn = -1
					else:
						turn = 0  

		# If we're in gamemode 2, show the multiplayer screen
		if (gamemode == 2):

			option = multi(screen, "".join(enteredip), mousex, mousey, mouseClicked)

			if (option == 1):
				multi_game_init(None)
				ip = getIP()
				gamemode = 3
				playernumber = 1

			elif (option == 2):
				ip = "".join(enteredip)
				multi_game_init(ip)
				gamemode = 3
				playernumber = 2

			elif (option == 3):
				gamemode = 0


		if (gamemode == 3):

			s = get_socket(ip)
			preamble = get_preamble(s)
			status, turn = preamble.split('.')
			status = int(status)
			turn = int(turn)
			boards = get_boards(s)

			if (status == 0):
				gamemode = 0

			if not gamestarted:
				try:
					playernumber
				except NameError:
					print ('Something went horribly wrong... I don\'t know whose turn it is!')
					sys.exit(1)
				print ("Starting a new multiplayer game")
				single(screen)
				place = 0
				spacetaken = 0
				turn = 0
				playerboard = board()
				playerattackboard = board()
				enemyboard = board()
				enemyattackboard = board()
				gameboards = [playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard()]
				gamestarted = True

			if (place == 0):
				multiinstructions(screen, 'Please place the Aircraft Carrier on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20)
			elif (place == 1):
				multiinstructions(screen, 'Please place the Battleship on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20)
			elif (place == 2):
				multiinstructions(screen, 'Please place the Submarine on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20)
			elif (place == 3):
				multiinstructions(screen, 'Please place the Destroyer on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20)
			elif (place == 4):
				multiinstructions(screen, 'Please place the Patrol Boat on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20)

			
			boxx, boxy = whatbox(mousex, mousey, XMARGIN)
			boxx2, boxy2 = whatbox(mousex, mousey, XMARGIN2)
			# user places ships on board
			if (place < 5 and place >= 0):
				drawboards(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2)
				if boxx2 != None and boxy2 != None and mouseClicked:
					checkplace = 0
					spacepressed = pressed[pygame.K_SPACE]
					if not (spacepressed):
						hold = boxy2
						if ((shiparray[place]+boxy2) < 11):
							if (checkplace == 0):
								for y in range(shiparray[place]): 
									if ((playerboard.returnpiece(boxx2,hold)) != 0):
										checkplace = 1
									else:
										hold = hold + 1
							for y in range(shiparray[place]): 
								if (checkplace == 1):
									break
								else:
									playerboard.setpiece(shiparray[place],boxx2,boxy2)
									boxy2 = boxy2 + 1
									if (y == (shiparray[place]-1)):
										place = place + 1
					elif (spacepressed):
						hold = boxx2
						if ((shiparray[place]+boxx2) < 11):
							if (checkplace == 0):
								for x in range(shiparray[place]): 
									if ((playerboard.returnpiece(hold,boxy2)) != 0):
										checkplace = 1
									else:
										hold = hold + 1
							for x in range(shiparray[place]): 
								if (checkplace == 1):
									break
								else:
									playerboard.setpiece(shiparray[place],boxx2,boxy2)
									boxx2 = boxx2 + 1
									if (x == (shiparray[place]-1)):
										place = place + 1

			# game ready to play
			if (place > 6):
				if (turn == playernumber):
					multiinstructions(screen, 'Please select spot on attack board to start game', '', 100, 500)
					if (boxx != None and boxy != None) and mouseClicked:
						shipmessage = ''
						place = place + 1
						temp = enemyboard.checkforhitormiss(boxx,boxy)
						if (temp == 9):
							pass
						else:
							playerattackboard.setpiece(temp,boxx,boxy)
							log_message('Player Move', playerattackboard.returnboard())

							if (temp == 7):
								printstatus(screen, 'Miss')
								miss.play(loops = 0)
							else:
								printstatus(screen, 'Hit')
								hit.play(loops = 0)

							if (checkforwin(playerattackboard)):
								place = -1
							else:
								temp_shipmessage = checkforshipsunk_multi(playerattackboard, temp, screen)
								if temp_shipmessage:
									shipmessage = temp_shipmessage

						gameboards = [playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard()]
						send_boards(s, gameboards)

				else:
					#waiting for other player to play, don't accept clicks
					multiinstructions(screen, 'Please wait for your opponent to play!', shipmessage, 200, 250)
					if (playernumber == 1):
						playerboard.setboard(boards[0])
						playerattackboard.setboard(boards[1])
						enemyboard.setboard(boards[2])
						enemyattackboard.setboard(boards[3])
					else:
						playerboard.setboard(boards[2])
						playerattackboard.setboard(boards[3])
						enemyboard.setboard(boards[0])
						enemyattackboard.setboard(boards[1])

				drawboards_multi(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2)

			if (place == 6):
			# waiting for server to signal game is started
				multiinstructions(screen, 'All Set!', 'Waiting for the other player to finish placing their ships...', 300, 20)

				if (status == 2):
					s.close()
					s = get_socket(ip)
					preamble = get_preamble(s)
					status, turn = preamble.split('.')
					status = int(status)
					turn = int(turn)
					boards = get_boards(s)
					if (playernumber == 1):
						playerboard.setboard(boards[0])
						enemyboard.setboard(boards[2])
					else:
						playerboard.setboard(boards[2])
						enemyboard.setboard(boards[0])
					place += 1


			if (place == 5):
				

				multiinstructions(screen, 'All Set!', 'Waiting for the other player to finish placing their ships...', 300, 20)
				if (turn == playernumber):
					print ("Player ready", playernumber)
					gameboards = [playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard()]
					send_boards(s, gameboards)
					place += 1

			if (place == -1):
				printstatus(screen, 'You win!')

			s.close()

		# If we're in gamemode 4, we're quitting
		if (gamemode == 4):
			screen.fill(color['black'])
			font = pygame.font.Font('resources/alphbeta.ttf', 70)
			thanks = font.render("Thanks for playing!", False, color['white'])
			thanksRect = thanks.get_rect()
			thanksRect.center = (400, 300)
			screen.blit(thanks, thanksRect)
			pygame.mixer.quit()
			pygame.display.update()
			print('Quitting :[')
			pygame.time.wait(1500)
			pygame.quit()
			sys.exit(0)
		# redraw screen       
		pygame.display.update()
		fpsClock.tick(60)
def makeObstacle(obstacleChoice, position, size, image, direction = 'left'):    
    if (obstacleChoice == 'Giant rock'):
        return AI.soccerBall(position, size, image, direction)
    else:
        return AI.Obstacle((0,0), (0,0), pygame.Surface((0, 0)))
Beispiel #45
0
 def useThunderDecision(self):
     decision = AI.useThunderAI(self.copy())
     return decision
Beispiel #46
0
                self.tactics.append(Tactics.Shove(self))
                self.tactics.append(Tactics.Charge(self))

        return AI.SuperAI.LostComponent(self, id)

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)

    def SmartZoneEvent(self, direction, id, robot, chassis):
        if id == 1 and self.weapons:
            if chassis:
                if direction == 1:
                    self.botinzone = 1
                if direction == -1:
                    self.botinzone = 0
        if id == 2:
            if robot > 0:
                if self.undered == 0:
                    self.memory[0] = 0
                    file("adaptiveAI.txt", "w").write(str(self.memory))
                    self.randcheck = 0
                    self.undered = 1
        return True


AI.register(Snow)
Beispiel #47
0
	def drawInterface():
		guesses = settings["guesses"]
		colourNo = settings["colours"]
		pegNo = settings["pegs"]
		colourList = settings["colourList"]
		
		# Draw interface frame layout
		#================================================
		frame = GUI.Frame(gameScr, relief=GUI.RAISED, borderwidth=1, bg="white")
		frame.pack(fill=GUI.BOTH, expand=1)
		
		# Draw game board
		#================================================
		hintWidth = 8 + int((pegNo + 1) / 2) * 12
		gridWidth = 50 * pegNo + hintWidth
		cvsGrid = GUI.Canvas(frame, width=gridWidth, height=((guesses + 1) * 50 + guesses), bg="white")
		cvsGrid.pack(side=GUI.RIGHT)
		gridPegs = []
		hintPegs = []
		row = 0
		while row < guesses + 1:
			gridPegs.append([])
			hintPegs.append([])
			col = 0
			while col < pegNo:
			
				# Draw rows of pegs
				#================================================
				xPos = 50 * col + 3
				yPos = 50 * row + row + 3
				gridPegs[row].append(cvsGrid.create_oval(xPos, yPos, xPos + 44, yPos + 44, fill="black"))
				
				# Draw hint pegs
				#================================================
				if row < guesses:
					hintX = 50 * pegNo + 6 + int(col / 2) * 12
					if col % 2 == 0:
						hintY = 50 * row + 15 + row
					else:
						hintY = 50 * row + 27 + row
					hintPegs[row].append(cvsGrid.create_oval(hintX, hintY, hintX + 8, hintY + 8, fill="black"))
					
				# Separate rows with lines
				#================================================
				if row != 0:
					cvsGrid.create_line(0, yPos - 3, gridWidth, yPos - 3)
				col += 1
			row += 1
		
		# Draw common interface buttons
		#================================================
		btnQuit = GUI.Button(gameScr, text="Quit Game", fg="red", command=quitGame)
		btnQuit.pack(side=GUI.RIGHT)
		btnMenu = GUI.Button(gameScr, text="Back to Menu", command=openMenu)
		btnMenu.pack(side=GUI.RIGHT)
		btnRestart = GUI.Button(gameScr, text="Restart Game", command=restartGame)
		btnRestart.pack(side=GUI.RIGHT)
		btnNew = GUI.Button(gameScr, text="New Game", command=newGame)
		btnNew.pack(side=GUI.RIGHT)
		
		# Draw human codebreaker buttons
		#================================================
		if settings["mode"] == 1:
			for i in range(0, colourNo):
				btnColour = GUI.Button(frame, text=colourList[i], bg=colourList[i], width=12, height=5, command=lambda a=colourList[i]: selectPeg(a))
				btnColour.pack(anchor=GUI.W)
			btnDel = GUI.Button(frame, text="Undo", width=12, command=undo)
			btnDel.pack(anchor=GUI.W)
			btnSave = GUI.Button(gameScr, text="Save Game", command=lambda a=settings, b=gameEnded: file.saveGame(a, b))
			btnSave.pack(side=GUI.RIGHT)
		
		# Draw CPU codebreaker buttons
		#================================================
		if settings["mode"] == 2:
			btnAI = GUI.Button(gameScr, text="Start AI", fg="blue", command=lambda a=settings, b=GUI, c=gameScr, d=gameEnded, e=selectPeg: AI.startAI(a, b, c, d, e))
			btnAI.pack(side=GUI.RIGHT)
		
		# Set up canvas objects for manipulation
		#================================================
		settings["grid"] = gridPegs
		settings["hints"] = hintPegs
		settings["canvas"] = cvsGrid
		
		# Resume a loaded game
		#================================================
		if load == True:
			loadGrid = loadData[0]
			loadHints = loadData[1]
			for row in range(0, settings["guesses"]):
				for col in range(0, settings["pegs"]):
					settings["canvas"].itemconfig(settings["grid"][row][col], fill=loadGrid[row][col])
					settings["canvas"].itemconfig(settings["hints"][row][col], fill=loadHints[row][col])
Beispiel #48
0
        while 1:
            for trigger in self.trigger2:
                self.Input(trigger, 0, 1)

            for i in range(0, 8):
                yield 0

    def LostComponent(self, id):
        # if we lose all our weapons, stop using the Engage tactic and switch to Shove
        if id in self.weapons: self.weapons.remove(id)

        if not self.weapons:
            tactic = [x for x in self.tactics if x.name == "Engage"]
            if len(tactic) > 0:
                self.tactics.remove(tactic[0])

                self.tactics.append(Tactics.Shove(self))
                self.tactics.append(Tactics.Charge(self))

        return AI.SuperAI.LostComponent(self, id)

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)


AI.register(OmniVSpinner)
Beispiel #49
0
def main(twoPlayer, playComputer, White, Black):
	black_player = chessboard.setBlack()
	white_player = chessboard.setWhite()
	players = chessboard.Players()
	for sprites in black_player.sprites():
		players.add(sprites)
	for sprites in white_player.sprites():
		players.add(sprites)
	black_pieces = black_player.sprites()
	white_pieces = white_player.sprites()
	Pieces = black_pieces + white_pieces 
	blackPiece = []
	whitePiece = []

	screen = pygame.display.set_mode((640, 640))
	gridsquare = chessboard.convert(pygame.Surface((80, 80)).convert_alpha())
	board = pygame.image.load('chessboard.gif').convert()
	board = pygame.transform.scale(board, (640, 640))
	
	clearBoard = pygame.image.load('chessboard.gif').convert()
	clearBoard = pygame.transform.scale(clearBoard, (640, 640))
	
	players.draw(board)
	screen.blit(board, (0, 0))
	grid = []
	newPiece = None
	for y in range(0, 640, 80):
		for x in range(0, 640, 80):
			occupied = False
			for piece in Pieces:
				if piece.xpos == x + 40 and piece.ypos == y + 40:
					occupied = True
					newPiece = piece
			if occupied:
				s = chessboard.Square(gridsquare, x, y, newPiece)
				#screen.blit(s.image, (x, y))
				grid.append(s)
			else:
				s = chessboard.Square(gridsquare, x, y, None)
				#screen.blit(s.image, (x, y))
				grid.append(s)
	pygame.display.update()
	checkmate = False
	stalemate = False
	turn = True
	whiteKing = None
	blackKing = None
	whiteCount = 0
	blackCount = 0
	
	while True:
		while not checkmate and not stalemate:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					sys.exit() 
			
			if twoPlayer:
				while turn and not checkmate and not stalemate:
					for event in pygame.event.get():
						if event.type == pygame.QUIT:
							sys.exit() 
					turn = user.movement_whitePlayer(white_player, event, grid, whitePiece, screen, board, clearBoard, black_player, players)

				black_pieces = black_player.sprites()
				if len(black_pieces) == 1:
					whiteCount += 1
			
				for black_piece in black_player:
					if type(black_piece) == chessboard.King:
						blackKing = black_piece		

				checkmate = blackKing.checkmate(black_player, white_player, grid)	
				stalemate = blackKing.stalemate(black_player, white_player, grid)	
				if whiteCount == 50:
					stalemate = True

				elif len(white_pieces) == 1 and len(black_pieces) == 1:
					stalemate = True

				while not turn and not checkmate and not stalemate:
					for event in pygame.event.get():
						if event.type == pygame.QUIT:
							sys.exit()
					turn = user.movement_blackPlayer(black_player, event, grid, blackPiece, screen, board, clearBoard, white_player, players)
					
				white_pieces = white_player.sprites()
				if len(white_pieces) == 1:
					blackCount += 1

				for white_piece in white_player:
					if type(white_piece) == chessboard.King:
						whiteKing = white_piece

				if not checkmate and not stalemate: 
					checkmate = whiteKing.checkmate(white_player, black_player, grid)
					stalemate = whiteKing.stalemate(white_player, black_player, grid)
				if blackCount == 50:
					stalemate = True

				elif len(white_pieces) == 1 and len(black_pieces) == 1:
					stalemate = True
			
			elif playComputer:
				if White:
					while turn and not checkmate and not stalemate:
						for event in pygame.event.get():
							if event.type == pygame.QUIT:
								sys.exit()
						turn = user.movement_whitePlayer(white_player, event, grid, whitePiece, screen, board, clearBoard, black_player, players)

					black_pieces = black_player.sprites()
					if len(black_pieces) == 1:
						whiteCount += 1
			
					for black_piece in black_player:
						if type(black_piece) == chessboard.King:
							blackKing = black_piece		

					checkmate = blackKing.checkmate(black_player, white_player, grid)	
					stalemate = blackKing.stalemate(black_player, white_player, grid)	
					if whiteCount == 50:
						stalemate = True

					elif len(white_pieces) == 1 and len(black_pieces) == 1:
						stalemate = True

					if not turn and not checkmate and not stalemate:
						for event in pygame.event.get():
							if event.type == pygame.QUIT:
								sys.exit()
						turn = AI.movement_blackPlayer(black_player, event, grid, screen, board, clearBoard, white_player, players)

					white_pieces = white_player.sprites()
					if len(white_pieces) == 1:
						blackCount += 1

					for white_piece in white_player:
						if type(white_piece) == chessboard.King:
							whiteKing = white_piece

					if not checkmate and not stalemate: 
						checkmate = whiteKing.checkmate(white_player, black_player, grid)
						stalemate = whiteKing.stalemate(white_player, black_player, grid)
					if blackCount == 50:
						stalemate = True

					elif len(white_pieces) == 1 and len(black_pieces) == 1:
						stalemate = True

					#turn = True
				
				elif Black:
					if turn and not checkmate and not stalemate:
						for event in pygame.event.get():
							if event.type == pygame.QUIT:
								sys.exit()
						turn = AI.movement_whitePlayer(white_player, event, grid, screen, board, clearBoard, black_player, players)

					black_pieces = black_player.sprites()
					if len(black_pieces) == 1:
						whiteCount += 1
			
					for black_piece in black_player:
						if type(black_piece) == chessboard.King:
							blackKing = black_piece		

					checkmate = blackKing.checkmate(black_player, white_player, grid)	
					stalemate = blackKing.stalemate(black_player, white_player, grid)	
					if whiteCount == 50:
						stalemate = True

					elif len(white_pieces) == 1 and len(black_pieces) == 1:
						stalemate = True

					while not turn and not checkmate and not stalemate:
						for event in pygame.event.get():
							if event.type == pygame.QUIT:
								sys.exit()
						turn = user.movement_blackPlayer(black_player, event, grid, blackPiece, screen, board, clearBoard, white_player, players)

					white_pieces = white_player.sprites()
					if len(white_pieces) == 1:
						blackCount += 1

					for white_piece in white_player:
						if type(white_piece) == chessboard.King:
							whiteKing = white_piece

					if not checkmate and not stalemate: 
						checkmate = whiteKing.checkmate(white_player, black_player, grid)
						stalemate = whiteKing.stalemate(white_player, black_player, grid)
					if blackCount == 50:
						stalemate = True

					elif len(white_pieces) == 1 and len(black_pieces) == 1:
						stalemate = True

		text = pygame.font.Font(None, 25)
		prompt = None
		if blackKing.checkmate(black_player, white_player, grid):
			prompt = text.render("White Won: Press Y to play again, Press N for menu", True, (0, 0, 255))
		elif whiteKing.checkmate(white_player, black_player, grid):
			prompt = text.render("Black Won: Press Y to play again, Press N for menu", True, (0, 0, 255))
		elif stalemate:
			prompt = text.render("Draw: Press Y to play again, Press N for menu", True, (0, 0, 255))
		players.clear(board, clearBoard)
		players.draw(board)
		screen.blit(board, (0, 0))
		select = False
		while not select:
			screen.blit(prompt, (0, 320))
			pygame.display.update()
			pygame.event.pump()
			keys = pygame.key.get_pressed()
			if keys[pygame.K_y]:
				players.clear(board, clearBoard)
				players.empty()
				black_player = chessboard.setBlack()
				white_player = chessboard.setWhite()
				for sprites in black_player.sprites():
					players.add(sprites)
				for sprites in white_player.sprites():
					players.add(sprites)
				black_pieces = black_player.sprites()
				white_pieces = white_player.sprites()
				Pieces = black_pieces + white_pieces 
				blackPiece = []
				whitePiece = []
				players.draw(board)
				screen.blit(board, (0, 0))
				grid = []
				newPiece = None
				for y in range(0, 640, 80):
					for x in range(0, 640, 80):
						occupied = False
						for piece in Pieces:
							if piece.xpos == x + 40 and piece.ypos == y + 40:
								occupied = True
								newPiece = piece
						if occupied:
							s = chessboard.Square(gridsquare, x, y, newPiece)
							#screen.blit(s.image, (x, y))
							grid.append(s)
						else:
							s = chessboard.Square(gridsquare, x, y, None)
							#screen.blit(s.image, (x, y))
							grid.append(s)
				pygame.display.update()
				checkmate = False
				stalemate = False
				turn = True
				whiteKing = None
				blackKing = None
				whiteCount = 0
				blackCount = 0
				select = True
			elif keys[pygame.K_n]:
				menu.main()
Beispiel #50
0
        self.max_turn_speed = 3

    def Activate(self, active):
        if active:
            if AI.SuperAI.debugging:
                self.debug = Gooey.Plain("watch", 0, 75, 100, 75)
                tbox = self.debug.addText("line0", 0, 0, 100, 15)
                tbox.setText("Throttle")
                tbox = self.debug.addText("line1", 0, 15, 100, 15)
                tbox.setText("Turning")
                tbox = self.debug.addText("line2", 0, 30, 100, 15)
                tbox.setText("")
                tbox = self.debug.addText("line3", 0, 45, 100, 15)
                tbox.setText("")

        return AI.SuperAI.Activate(self, active)

    def LostComponent(self, id):
        #print "Lost Component!"
        return AI.SuperAI.LostComponent(self, id)

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)


AI.register(Pinner)
Beispiel #51
0
        self.last_move = p.move(self.board, self.last_move.x, self.last_move.y)
        x, y = self.last_move.x, self.last_move.y
        bx, by = self.last_move.boardx, self.last_move.boardy
        self.mini[x][y] = '.'
        self.mark(self.board[bx][by])

        print 'TURN: %d' % self.turn
        print self.board
        print '\nNext move:\n%s' % self.mini
        print '\n\n'

        #check win
        if self.check_win() != BLANK:
            print self.check_win()
            self.gameover = True
            self.winner = self.check_win()
        self.turn += 1
        self.mini.clear()

    def check_win(self):
        return self.board.check_win()


bb = big_board()
bb.randomize()
#bb.check_win()
#print bb

g = game(AI.random_bot(), AI.center_bot())
g.start_game(delay=0.1)
Beispiel #52
0
                if self.wiggletimer >= 8:
                    self.wiggletimer = -8
            # fire everything we have as a last-ditch effort if we're still not free after 5 seconds
            if self.srimechtimer >= 20:
                self.srispintimer += 1
                for trigger in self.triggers:
                    self.Input(trigger, 0, 1)
                for trigger in self.trigger2:
                    self.Input(trigger, 0, 1)
                if self.srispintimer < 7:
                    self.Input("Spin1", 0, -100)
                    self.Input("Spin2", 0, -100)
                if self.srispintimer >= 7:
                    self.Input("Spin1", 0, 100)
                    self.Input("Spin2", 0, 100)
                if self.srispintimer == 15:
                    self.srispintimer = 0
        else:
            self.srimechtimer = 0
            self.srispintimer = 0
            self.wiggletimer = -8

    def LostComponent(self, id):
        # if we lose all our weapons, ignore it because ram tactics in reverse don't work well.
        if id in self.weapons: self.weapons.remove(id)

        return AI.SuperAI.LostComponent(self, id)


AI.register(SwitchDirEcoOmni)
Beispiel #53
0
 def __init__(self):
     #
     self.UsePushStart = True
     self.PushStartDepth = 0.5
     self.Depth = 1
     #
     self.DataTimeout = 2
     self.MinProgress = 0.5
     self.MinProgressSamples = 5
     #
     self.FirstHeading = AI.OptionWithMeta(90,
                                           units=" degrees",
                                           opt_type=Bearing)
     self.TurnDistance = AI.OptionWithMeta(
         25, docstring="Distance from wall at which to turn", units="m")
     self.TDError = AI.OptionWithMeta(
         1, docstring="Acceptable error in distance", units="m")
     self.TDProportion = 5
     self.TDClamp = AI.OptionWithMeta(
         30,
         docstring="Highest speed at which to travel (pre-turning)",
         opt_type=MotorValue)
     self.TDTimeout = AI.OptionWithMeta(
         0, docstring="Time to travel before giving up.", units="s")
     #
     self.SecondHeading = AI.OptionWithMeta(0,
                                            units=" degrees",
                                            opt_type=Bearing)
     self.SecondSpeed = AI.OptionWithMeta(
         100,
         docstring="Speed to travel after turning",
         opt_type=MotorValue)
     self.SecondTime = AI.OptionWithMeta(
         10, docstring="Time to travel, after turning", units="s")
     #
     self.ThirdHeading = AI.OptionWithMeta(180,
                                           units=" degrees",
                                           opt_type=Bearing)
     self.StopDistance = AI.OptionWithMeta(
         2,
         docstring="Distance from back wall at which to finally stop.",
         units="m")
     self.SDError = AI.OptionWithMeta(
         1, docstring="Acceptable error in distance.", units="m")
     self.SDProportion = 5
     self.SDClamp = AI.OptionWithMeta(
         30,
         docstring="Highest speed at which to travel in final section.",
         opt_type=MotorValue)
     self.SDTimeout = AI.OptionWithMeta(
         0, docstring="Time to travel before giving up.", units="s")
Beispiel #54
0
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)
            elif id == 4: self.debug.get("line4").setText(string)
            elif id == 5: self.debug.get("line5").setText(string)
            elif id == 6: self.debug.get("line6").setText(string)
            elif id == 7: self.debug.get("line7").setText(string)
            elif id == 8: self.debug.get("line8").setText(string)
            elif id == 9: self.debug.get("line9").setText(string)
            elif id == 10: self.debug.get("line10").setText(string)


    def ShiftConditionOk(self):
        #test condition to turn servo
        # true : turn servo, may 'restart' different counter for next test
        # false : condition not meet.
        # in this version, turn condition depends of timer.
        #return False
        self.servoCountDown -= 1    # count down
        if self.servoCountDown <= 0 : #Time to shift !
            self.servoCountDown  =    self.servoTimer
            return True
        else:
            return False


AI.register(ShiftWeapon3)

Beispiel #55
0
                    if self.GetPistonPosition(linacu) < -0.05:
                        self.Input(self.trigger + str(n), 1, -100)
                        self.Input(self.trigger + str(n), 0, 0)
                        self.DebugString(7, "Descend")
                    else:
                        self.Input(self.trigger + str(n), 1, 0)
                        self.DebugString(7, "Stop")
                n += 1

        self.DebugString(
            5,
            str(self.GetInputStatus(self.trigger, 0)) + " " +
            str(self.GetInputStatus(self.trigger, 1)))
        return bReturn

    def DebugString(self, id, string):
        if self.debug:
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)
            elif id == 4: self.debug.get("line4").setText(string)
            elif id == 5: self.debug.get("line5").setText(string)
            elif id == 6: self.debug.get("line6").setText(string)
            elif id == 7: self.debug.get("line7").setText(string)
            elif id == 8: self.debug.get("line8").setText(string)
            elif id == 9: self.debug.get("line9").setText(string)


AI.register(Forklift)
Beispiel #56
0
            if id == 0: self.debug.get("line0").setText(string)
            elif id == 1: self.debug.get("line1").setText(string)
            elif id == 2: self.debug.get("line2").setText(string)
            elif id == 3: self.debug.get("line3").setText(string)

    def SmartZoneEvent(self, direction, id, robot, chassis):
        if id == 1 and self.weapons:
            if robot > 0:
                if direction == 1:
                    self.compinzone = 1
                    if chassis:
                        self.botinzone = 1
                if direction == -1:
                    self.compinzone = 0
                    if chassis:
                        self.botinzone = 0
        elif id == 2 and not self.weapons and self.sweapons:
            if robot > 0:
                if direction == 1:
                    self.compinzone = 1
                    if chassis:
                        self.botinzone = 1
                if direction == -1:
                    self.compinzone = 0
                    if chassis:
                        self.botinzone = 0
        return True


AI.register(SwitchWepPopup)
Beispiel #57
0
def runGame(MAP_NUMBER):
    '''
        Set up initial player object.
        This object contains the following keys:
            surface: the image of the player
            facing: the direction the player is facing
            x: the left edge coordinate of the player on the window
            y: the top edge coordinate of the player on the window
            width: the width of the player image
            height: the height of the player image
    '''
    # Initialize the player object
    p = player.Player(
        (HALF_WINWIDTH,HALF_WINHEIGHT),
        (PLAYER_WIDTH,PLAYER_HEIGHT),
        IMAGESDICT['player']
        )

    # initialize camera variables
    cam_x = HALF_WINWIDTH
    cam_y = HALF_WINHEIGHT

    ROCK_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['rock'], ROCK_BALL_SIZE)
    ROCK_IMG_SCALE_2 = pygame.transform.smoothscale(IMAGESDICT['rock2'], ROCK_BALL_SIZE)
    ROCK_IMG_SCALE_3 = pygame.transform.smoothscale(IMAGESDICT['rock3'], ROCK_BALL_SIZE)
    ROCK_IMG_SCALE_4 = pygame.transform.smoothscale(IMAGESDICT['rock4'], ROCK_BALL_SIZE)
    BANANA_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['banana_peel'], BANANA_PEEL_SIZE)
    SPIKES_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['spikes'], SPIKES_SIZE)
    SNAKE_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['snake'], SNAKE_SIZE)
    SNAKE_IMG_SCALE_2 = pygame.transform.smoothscale(IMAGESDICT['snake2'], SNAKE_SIZE_2)
    BIRD_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['bird'], BIRD_SIZE)
    BIRD_IMG_SCALE_2 = pygame.transform.smoothscale(IMAGESDICT['bird2'], BIRD_SIZE)
    SPIDER_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['spider'], SPIDER_SIZE)
    SPIDER_IMG_SCALE_2 = pygame.transform.smoothscale(IMAGESDICT['spider2'], SPIDER_SIZE)
    LOG_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['log'], LOG_SIZE)
    MUD_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['mud'], MUD_SIZE)
    MUD_IMG_SCALE_2 = pygame.transform.smoothscale(IMAGESDICT['mud2'], MUD_SIZE_2)
    TIDAL_WAVE_IMG_SCALE = pygame.transform.smoothscale(IMAGESDICT['tidalWave'], TIDAL_WAVE_SIZE)

    # Animations for various AI
    snakeAnimation = [SNAKE_IMG_SCALE, SNAKE_IMG_SCALE_2]
    birdAnimation = [BIRD_IMG_SCALE, BIRD_IMG_SCALE_2]
    spiderAnimation = [SPIDER_IMG_SCALE, SPIDER_IMG_SCALE_2]
    rockAnimation = [ROCK_IMG_SCALE, ROCK_IMG_SCALE_2, ROCK_IMG_SCALE_3, ROCK_IMG_SCALE_4]
    mudAnimation = [MUD_IMG_SCALE, MUD_IMG_SCALE_2]

    giantRock = AI.giantRock(
        ROCK_BALL_POSITION,
        ROCK_BALL_SIZE,
        ROCK_IMG_SCALE,
        LEFT
        )

    # For storing our obstacles
    obstacleObjs = []

    # obstacleObjs.append(makeObstacle('Giant rock', ROCK_BALL_POSITION, ROCK_BALL_SIZE, ROCK_IMG_SCALE))
    # obstacleObjs.append(makeObstacle('Tidal wave', TIDAL_WAVE_POSITION, TIDAL_WAVE_SIZE, TIDAL_WAVE_IMG_SCALE))
    '''
    obstacleObjs.append(makeObstacle('Giant rock', ROCK_BALL_POSITION, ROCK_BALL_SIZE, ROCK_IMG_SCALE))
    obstacleObjs.append(makeObstacle('Spikes', SPIKES_POSITION, SPIKES_SIZE, SPIKES_IMG_SCALE))
    obstacleObjs.append(makeObstacle('Snake', SNAKE_POSITION, SNAKE_SIZE, SNAKE_IMG_SCALE))
    obstacleObjs.append(makeObstacle('Bird', BIRD_POSITION, BIRD_SIZE, BIRD_IMG_SCALE))
    obstacleObjs.append(makeObstacle('Spider', SPIDER_POSITION, SPIDER_SIZE, SPIDER_IMG_SCALE))
    obstacleObjs.append(makeObstacle('Log', LOG_POSITION, LOG_SIZE, LOG_IMG_SCALE))
    obstacleObjs.append(makeObstacle('Banana peel', BANANA_PEEL_POSITION, BANANA_PEEL_SIZE, BANANA_IMG_SCALE))
    obstacleObjs.append(makeObstacle('Mud', MUD_POSITION, MUD_SIZE, MUD_IMG_SCALE))
    '''
    ballImage = pygame.transform.scale(IMAGESDICT['rock'], ROCK_BALL_SIZE)

    slipTimeElapsed = BANANA_PEEL_INIT_SLIP_TIME

    # Initialize moving variables
    moveLeft  = False
    moveRight = False
    moveUp    = False
    moveDown  = False

    pygame.mixer.init()
    if MAP_NUMBER == 0:
        sprite_layers, player_sprite, player_layer, renderer = initializeLevel('ForestLevel.tmx',PLAYER_LAYER,p)        
        pygame.mixer.music.load('Sounds/Level2.mp3')
        obstacleObjs.append(makeObstacle('Giant rock', ROCK_BALL_POSITION, ROCK_BALL_SIZE, ROCK_IMG_SCALE))
    elif MAP_NUMBER == 1:        
        sprite_layers, player_sprite, player_layer, renderer = initializeLevel('SandLevel.tmx',PLAYER_LAYER,p)
        pygame.mixer.music.load('Sounds/NeroNewLifeCut.mp3')
        obstacleObjs.append(makeObstacle('Tidal wave', TIDAL_WAVE_POSITION, TIDAL_WAVE_SIZE, TIDAL_WAVE_IMG_SCALE))
        
    pygame.mixer.music.play(0)        
    frame_count = 0

    while True: # main game loop

        # update player sprite
        sprite_layers[PLAYER_LAYER].remove_sprite(player_sprite)
        player_sprite = p.get_sprite()
        sprite_layers[PLAYER_LAYER].add_sprite(player_sprite)

        # reset applicable variables
        step_x = 0
        step_y = 0

        # This loop will handle all of the player input events
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            elif event.type == KEYDOWN:
                if event.key in (K_UP, K_w, K_SPACE):
                    moveDown = False
                    moveUp = True
                elif event.key in (K_DOWN, K_s):
                    moveUp = False
                    moveDown = True
                elif event.key in (K_LEFT, K_a):
                    moveRight = False
                    moveLeft = True
                elif event.key in (K_RIGHT, K_d):
                    moveLeft = False
                    moveRight = True

            elif event.type == KEYUP:
                # stop moving the player
                if event.key in (K_LEFT, K_a):
                    moveLeft = False
                elif event.key in (K_RIGHT, K_d):
                    moveRight = False
                elif event.key in (K_UP, K_w, K_SPACE):
                    moveUp = False
                elif event.key in (K_DOWN, K_s):
                    moveDown = False
                elif event.key == K_ESCAPE:
                        terminate()
        '''
            All the jumping and gravity is handled here.
            If the player is jumping we move them up, otherwise they are moving down (gravity).
            We can alter how quickly the player jumps by altering the moverate or jump duration.
        '''
        if p.isJumping():
            t = pygame.time.get_ticks() - jumpingStart
            if t > JUMPING_DURATION:
                p.jumping = False
                p.change_sprite(
                IMAGESDICT['jump1']
                )
            elif t > JUMPING_DURATION / 2:
                p.change_sprite(
                IMAGESDICT['jump4']
                )
            if t < JUMPING_DURATION and t > 0:
                step_y -= MOVERATE
        elif not p.isJumping():
            step_y += MOVERATE

        # actually move the player
        if moveLeft:
            step_x -= MOVERATE
        if moveRight:
            step_x += MOVERATE
            if not p.isJumping():
                if frame_count is 20:
                    p.change_sprite(
                    IMAGESDICT['run1']
                    )
                elif frame_count is 40:
                    p.change_sprite(
                    IMAGESDICT['run2']
                    )
                elif frame_count is 60:
                    p.change_sprite(
                    IMAGESDICT['run3']
                    )
                elif frame_count is 80:
                    p.change_sprite(
                    IMAGESDICT['run4']
                    )
                if frame_count > 80:
                    frame_count = 0
        if moveUp:
            if not p.isJumping() and p.isOnGround():
                p.jumping = True
                p.onGround = False
                p.change_sprite(
                IMAGESDICT['jump2']
                )
                jumpingStart = pygame.time.get_ticks()
                step_y -= 60               


        if check_game_end(p,step_x,step_y,sprite_layers[DEATH_LAYER]):
            print 'Collided with death layer'
        elif check_game_end(p,step_x,step_y,sprite_layers[WIN_LAYER]):
            print 'Collided with win layer'
        elif p.get_rect().left <= (cam_x-HALF_WINWIDTH):
            print 'Collided with left end of screen'
        step_x, step_y = check_collision(p,step_x,step_y,sprite_layers[COLL_LAYER])



        # Apply the steps to the player and the player rect
        p.x += step_x
        p.y += step_y

        player_sprite.rect.midbottom = (p.x, p.y)

        # Set the new camera position
        renderer.set_camera_position_and_size(cam_x, cam_y, WINWIDTH, WINHEIGHT)

        # Draw the background
        SCREEN.fill((0, 0, 0))

        # render the map including the player
        for sprite_layer in sprite_layers:
            if sprite_layer.is_object_group:
                # we dont draw the object group layers
                # you should filter them out if not needed
                continue
            else:
                renderer.render_layer(SCREEN, sprite_layer)

        # Collision debugging
        # pygame.draw.rect(SCREEN, (0, 0, 0), (p.x, p.y, p.width, p.height))
        # pygame.draw.rect(SCREEN, (0, 0, 0), (obstacleObjs[0].xPos, obstacleObjs[0].yPos, obstacleObjs[0].width, obstacleObjs[0].height))
        # pygame.draw.rect(SCREEN, (255, 0, 255), (obstacleObjs[1].xPos, obstacleObjs[1].yPos, obstacleObjs[1].width, obstacleObjs[1].height))

        obstacleChoice = random.randint(1, 4)

        if (cam_x % 100 == 0):
            if (obstacleChoice == 1):
                obstacleObjs.append(makeObstacle('Bird', BIRD_POSITION, BIRD_SIZE, BIRD_IMG_SCALE))
            elif (obstacleChoice == 2):
                obstacleObjs.append(makeObstacle('Snake', SNAKE_POSITION, SNAKE_SIZE, SNAKE_IMG_SCALE))
            elif (obstacleChoice == 3):
                obstacleObjs.append(makeObstacle('Banana peel', BANANA_PEEL_POSITION, BANANA_PEEL_SIZE, BANANA_IMG_SCALE))
            else:
                obstacleObjs.append(makeObstacle('Spider', SPIDER_POSITION, SPIDER_SIZE, SPIDER_IMG_SCALE))
                        
        '''
            We need specific drawing cases for different obstacles,
            since every obstacle could have different methods
            defined for drawing executions. This is what we do
            below.
        '''
        '''
            Here, we have backwards-list checking to avoid a common object
            deletion mistake.
        '''
        
        for i in range(len(obstacleObjs) - 1, -1, -1):
            # Player collision checking with the obstacles.
            pygame.draw.rect(SCREEN, (0, 0, 0), (p.x, p.y, p.width, p.height))
            # if p.isTouching(obstacleObjs[i].xPos, obstacleObjs[i].yPos, obstacleObjs[i].yPos + obstacleObjs[i].height):
                # soundObj = pygame.mixer.Sound('Sounds/Spikes.wav')
                # soundObj.play()
            # Collision boundary drawing (for debug)
            # pygame.draw.rect(SCREEN, GRAY_1, (obstacleObjs[i].xPos, obstacleObjs[i].yPos, obstacleObjs[i].width, obstacleObjs[i].height))
            # Checking if a particular object is a rock.
            if isinstance(obstacleObjs[i], AI.giantRock):
                obstacleObjs[i].setSpeed(ROCK_SPEED)
                obstacleObjs[i].doGiantRockAction(p, floorY() - 40, ROCK_GRAVITY, WINWIDTH)
                # CHOPPED_ROCK = pygame.transform.rotozoom(obstacleObjs[i].image, obstacleObjs[i].giantRockRotate(ROCK_ROTATE_INCREMENT), 2.0)
                # CHOPPED_ROCK = pygame.transform.scale(CHOPPED_ROCK, obstacleObjs[i].image.get_size())
                SCREEN.blit(rockAnimation[obstacleObjs[i].animateToNext(2, 8)], obstacleObjs[i].get_rect())
            # Checking if a particular object is a banana peel.
            elif isinstance(obstacleObjs[i], AI.bananaPeel):
                obstacleObjs[i].setHoriAndVertRiseSpeeds(BANANA_PEEL_HORI_RISE_SPEED, BANANA_PEEL_VERT_RISE_SPEED)
                obstacleObjs[i].doBananaPeelAction(p, floorY() + 180, ROCK_GRAVITY, BANANA_PEEL_TIME_TO_RISE, WINWIDTH)
                obstacleObjs[i].move(-CAM_X_INCREMENT, 0)
                BANANA_IMG_ROT = pygame.transform.rotate(obstacleObjs[i].image, obstacleObjs[i].slipRotate(floorY(), BANANA_ROTATE_FIRST, BANANA_ROTATE_SECOND))
                blit_alpha(SCREEN, BANANA_IMG_ROT, obstacleObjs[i].get_rect(), obstacleObjs[i].doFadeOutBananaPeel(BANANA_PEEL_FADE_DECREMENT))
                # Has the banana peel faded to 0 after being slipped on?
                # (This check has been validated)
                if obstacleObjs[i].getBananaPeelFadeAmount() <= 0:
                    del obstacleObjs[i]
            # Checking if a particular object represents the spikes
            # elif isinstance(obstacleObjs[i], AI.spikes):
                # obstacleObjs[i].spikeBump(p)
                # SCREEN.blit(obstacleObjs[i].image, obstacleObjs[i].get_rect())
            # Checking if the object is a tree log
            elif isinstance(obstacleObjs[i], AI.treeLog):
                obstacleObjs[i].collidedHardWith(p)
                SCREEN.blit(obstacleObjs[i].image, obstacleObjs[i].get_rect())
            # Checking if the object is a snake
            elif isinstance(obstacleObjs[i], AI.snake):
                obstacleObjs[i].setFrameRate(SNAKE_FRAME_RATE)
                if (obstacleObjs[i].doSnakeAction(SNAKE_SPEED)):
                    SCREEN.blit(snakeAnimation[0], obstacleObjs[i].get_rect())
                else:
                    SCREEN.blit(snakeAnimation[1], obstacleObjs[i].get_rect())
                if (obstacleObjs[i].xPos + obstacleObjs[i].width < 0):
                    del obstacleObjs[i]
            # Checking if the object is a bird
            elif isinstance(obstacleObjs[i], AI.bird):
                obstacleObjs[i].setFrameRate(BIRD_FRAME_RATE)
                if (obstacleObjs[i].doBirdAction(BIRD_SPEED)):
                    SCREEN.blit(birdAnimation[0], obstacleObjs[i].get_rect())
                else:
                    SCREEN.blit(birdAnimation[1], obstacleObjs[i].get_rect())
                if (obstacleObjs[i].xPos + obstacleObjs[i].width < 0):
                    del obstacleObjs[i]
            # Checking if the object is a spider
            elif isinstance(obstacleObjs[i], AI.spider):
                obstacleObjs[i].setFrameRate(SPIDER_FRAME_RATE)
                obstacleObjs[i].move(-CAM_X_INCREMENT, 0)
                if (obstacleObjs[i].doSpiderAction(SPIDER_SPEED)):
                    SCREEN.blit(spiderAnimation[0], obstacleObjs[i].get_rect())
                else:
                    SCREEN.blit(spiderAnimation[1], obstacleObjs[i].get_rect())
                obstacleObjs[i].setWebStringRect(obstacleObjs[i].xPos + obstacleObjs[i].width/2, obstacleObjs[i].yPos - 50, 2, 50) 
                pygame.draw.rect(SCREEN, GRAY_1, obstacleObjs[i].getWebStringRect())                
            # Checking if the object represents the mud
            elif isinstance(obstacleObjs[i], AI.mud):
                obstacleObjs[i].setFrameRate(MUD_FRAME_RATE)
                if (obstacleObjs[i].doMudAction(MUD_FRAME_RATE)):
                    SCREEN.blit(mudAnimation[0], obstacleObjs[i].get_rect())
                else:
                    SCREEN.blit(mudAnimation[1], obstacleObjs[i].get_rect())
            # Default for drawing any other obstacles
            elif isinstance(obstacleObjs[i], AI.tidalWave):
                SCREEN.blit(obstacleObjs[i].image, obstacleObjs[i].get_rect())        

        cam_x += CAM_X_INCREMENT        
        frame_count += 1

        pygame.display.update()
        FPSCLOCK.tick()
Beispiel #58
0
                    sendmsg(channel,stats.runCommands(channel,nick,commandChar,ircmsg,ircsock,hostmask))
            except: pass
            
            if Trivial.birthday(nick,BWBellairsTrue) != False:
                for i in Trivial.birthday(nick,BWBellairsTrue):
                    sendmsg(channel,i)
                BWBellairsTrue = False   
                    
            if config.config.enableQuizCheat:
                a = QuizSolver.phraseChat(ircmsg,nick)
                sendmsg(channel,a)
            
            #TEMP TEST!!
            if ircmsg.split(" :",1)[1].startswith("bowserbot") or ircmsg.lower().split(" :",1)[1].startswith(botnick.lower()):
                if "aegisserver2" not in ircmsg.lower():
                    AI.phraseText(ircmsg.lower().split(" :",1)[1].replace('bowserbot','').replace(botnick.lower(),""),channel,nick,hostmask,ircsock,botnick)
            
            
        
        #Auto rejoin
        for channel in channels:
            if ircmsg.lower().find("kick " + channel.lower() + " " + botnick.lower()) != -1:
                joinchan(channel)
                time.sleep(1)
                joinchan(channel)
            if ircmsg.lower().find("part " + channel.lower()) != -1:
                joinchan(channel)
                time.sleep(1)
                joinchan(channel)