コード例 #1
0
ファイル: player.py プロジェクト: kejndan/BattleShip
class Player(object):
    def __init__(self, name, queue, s_z):
        self.player_name = name
        self.queue = queue
        self.field = Field(s_z)
        self.field_enemy = Field(s_z)
        self.killed = 0
        self.log = []

    def check_win(self):
        if self.killed == Field.num_ships:
            return 1

    def attack(self, enemy, shoot):
        result = 'H'
        self.field.draw(self.player_name)
        self.field_enemy.draw(enemy.player_name)
        while result != 'M' and self.killed < Field.num_ships:
            point = str(
                input('Shoots by {}.\n'
                      'Enter the coordinates\n'.format(self.player_name)))
            result = shoot.hit(self.field_enemy.field, enemy.field.field,
                               ord(point[0]) - ord('A'),
                               int(point[1]) - 1)
            self.field_enemy.draw(enemy.player_name)
            if result == 'K':
                self.killed += 1
コード例 #2
0
ファイル: game.py プロジェクト: KseniaSycheva/TreasureHunter
class Game:
    def __init__(self, field_width):
        self.screen = pygame.display.set_mode(SIZE)
        self.field = Field(field_width, field_width)
        self.field.generate_blocks()
        """self.borders = pygame.sprite.Group()
        self.horizontal_borders = pygame.sprite.Group()
        self.vertical_borders = pygame.sprite.Group()
        Border(0, 0, WIDTH, 0, self.horizontal_borders, self.vertical_borders, self.borders)
        Border(0, 0, 0, HEIGHT, self.horizontal_borders, self.vertical_borders, self.borders)
        Border(0, HEIGHT, WIDTH, HEIGHT, self.horizontal_borders, self.vertical_borders, self.borders)
        Border(WIDTH, 0, WIDTH, HEIGHT, self.horizontal_borders, self.vertical_borders, self.borders)"""

    def update(self):
        self.screen.fill('black')
        bubble_sprites.update()
        self.field.draw(self.screen)
        bubble_sprites.draw(self.screen)

    def create_bubbles(self):
        n_bubbles = random.randrange(1, 5)
        for _ in range(n_bubbles):
            Bubble(32)
コード例 #3
0
def calc():
    from field import Field
    g = Lotto()
    g.load("lotto.csv", ['SAT'])
    field = Field()
    field.draw(g)
    m = []
    for b, v in field.balls.items():
        m.append(v.drawnWith)
    s = '  : '
    for a in range(45):
        s += '{:2.0f} '.format(a + 1)
    print(s)
    for a in range(45):
        s = '{:2.0f}  '.format(a + 1)
        for b in range(45):
            if a == b:
                s += '   '
            else:
                s += '{:2.0f} '.format(m[a][b])
        print(s)

    for i in range(1, 46):
        print(field.balls[i])
コード例 #4
0
ファイル: game.py プロジェクト: music960633/PyTetris
class Game1pInvisible(Game):
  def __init__(self):
    Game.__init__(self)
    self.field = Field(10, 20, invisible = True)
    
  def start(self):
    while True:
      # restart
      self.field.restart()
      while True:
        # display
        self.screen.fill(BLACK)
        self.screen.blit(self.field.draw(), (20, 20))
        pygame.display.flip()
        # routine work
        quit, restart = Game.routine(self)
        if quit: return
        if restart: break
コード例 #5
0
ファイル: game.py プロジェクト: music960633/PyTetris
class Game1p4wide(Game):
  def __init__(self):
    Game.__init__(self)
    self.field = Field(4, 20)

  def start(self):
    while True:
      # restart
      self.field.restart()
      self.field.recieveAttack(1)
      self.field.clearAttack()
      while True:
        # display
        self.screen.fill(BLACK)
        self.screen.blit(self.field.draw(), (20, 20))
        pygame.display.flip()
        # routine work
        quit, restart = Game.routine(self)
        if quit: return
        if restart: break
コード例 #6
0
ファイル: game.py プロジェクト: Igordr1999/pacman
class Game(Tab):
    """Tab class that represents logic of a game"""
    def __init__(self, wrapper):
        super(Game, self).__init__(wrapper)
        self.type_scores = {'s': 10, 'e': 50}
        self.field = Field('1_lvl.txt')
        self.units = Units(self)
        self.scores = Scores(position=Vector(
            10,
            self.field.get_size().to_abs().y + 5),
                             level=1)

    def set_hs(self, hs):
        # type: (int) -> None
        """Set highscore and write it to file"""
        pass

    def start(self):
        Input.reset()
        self.field = Field(str(self.scores.level) + '_lvl.txt')
        self.units.add_pacman(self.field.get_pacman_spawn())
        self.units.add_ghosts(self.field.get_ghosts_spawn())
        Music.play('bg', .1)

    def pacman_die(self):
        if self.scores.lives >= 1:
            self.scores.lives -= 1
            if self.scores.lives:
                Music.play('go')
                self.units.reset()
                Input.reset()
            else:
                self.game_over()

    def add_score(self, value):
        # type: (int) -> int
        return self.scores.add_score(value)

    def next_level(self):
        # type: () -> None
        """Switch to next level"""
        self.scores.level += 1
        Input.reset()
        self.field = Field(str(self.scores.level) + '_lvl.txt')
        self.units.add_pacman(self.field.get_pacman_spawn())
        self.units.add_ghosts(self.field.get_ghosts_spawn())
        Music.play('bg', .1)

    def get_size(self):
        # type: () -> Vector
        """Return size vector of tab"""
        return Vector(
            self.field.get_size().to_abs().x,
            self.field.get_size().to_abs().y + self.scores.get_size().y)

    def update(self):
        # type: () -> None
        """Update the objects"""
        if self.field.seed_count <= 0:  # все зерна съедены
            self.next_level()
        else:
            if self.scores.score:
                if self.field.get_door_status() == 1:
                    self.field.get_cell(self.field.door).set_type('0')
                for g in (self.units.blinky, self.units.pinky,
                          self.units.clyde):
                    if not g.get_mode():
                        g.set_mode(1)
                if not self.units.inky.get_mode(
                ) and self.scores >= 30 * self.type_scores.get('s'):
                    self.units.inky.set_mode(1)
            self.units.pacman.set_buffer_direction(Input.key_direction)
            self.units.move()

    def game_over(self):
        Music.stop('bg')
        Music.play('go')
        self.wrapper.set_current_tab('mainmenu')
        self.wrapper.add_tab('game', Game(self.wrapper))

    def draw(self):
        # type: () -> None
        """Draw all objects"""
        self.field.draw()
        self.units.draw()
        self.scores.draw()
コード例 #7
0
ファイル: match.py プロジェクト: andru255/pyNekketsu
class Match(object):
    snd_whistle = pygame.mixer.Sound("data/sound/etw/fischiolungo.wav")

    #TODO: add field choice
    def __init__(self, teamA, teamB):
        self.goal_image = pygame.image.load("data/goal.png")
        self.start_image = pygame.image.load("data/start.png")
        self.message_drawing_time = 50
        self.message_image = self.start_image
        self.clock_image = pygame.image.load("data/clock.png")
        self.is_finished = False
        self.teamA_filename = teamA
        self.teamB_filename = teamB

        self.match_time = 0
        self.human_players = [-1, 0,
                              0]  #max two players, player num 0 does not exist
        self.pause = False
        self.ball = Ball()
        self.player_list = []
        self.team = {}  #

        #read xml file to get colors !
        self.team[-1] = Team(self.teamA_filename)
        self.team[1] = Team(self.teamB_filename)

    def init(self,
             nbr_players_human_teamA,
             nbr_players_teamA,
             nbr_players_human_teamB,
             nbr_players_teamB,
             difficulty=8,
             length=60):
        Player_CPU.difficulty = difficulty
        Player_GK.difficulty = difficulty

        self.goal_image = pygame.image.load("data/goal.png")
        self.start_image = pygame.image.load("data/start.png")
        self.message_drawing_time = 50
        self.message_image = self.start_image
        self.clock_image = pygame.image.load("data/clock.png")
        self.is_finished = False

        self.match_time = length
        self.human_players = [-1, 0,
                              0]  #max two players, player num 0 does not exist
        self.pause = False
        self.ball = Ball()
        self.player_list = []

        human_players_teamA = []
        human_players_teamB = []
        if (nbr_players_human_teamA > 0):
            human_players_teamA.append(1 + len(human_players_teamA) +
                                       len(human_players_teamB))
        if (nbr_players_human_teamA > 1):
            human_players_teamA.append(1 + len(human_players_teamA) +
                                       len(human_players_teamB))
        if (nbr_players_human_teamB > 0):
            human_players_teamB.append(1 + len(human_players_teamA) +
                                       len(human_players_teamB))
        if (nbr_players_human_teamB > 1):
            human_players_teamB.append(1 + len(human_players_teamA) +
                                       len(human_players_teamB))

        self.field = Field(self.team[-1].top_color, self.team[-1].bottom_color,
                           self.team[1].top_color, self.team[1].bottom_color)
        self.cam = Camera(self.field)

        self.team[-1].create_from_xml(-1, nbr_players_teamA,
                                      human_players_teamA, self)
        self.player_list += self.team[-1].players

        self.team[1].create_from_xml(1, nbr_players_teamB, human_players_teamB,
                                     self)
        self.player_list += self.team[1].players

        print("Match starts")

    def update(self):
        Inputs.readkeys()  #read all the actual keys
        if (Inputs.player_just_Start[1] or Inputs.player_just_Start[2]):
            self.pause = not self.pause
            if (self.match_time <= 0):
                self.is_finished = True
            else:
                if (configuration["sound"] == "on"):
                    Match.snd_whistle.play()

        if (not self.pause):
            if (self.message_drawing_time < 10):
                if (self.message_drawing_time > 0):
                    self.message_drawing_time -= 1 * configuration["delta_time"]
                    if (self.message_drawing_time > 5) and (
                            self.message_image == self.start_image):  #kick off
                        if (configuration["sound"] == "on"):
                            Match.snd_whistle.play()
                        self.message_drawing_time = 5

                if (self.match_time > 0):  #when time is out, players stop
                    self.match_time -= 1.0 / 30 * configuration[
                        "delta_time"]  #30 FPS
                    self.team[-1].update(self)
                    self.team[1].update(self)
                if (-1 < self.match_time < 0):
                    if (configuration["sound"] == "on"):
                        Match.snd_whistle.play()

                self.ball.update(self)
            else:
                self.message_drawing_time -= 1 * configuration["delta_time"]
            #camera moves even if there is a message
            if (self.ball.owner == 0):
                self.cam.aim_to(
                    [self.ball.pos[0], self.ball.pos[1], self.ball.pos[2] / 2],
                    0, 50)
            else:
                self.cam.aim_to(
                    [self.ball.pos[0], self.ball.pos[1], self.ball.pos[2] / 2],
                    self.ball.owner.direction, 5)

        else:  #during pause the ball continues to roll
            self.ball.animation()

    def show_loading(self, display, font):
        title_image = pygame.image.load("data/title.png")
        # Get the surface from the NES game library
        screen = display.get_surface()
        screen.blit(title_image, (0, 0))
        screen.blit(self.team[-1].outfit_img, (52, 140))
        screen.blit(self.team[1].outfit_img, (180, 140))
        ren = font.render("vs.")
        screen.blit(ren, (128 + font.center_shift("vs."), 155))

        ren = font.render(self.team[-1].name)
        screen.blit(ren, (64 + font.center_shift(self.team[-1].name), 175))
        screen.blit(self.team[-1].image, (56, 185))
        ren = font.render(self.team[1].name)
        screen.blit(ren, (192 + font.center_shift(self.team[1].name), 175))
        screen.blit(self.team[1].image, (186, 185))
        # Update and draw the display
        display.update()

    def draw(self, surface, font):
        self.field.draw(surface, self.cam)

        sprite_list = sorted([self.ball] + self.player_list,
                             key=lambda Sprite: -Sprite.pos[1]
                             )  #sort all the sprites list with y pos
        for s in sprite_list:
            s.draw(surface, self.cam)

        if (self.message_drawing_time > 0):
            surface.blit(self.message_image, [0, 0])

        if (self.pause):
            ren = font.render(" --- PAUSE --- ")
            surface.blit(ren, (8, 32))

        if (self.match_time <= 0):
            self.match_time = -1
            #ren = font.render("Score: "+str(self.team[-1].nb_goals)+" - "+str(self.team[1].nb_goals))
            #surface.blit(ren, (8, 8))
            winner_name = self.team[-1].name
            if (self.team[-1].nb_goals < self.team[1].nb_goals):
                winner_name = self.team[1].name
            if (self.team[-1].nb_goals != self.team[1].nb_goals):
                ren = font.render(winner_name + " won!")
            else:
                ren = font.render("Draw")
            surface.blit(ren, (32, 16))

            ren = font.render("Press Start (P or R)")
            surface.blit(ren, (32, 24))

            ren = font.render("to continue...")
            surface.blit(ren, (64, 32))
        else:
            surface.blit(self.ball.image, (2, 4))
            if (self.ball.owner != 0):
                surface.blit(self.team[self.ball.owner.team.wing].image,
                             (20, 2))
                ren = font.render(self.ball.owner.name)
                surface.blit(ren, (36, 8))

        #had to force number of digits for time and nb goals
        ren = font.render("                 " + str(self.team[-1].nb_goals) +
                          " - " + str(self.team[1].nb_goals) + "    " +
                          str(max(int(self.match_time), 0)))
        surface.blit(ren, (8, 8))
        surface.blit(self.team[-1].image, (120, 2))
        surface.blit(self.team[1].image, (188, 2))
        surface.blit(self.clock_image, (240, 2))
コード例 #8
0
ファイル: match.py プロジェクト: PierreND/pyNekketsu
class Match(object):
    snd_whistle = pygame.mixer.Sound("data/sound/etw/fischiolungo.wav")
 
    #TODO: add field choice
    def __init__(self,teamA,teamB):
        self.goal_image=pygame.image.load("data/goal.png")
        self.start_image=pygame.image.load("data/start.png")
        self.message_drawing_time=50
        self.message_image=self.start_image
        self.clock_image=pygame.image.load("data/clock.png")
        self.is_finished=False
        self.teamA_filename=teamA
        self.teamB_filename=teamB
        
        self.match_time=0
        self.human_players=[-1,0,0] #max two players, player num 0 does not exist
        self.pause=False
        self.ball=Ball()
        self.player_list=[]
        self.team={}#

        #read xml file to get colors !
        self.team[-1]=Team(self.teamA_filename)
        self.team[1]=Team(self.teamB_filename)
        

    def init(self,nbr_players_human_teamA,nbr_players_teamA,nbr_players_human_teamB,nbr_players_teamB,difficulty=8,length=60):
        Player_CPU.difficulty=difficulty
        Player_GK.difficulty=difficulty

        self.goal_image=pygame.image.load("data/goal.png")
        self.start_image=pygame.image.load("data/start.png")
        self.message_drawing_time=50
        self.message_image=self.start_image
        self.clock_image=pygame.image.load("data/clock.png")
        self.is_finished=False
        
        self.match_time=length
        self.human_players=[-1,0,0] #max two players, player num 0 does not exist
        self.pause=False
        self.ball=Ball()
        self.player_list=[]
        
        human_players_teamA=[]
        human_players_teamB=[]
        if (nbr_players_human_teamA>0):
            human_players_teamA.append( 1+len(human_players_teamA)+len(human_players_teamB) )
        if (nbr_players_human_teamA>1):
            human_players_teamA.append( 1+len(human_players_teamA)+len(human_players_teamB) )
        if (nbr_players_human_teamB>0):
            human_players_teamB.append( 1+len(human_players_teamA)+len(human_players_teamB) )
        if (nbr_players_human_teamB>1):
            human_players_teamB.append( 1+len(human_players_teamA)+len(human_players_teamB) )

        self.field=Field(self.team[-1].top_color,self.team[-1].bottom_color,self.team[1].top_color,self.team[1].bottom_color)
        self.cam=Camera(self.field)

        self.team[-1].create_from_xml(-1,nbr_players_teamA,human_players_teamA,self)
        self.player_list+=self.team[-1].players
        
        self.team[1].create_from_xml(1,nbr_players_teamB,human_players_teamB,self)
        self.player_list+=self.team[1].players
        
        print("Match starts")
        
    
    def update(self):
        Inputs.readkeys()#read all the actual keys
        if (Inputs.player_just_Start[1] or Inputs.player_just_Start[2]):
            self.pause=not self.pause
            if (self.match_time<=0):
                self.is_finished=True
            else:
                if (configuration["sound"]=="on"):
                    Match.snd_whistle.play()
        
        if (not self.pause):
            if (self.message_drawing_time<10):
                if (self.message_drawing_time>0):
                    self.message_drawing_time-=1*configuration["delta_time"]
                    if (self.message_drawing_time>5)and(self.message_image==self.start_image):#kick off
                        if (configuration["sound"]=="on"):
                            Match.snd_whistle.play()
                        self.message_drawing_time=5


                if (self.match_time>0):#when time is out, players stop
                    self.match_time-=1.0/30*configuration["delta_time"] #30 FPS
                    self.team[-1].update(self)
                    self.team[1].update(self)
                if (-1<self.match_time<0):
                    if (configuration["sound"]=="on"):
                        Match.snd_whistle.play()

                self.ball.update(self)
            else:
                self.message_drawing_time-=1*configuration["delta_time"]
            #camera moves even if there is a message
            if (self.ball.owner==0):
                self.cam.aim_to([self.ball.pos[0],self.ball.pos[1],self.ball.pos[2]/2],0,50)
            else:
                self.cam.aim_to([self.ball.pos[0],self.ball.pos[1],self.ball.pos[2]/2],self.ball.owner.direction,5)


        else:#during pause the ball continues to roll
            self.ball.animation()
        
    

    def show_loading(self,display,font):
        title_image=pygame.image.load("data/title.png")
        # Get the surface from the NES game library
        screen = display.get_surface()
        screen.blit(title_image,(0,0))
        screen.blit(self.team[-1].outfit_img,(52, 140))
        screen.blit(self.team[1].outfit_img,(180, 140))
        ren = font.render("vs.")
        screen.blit(ren, (128+font.center_shift("vs."), 155))

        ren = font.render(self.team[-1].name)
        screen.blit(ren, (64+font.center_shift(self.team[-1].name), 175))
        screen.blit(self.team[-1].image,(56, 185))
        ren = font.render(self.team[1].name)
        screen.blit(ren, (192+font.center_shift(self.team[1].name), 175))
        screen.blit(self.team[1].image,(186, 185))
        # Update and draw the display
        display.update()





    def draw(self,surface,font):
        self.field.draw(surface,self.cam)

        sprite_list=sorted( [self.ball]+self.player_list,   key=lambda Sprite: -Sprite.pos[1]) #sort all the sprites list with y pos
        for s in sprite_list:
            s.draw(surface,self.cam)
        
        if (self.message_drawing_time>0):
            surface.blit(self.message_image, [0,0])
    

        if (self.pause):
            ren = font.render(" --- PAUSE --- ")
            surface.blit(ren, (8, 32))

        if (self.match_time<=0):
            self.match_time=-1
            #ren = font.render("Score: "+str(self.team[-1].nb_goals)+" - "+str(self.team[1].nb_goals))
            #surface.blit(ren, (8, 8))
            winner_name=self.team[-1].name
            if (self.team[-1].nb_goals<self.team[1].nb_goals):
                winner_name=self.team[1].name
            if (self.team[-1].nb_goals!=self.team[1].nb_goals):
                ren = font.render(winner_name+" won!")
            else:
                ren = font.render("Draw")
            surface.blit(ren, (32, 16))
            
            ren = font.render("Press Start (P or R)")
            surface.blit(ren, (32, 24))

            ren = font.render("to continue...")
            surface.blit(ren, (64, 32))
        else:
            surface.blit(self.ball.image, (2,4))
            if (self.ball.owner != 0):
                surface.blit(self.team[self.ball.owner.team.wing].image, (20,2))
                ren = font.render(self.ball.owner.name)
                surface.blit(ren, (36, 8))
        

        #had to force number of digits for time and nb goals
        ren = font.render("                 "+str(self.team[-1].nb_goals)+" - "+str(self.team[1].nb_goals)+"    "+str(max(int(self.match_time),0)))
        surface.blit(ren, (8, 8))
        surface.blit(self.team[-1].image, (120,2))
        surface.blit(self.team[1].image, (188,2))
        surface.blit(self.clock_image, (240,2))
コード例 #9
0
ファイル: simulator.py プロジェクト: AngelTsanev/AntColony
    for ant in ants:
        Matrix.SetPixel(ant.coordinates[1], ant.coordinates[0], 200, 0, 0)
	#base
    Matrix.SetPixel(base[1], base[0], 100, 255, 100)


field = Field("field.txt", (30, 40))

field.food.append((10, 10))
field.food.append((20, 20))

for i in range(1, 21):
    field.units.append(Ant(Color(0, 0, 100), 30, 40, i))
    field.add_occupied((30, 40))

offscreenCanvas = Matrix.CreateFrameCanvas()

i = 1
while True:
    i+=1
    offscreenCanvas.Clear()
    field.draw()
    field.generate_next()
    colorize(field.food, field.base, field.units)
    if i % 10 == 0:
        i = 1
        field.evaporate_pheromones()
    time.sleep(1)
    offscreenCanvas = Matrix.SwapOnVSync(offscreenCanvas)

コード例 #10
0
ファイル: main.py プロジェクト: WouterVrielink/populations
from field import Field
from walker import Walker

simulation_field = Field(100, 100)

creature = Walker(15, 10, 1, 0)

simulation_field.creatures.append(creature)

simulation_field.draw()
コード例 #11
0
ファイル: gameManager.py プロジェクト: ymzk/AiContest2012
class GameManager(Runnable):
  def __init__(self,settingFileName = "setting/gameSettings.conf"):
    super().__init__()
    #self.testInitialize()
    self.initialize(settingFileName)
    time.sleep(2)
  def defaultInitialize(self):
#    self.specialUnit = GameObject(move = MoveByKeyAsUnit(velocity = 50))
    self._viewPoint = None
    self.bullets = RunnableList()
    self.units = RunnableList()
    self.items = RunnableList()
    self.bases = RunnableList()
    self.debugObjects = RunnableList()
    self.field = Field(self)
  def initialize(self,settingFilename):
    self.defaultInitialize()
    file = open(settingFilename, "r")
    self.field.loadField(file.readline().strip())
    for team in (0,1):
      gen = self.field.getUnitPosition(team)
      for aiName,(point,direction) in zip(file.readline().split(),gen):
        if aiName == "debug":
          unit = Unit(point,direction,self,team,len(self.units))
          self.addDebugUnit(unit)
          self.units.append(unit)
          continue
        elif aiName == "player":
          unit = Unit(point,direction,self,team,len(self.units), aiManager = PlayerManager())
          self._viewPoint = unit
#          self.addDebugUnit(unit,UNIT_MAX_ROLL_ANGLE,UNIT_MAX_SPEED)
          self.units.append(unit)
          continue
        else:
          self.units.append(Unit(point,direction,self,team,len(self.units),AiManager(aiName)))
    self.debugmode = eval(file.readline())
    if self.debugmode:
      pass
    for i in self.units:
      i.sendStartingMessage()
    if self._viewPoint is None:
      self._viewPoint = GameObject(direction = -1.57079633, move = MoveByKey(speed = 5))
      self.debugObjects.append(self._viewPoint)
    self._defeatTeam = 0

  def addDebugUnit(self,unit,angle = 0.3,velocity = 10):
    self.debugUnit = unit
    self.debugUnit.setMove(MoveByKeyAsUnit(angle = angle, velocity = velocity))
    self._viewPoint = self.debugUnit
        
  def writeEndMessage(self,unit,file):
    file.write("endGame")
    if self._defeatTeam == 3:
      file.write("drawGame")
    elif self._defeatTeam == 0:
      file.write("canceled this Game")
    else:
      file.write("team ")
      file.write(self._defeatTeam)
      file.write(" win")
  def writeStartingMessage(self,unit,file):
    file.write("startInit")
    self.writeMessageUnit(unit,file)
    self.writeMessageField(self.field,file)
    file.write("endInit\n")
    self.writeMessage(unit,file)
  def writeMessage(self,unit,file):
    file.write("start")
    for i in self.bases:
      self.writeMessageBase(i,file)
    for i in self.units:
      if i.getTeamFlag() == unit.getTeamFlag():
        self.writeMessageUnit(i,file)
        continue
      if abs(i.getPosition() - unit.getPosition()) < RADIUS_OF_THE_VISILITY_ARIA:
        self.writeMessageUnit(i,file)
        continue
    for i in self.bullets:
      if abs(i.getPosition() - unit.getPosition()) <RADIUS_OF_THE_VISILITY_ARIA:
        self.writeMessageBullet(i,file)
    for i in self.items:
      if i.checkAvailable:
        if abs(i.getPosition() - unit.getPosition()) <RADIUS_OF_THE_VISILITY_ARIA:
          self.writeMessageItem(i,file)
    file.write("end")
  def writeMessageUnit(self,unit,file):
    file.write("unit")
    for i in unit.encode():
      file.write(str(i))
  def writeMessageBullet(self,bullet,file):
    file.write("bullet")
    for i in bullet.encode():
      file.write(str(i))
  def writeMessageBase(self,base,file):
    file.write("base")
    for i in base.encode():
      file.write(str(i))
  def writeMessageItem(self,item,file):
    file.write("item")
    for i in item.encode():
      file.write(str(i))      
  def writeMessageField(self,field,file):
    file.write("field")
    for i in field.encode():
      file.write(str(i))


    
  def addBullet(self, bullet):
    self.bullets.append(bullet)
  def addItem(self, item):
    self.items.append(item)
  def addBase(self, base):
    self.bases.append(base)
  def getBase(self, teamFlag):
    for i in self.bases:
      if i.getTeamFlag() == teamFlag:
        #baseはひとつだと仮定
        return i
  def step(self):
    if self.debugmode:
      self.readKeyEvent()
#    self.specialUnit.step()
    self.field.step()
    self.units.step()
    #baseはunitの後
    self.bases.step()
    self.bullets.step()
    self.items.step()
    self.debugObjects.step()

    for counter in range(20):
      #振動して無限ループになったとき、20回で終了するようにしている。
      #押し合い
      powerList = [Coordinate(0,0) for i in range(len(self.units))]
      for ii in range(len(self.units)):
        for jj in range(ii):
          i = self.units[ii].getPosition()
          j = self.units[jj].getPosition()
          if abs(i - j) < RADIUS_OF_THE_UNIT * 2 :
            factor = (RADIUS_OF_THE_UNIT * 2 - abs(i - j))/(abs(i - j) + 10 **(-7)) * (i - j)
            powerList[ii] += factor
            powerList[jj] -= factor
            #重なっているとき
      for ii in range(len(self.units)):
        for jj in range(len(self.bases)):
          i = self.units[ii].getPosition()
          j = self.bases[jj].getPosition()
          if abs(i - j) < RADIUS_OF_THE_UNIT + RADIUS_OF_THE_BASE:
            factor = (RADIUS_OF_THE_UNIT + RADIUS_OF_THE_BASE - abs(i - j))/(abs(i - j) + 10 **(-7)) * (i - j)
            powerList[ii] += factor
            #重なっているとき
            
      for i in range(len(self.units)):
        #壁との当たり判定壁との当たり判定はFeildで行う。
        #返り値はかかる力ベクトル(Coordinate)
        powerList[i] += self.field.wallDistance(RADIUS_OF_THE_UNIT, self.units[i])

      flag = True
      for i in range(len(self.units)):
        if powerList[i].norm() >= 1:
          self.units[i].setPosition(self.units[i].getPosition() + powerList[i] * PUSH_STRENGTH)
          flag = False
      if flag:
        break

    #当たり判定
    for i in range(len(self.units)):
      self.field.fieldEffect(self.units[i])
    for i in range(len(self.bullets)):
      self.field.fieldEffect(self.bullets[i])
    for i in range(len(self.items)):
      self.field.fieldEffect(self.items[i])
    #item
    for ii in range(len(self.items)):
      i = self.items[ii].getPosition()
      for jj in range(len(self.units)):
        j = self.units[jj].getPosition()
        if abs(i-j) < RADIUS_OF_THE_ITEM + RADIUS_OF_THE_UNIT:
          #あたったとき
          self.items[ii].effect(self.units[jj])
          break
    #bullet
    for ii in range(len(self.bullets)):
      i = self.bullets[ii].getPosition()
      for jj in range(len(self.units)):
        j = self.units[jj].getPosition()
        if abs(i-j) < RADIUS_OF_THE_UNIT:
          #あたったとき
          self.bullets[ii].attack(self.units[jj])
          break
    flag = False
    self._defeatTeam = 0
    for ii in range(len(self.bullets)):
      i = self.bullets[ii].getPosition()
      for jj in range(len(self.bases)):
        j = self.bases[jj].getPosition()
        if abs(i-j) < RADIUS_OF_THE_BASE:
          #あたったとき
          self.bullets[ii].attack(self.bases[jj])
          if self.bases[jj].checkAlive():
            continue
          flag = True
          self._defeatTeam |= 1<<jj
          break
    if flag:
      if self._defeatTeam == 1:
        print("team 1 win")
      elif self._defeatTeam == 2:
        print("team 0 win")
      elif self._defeatTeam == 3:
        print("draw")
      self.end()
    for i in self.units:
      i.sendData()
  
  def draw(self, screan):
    self.field.draw(screan,self._viewPoint)
    self.bases.draw(screan, self._viewPoint)
    self.units.draw(screan, self._viewPoint)
    self.bullets.draw(screan, self._viewPoint)
    self.items.draw(screan, self._viewPoint)
  def readKeyEvent(self):
    self._viewPoint = GetKeyEvent(self._viewPoint, self.units, self.debugObjects)
  def end(self):
    for i in self.units:
      i.sendEndMessage()
    self.field.end()
    self.bases.end()
    self.units.end()
    self.bullets.end()
    self.items.end()
    time.sleep(3)
    Runnable.end(self)
コード例 #12
0
running = True

while running:
    #clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key in directions.key_map.keys():
                state.move(directions.key_map[event.key])
            if event.key == pygame.K_q: # quit
                running = False
            if event.key == pygame.K_z: # reset state
                state = State(fld,win)
            if event.key == pygame.K_r: # move at random
                state.move_random()
            if event.key == pygame.K_w: # move at random till dead_end()
                state = state.randomize(True)
            if event.key in (pygame.K_u, pygame.K_KP5): # undo last move
                state.undo()
            if event.key == pygame.K_d: # dump state to "state.txt"
                state.dump()
    win.fill(colors.BLACK)
    state.draw_all_possible_moves()
    fld.draw(win)
    state.draw_moves()
    state.draw_ball()
    state.draw_whose_turn()
    pygame.display.flip()

pygame.quit()
コード例 #13
0
ファイル: game.py プロジェクト: LTCTM/RunnersAndLadders
class Game(object):
    MAX_CAUGHT_TIME = 1
    TRAP_RECOVER_TIME = 4

    def __init__(self, map_index):
        "map_index:地图编号"
        #系统
        self.__pressed_keys = pygame.key.get_pressed()
        self.__start_time = time.clock()
        #游戏内容
        self.result = None
        self.__runner_caught_count = 0
        self.__gold_got = 0
        self.field = Field(map_index, self)
        self.runner = Runner(self, self.field.runner_init_location)
        self.red_ones = []
        for ROIL in self.field.red_ones_init_location:
            self.red_ones.append(RedOne(self, ROIL))
        self.__all_characters = tuple(self.red_ones) + (self.runner, )
        self.__traps = []

    def dig_trap(self, location, create_time):
        "location:为元组或Position对象,create_time:创造陷阱的主时间main_time"
        self.__traps.append((location, create_time))
        self.field.set_grid(location, GridType.trap)

    @property
    def living_red_ones_location(self):
        return (red_one.location for red_one in self.red_ones
                if not red_one.dead)

    def __listen_input(self):
        "消息处理"
        while not self.result:
            for event in pygame.event.get():
                if event.type == QUIT:
                    os._exit(0)
            self.__pressed_keys = pygame.key.get_pressed()
            if self.__pressed_keys[K_ESCAPE]:
                self.result = "Cancel"

    def __heart_process(self):
        "游戏过程(心跳过程)"
        runner_last_die_time = 0
        while not self.result:
            main_time = time.clock() - self.__start_time
            self.field.draw(SCREEN)
            if self.runner.dead:
                #Runner死亡状态,一切游戏内容暂停,不显示红人,显示Runner死亡图标。到一定时间玩家复活
                self.runner.draw(SCREEN)
                self.runner.try_reborn(main_time)
            else:
                #正常游戏状态
                #陷阱可能重置
                if len(self.__traps) > 0:
                    oldest_trap = self.__traps[0]
                    trap_location = oldest_trap[0]
                    trap_set_time = oldest_trap[1]
                    if main_time >= trap_set_time + self.TRAP_RECOVER_TIME:
                        self.field.set_grid(trap_location, GridType.brick)
                        self.__traps.pop(0)
                        #重置的陷阱可能会击杀人物
                        for character in self.__all_characters:
                            if character.location == trap_location:
                                character.die(main_time)
                #Runner和红人接受指令或尝试复活
                for character in self.__all_characters:
                    if character.dead:
                        character.try_reborn(main_time)
                    elif character.busy:
                        character.act(main_time)
                    else:
                        character.get_command(main_time, self.__pressed_keys)
                    character.draw(SCREEN)
                if self.runner.location in self.living_red_ones_location:
                    #被抓住
                    self.runner.die(main_time)
                if self.field.get_grid(self.runner.location) == GridType.gold:
                    #吃到金子
                    self.field.set_grid(self.runner.location, GridType.air)
                    self.__gold_got += 1
                    if self.__gold_got == self.field.gold_count:
                        #胜利
                        self.result = "You Win"
                if self.runner.dead:
                    #Runner因为各种原因死亡
                    runner_last_die_time = main_time
                    self.__runner_caught_count += 1
                    if self.__runner_caught_count > self.MAX_CAUGHT_TIME:
                        #失败
                        self.result = "You lose"
                    #部分游戏内容重置
                    for trap in self.__traps:
                        self.field.set_grid(trap[0], GridType.brick)
                    for red_one in self.red_ones:
                        red_one.move_init_location()
                    self.__traps.clear()
            #显示
            pygame.display.update()
        #游戏结束
        if self.result == "Cancel":
            pass
        else:
            self.field.draw(SCREEN)
            if self.runner.dead:
                self.runner.draw(SCREEN)
            else:
                for character in self.__all_characters:
                    character.draw(SCREEN)
            print_text(self.result)
            pygame.display.update()
            time.sleep(3)

    def begin(self):
        self.__main_task = Task.start_new(self.__heart_process)
        self.__listen_input()
        self.__main_task.wait()
        return self.result
コード例 #14
0
class Program:
    """The main class for playing a program"""
    def __init__(self, resolution=(1366, 768), fullscreen=True):
        fullscreen = pygame.FULLSCREEN if fullscreen else 0
        self.resolution = resolution
        try:
            self.window = pygame.display.set_mode(resolution, fullscreen)
        except Exception as e:
            Tk().withdraw()
            messagebox.showerror('Ошибка!', e)
            raise e
        pygame.display.set_caption('Life by BUS410')
        self.cols = (resolution[0] - UI_WIDTH) // 10
        self.rows = resolution[1] // 10
        self.field = Field(resolution[0] - UI_WIDTH,
                           resolution[1],
                           self.cols,
                           self.rows,
                           count_put_food=32)
        self.field.update()
        self.update_iterator = UPDATE_FREQUENCY
        self.update_frequency = UPDATE_FREQUENCY
        self.clock = pygame.time.Clock()
        self.start = False
        self.next_update = True
        self.widgets = [
            Widget(x=0,
                   y=0,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Старт/Стоп',
                   background_color=BUTTON_COLOR,
                   onclick=self.start_stop,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=0,
                   y=WIDGET_HEIGHT,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Очистить',
                   onclick=self.clear,
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 2,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Размер таблицы'),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 3,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='-',
                   onclick=lambda: self.change_field('-'),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=UI_WIDTH // 2,
                   y=WIDGET_HEIGHT * 3,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='+',
                   onclick=lambda: self.change_field('+'),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 4,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='-10',
                   onclick=lambda: self.change_field('-', 10),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=UI_WIDTH // 2,
                   y=WIDGET_HEIGHT * 4,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='+10',
                   onclick=lambda: self.change_field('+', 10),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 5,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Частота обновл.'),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 6,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='-',
                   onclick=lambda: self.change_update_frequency('+'),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=UI_WIDTH // 2,
                   y=WIDGET_HEIGHT * 6,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='+',
                   onclick=lambda: self.change_update_frequency('-'),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 7,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Еды за раз'),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 8,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='-',
                   onclick=lambda: self.change_food_count('-'),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=UI_WIDTH // 2,
                   y=WIDGET_HEIGHT * 8,
                   width=UI_WIDTH // 2,
                   height=WIDGET_HEIGHT,
                   text='+',
                   onclick=lambda: self.change_food_count('+'),
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 9,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Пищи: 1'),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 10,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Организмов: 0'),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 11,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Хищников: 0'),
            Widget(x=0,
                   y=WIDGET_HEIGHT * 12,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Поле: 36x64'),
            Widget(x=0,
                   y=resolution[1] - WIDGET_HEIGHT,
                   width=UI_WIDTH,
                   height=WIDGET_HEIGHT,
                   text='Выход',
                   background_color=BUTTON_COLOR,
                   background_color_cover=BUTTON_COVER,
                   background_color_click=BUTTON_CLICKED,
                   onclick=self.quit)
        ]

    def start_stop(self):
        if self.start:
            self.start = False
        else:
            self.start = True

    def quit(self):
        self.next_update = False

    def clear(self):
        self.field.clear()
        self.field.update()
        self.update_info()

    def change_food_count(self, action):
        if action == '+':
            self.field.count_put_food += 10
        elif action == '-':
            if self.field.count_put_food > 0:
                self.field.count_put_food -= 10

    def change_update_frequency(self, action):
        if action == '+':
            self.update_frequency += 1
            if self.update_frequency >= FPS:
                self.update_frequency = FPS
        elif action == '-':
            self.update_frequency -= 1
            if self.update_frequency <= 1:
                self.update_frequency = 1

    def change_field(self, action, n=1):
        if action == '+':
            self.rows += n
            self.cols += n
        elif action == '-':
            if self.rows > MIN_ROWS_COLS + n - 1:
                self.rows -= n
            if self.cols > MIN_ROWS_COLS + n - 1:
                self.cols -= n
        self.field = Field(self.resolution[0] - UI_WIDTH,
                           self.resolution[1],
                           self.cols,
                           self.rows,
                           count_put_food=self.field.count_put_food)
        self.field.update()

    def update_info(self):
        self.widgets[-2].text = f'Поле: {self.rows}x{self.cols}'
        self.widgets[-3].text = f'Хищников: {self.field.predators}'
        self.widgets[-4].text = f'Организмов: {self.field.organisms}'
        self.widgets[-5].text = f'Пищи: {self.field.foods}'

    def main(self):
        while True:
            if not self.update():
                break
            self.clock.tick(FPS)
        pygame.quit()

    def update(self):
        self.next_update = True
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                self.next_update = False
            elif e.type == pygame.KEYUP and e.key == pygame.K_ESCAPE:
                self.next_update = False
            elif e.type == pygame.MOUSEBUTTONUP:
                if e.button == 1:
                    pos = pygame.mouse.get_pos()
                    if pos[0] > UI_WIDTH:
                        pos = (pos[0] - UI_WIDTH, pos[1])
                        self.field.put_live(1, pos)
                        self.field.update()
                        self.update_info()

        for widget in self.widgets:
            widget.update(events)

        if self.start and not self.update_iterator:
            self.update_iterator = self.update_frequency
            self.field.update()
            self.update_info()
        if self.update_iterator:
            self.update_iterator -= 1

        self.draw()

        return self.next_update

    def draw(self):
        self.window.fill(WINDOW_BACKGROUND)
        for widget in self.widgets:
            widget.show(self.window)
        self.field.draw(self.window, (UI_WIDTH, 0))
        pygame.display.update()