Exemplo n.º 1
0
def populateListOfConditions(theFileName):
    with open(theFileName, 'r', encoding='mac_roman') as csvfile:
        fileReader = csv.reader(csvfile)
        next(fileReader)
        previousRowID = ""
        previousRowCondition = ""
        for row in fileReader:
            if row[CONDITION_COLUMN] == "" or row[
                    CONDITION_COLUMN] != previousRowID:
                listOfConditions[row[CONDITION_COLUMN]] = []
                newCondition = Condition(row[CONDITION_COLUMN],
                                         row[SUBTYPE_COLUMN])
                newField = Field(row[SUBTYPE_COLUMN], row[LINE_NUMBER_COLUMN],
                                 row[FIELD_COLUMN], row[PROGRESS_COLUMN])
                newCondition.addFieldToCondition(newField)
                listOfConditions[row[CONDITION_COLUMN]].append(newCondition)
            elif row[CONDITION_COLUMN] == previousRowID:
                if row[SUBTYPE_COLUMN] == previousRowCondition:
                    newField = Field(row[SUBTYPE_COLUMN],
                                     row[LINE_NUMBER_COLUMN],
                                     row[FIELD_COLUMN], row[PROGRESS_COLUMN])
                    conditionReference = listOfConditions[
                        row[CONDITION_COLUMN]]
                    conditionReference[-1].addFieldToCondition(newField)
                elif row[SUBTYPE_COLUMN] != previousRowCondition:
                    newCondition = Condition(row[CONDITION_COLUMN],
                                             row[SUBTYPE_COLUMN])
                    newField = Field(row[SUBTYPE_COLUMN],
                                     row[LINE_NUMBER_COLUMN],
                                     row[FIELD_COLUMN], row[PROGRESS_COLUMN])
                    newCondition.addFieldToCondition(newField)
                    listOfConditions[row[CONDITION_COLUMN]].append(
                        newCondition)
            previousRowID = row[CONDITION_COLUMN]
            previousRowCondition = row[SUBTYPE_COLUMN]
Exemplo n.º 2
0
def get_captures_for_queen_directions(board, pawn, player, nx, ny):
    x = pawn.x
    y = pawn.y
    n = 0
    board_with_captured = []
    while True:
        x = x + n * nx
        y = y + n * ny
        if board.does_field_exist(x, y):
            if board.is_opponent_pawn(player, x, y):
                if is_correct_move(board, Field(x + nx, y + ny, "c", 100)):
                    # print("oponen")
                    future_pawn = Field(x + nx, y + ny, pawn.pawn, pawn.value)
                    opponent_pawn = Field(x, y, "c", 0)
                    new_board = board.copy_board()
                    new_board.remove_pawn(pawn)
                    new_board.remove_pawn(opponent_pawn)
                    new_board.add_pawn(future_pawn)
                    board_with_captured = [new_board]

                    break
        else:
            break
        n += 1
    return board_with_captured
Exemplo n.º 3
0
 def test_show_hide(self):
     field = Field(None, (0, 0))
     assert not field.visible
     field.show()
     assert field.visible
     field.hide()
     assert not field.visible
Exemplo n.º 4
0
    def generate(self):
        self.gen += 1

        while len(self.pool) < 2:
            self.pool.append(Field())

        parents = self.get_parents()
        children = self.get_children(parents)

        if children[0].score > parents[1].score:
            self.pool.append(children[0])
            self.pool.append(children[1])
            self.pool.append(parents[1])
            return

        if parents[0].score > children[1].score:
            self.pool.append(parents[1])
            return

        if parents[1].score > children[1].score:
            self.pool.append(children[1])
            self.pool.append(parents[1])
            return

        self.pool.append(children[1])
        self.pool.append(Field())
        return
Exemplo n.º 5
0
    def __init__(self):
        self.top = Tk()
        self.canvas = Canvas(self.top, bg="darkgreen", height=700, width=1000)
        self.field = Field(self.canvas, "darkgreen", 1000, 700, 50, 30, 160,
                           80, 150, 70, 200, 10, 150, 5)
        self.meshGrid = MeshGrid(self.canvas, 1000, 700, 50, 15)
        self.ball = Ball(self.canvas, 500, 350, 10, 4, "white", "black", 1)

        buttonNextFrame = Button(self.top,
                                 text="Next Frame",
                                 command=self.nextFrame)
        buttonNextFrame.place(x=350, y=680)

        buttonShowMeshgrid = Button(self.top,
                                    text="Show Grid",
                                    command=self.showMeshGrid)
        buttonShowMeshgrid.place(x=550, y=680)

        buttonShowFlowfield = Button(self.top,
                                     text="Show Flowfield",
                                     command=self.showFlowField)
        buttonShowFlowfield.place(x=650, y=680)

        buttonShowField = Button(self.top,
                                 text="Show Field",
                                 command=self.showFootballField)
        buttonShowField.place(x=450, y=680)

        self.animate()

        self.nextFrame()
        self.canvas.pack()
        self.top.mainloop()
Exemplo n.º 6
0
    def moveSlice(self, slice, toLeft):
        # slice is a row or column from board
        # toLeft == 1 means agregate values to the left
        if not toLeft:
            slice.reverse()
        newslice = []
        current = None
        for i in range(len(slice)):
            if slice[i].getValue() is None:
                continue
            if current is None and isinstance(slice[i].getValue(), int):
                current = slice[i].getValue()
                continue
            elif slice[i].getValue() == current and isinstance(slice[i].getValue(), int):
                newslice.append(Field(current*2))
                current = None
            elif slice[i].getValue() != current and isinstance(slice[i].getValue(), int):
                newslice.append(Field(current))
                current = slice[i].getValue()

        newslice.append(Field(current))
        for i in range(self.size - len(newslice)):
            newslice.append(Field(None))
        if not toLeft:
            newslice.reverse()
            return newslice
        return newslice
Exemplo n.º 7
0
def test_successful_end_to_end():
	f = Field(Example)

	assert f.from_kind == Question
	assert f.to_kind   == Answer

	assert 'get_question'		 in f.opcode
	assert 'tests_verify_answer' in f.opcode
	assert '2pat_merge_as_pic'	 in f.opcode

	source = Source(('get_question',
					 'pic_all_as_pat',
					 'pat_flip_up_down',
					 'get_question',
					 'pic_all_as_pat',
					 '2pat_merge_as_pic',
					 'tests_verify_answer'))

	code = f.compile(source)

	assert isinstance(code, Code)
	assert len(code.data) == len(source.data)

	ctx = Context('data')
	prb = ctx.get_problem_startswith('496994bd')

	for example in prb:
		ret = f.run(code, example, peek_answer=True)

		assert isinstance(ret, Block)
		assert ret.type == Block.type_integer
		assert isinstance(ret.data, int)

		assert ret.data == 1
Exemplo n.º 8
0
    def __init__(self):
        super(TFTEnv, self).__init__()
        self.reward_range = (0, MAX_ACCOUNT_BALANCE)

        # Actions of the format Buy x%, Sell x%, Hold, etc.
        self.action_space = spaces.Box(low=np.array([0, 0]),
                                       high=np.array([8, 1]),
                                       dtype=np.float16)
        """
        Multidiscrete action space as follows:
        1. Buy Champion: Discrete 6 - NOOP[0], BUY[1-5]
        2. Sell Champion: Discrete 6 (from bench) - NOOP[0], SELL[1-9]
        3. Level up: Discrete 2 - NOOP[0], LEVEL[1]
        4. Reroll: Discrete 2 - NOOP[0], REROLL[2]
        5. Move Champion from board to bench: Discrete 190 - NOOP[0], MOVE[1-189]
        6: Move Champion from bench to board: Discrete 190 - NOOP[0], MOVE[1-189]
        8. Move Champion from board to board: Discrete 421 - NOOP[0], MOVE[1-420]
        """
        self.action_space = spaces.MultiDiscrete([5, 10, 421, 2, 2])
        # Prices contains the OHCL values for the last five prices
        """
        Observation space:
        Bench: [9, 5]
        Board: [21, 5]
        Store: [5, 5] [Slot 1-5][Champion ID, Stars, Tier, Synergy 1, Synergy 2]
        """
        self.observation_space = spaces.Box(0, 5, shape=(35, 6), dtype=np.int)
        # main execution
        self.info_reader = ScreenInterpreter()
        self.pc = PlayerControl()
        self.field = Field()
        self.offset = win32gui.ClientToScreen(self.info_reader.hwnd, (0, 0))
        self.pc.setOffset(self.offset)
        self.current_step = 0
Exemplo n.º 9
0
class Game(object):
    def __init__(self):
        #self.menu = some_menu()
        self.field = Field()

        self.coords = self.field.get_new_coords()

    def draw_all(self):
        #отрисовать меню

        self.field.draw_field()

    def make_shot(self, coord):

        ship = self.field.make_shot(coord)

        killed = ship.make_shot()

        #change counts

    def start(self):

        while self.coords:

            self.draw_all()

            # choice = input('Введите x,y: ').replace(" ").split(',')
            # choice.make_shot()
            # self.field.make_shot(self.coords.get(choice), choice)
            self.coords = None
Exemplo n.º 10
0
    def _draw_field(self, field: Field, offset=0):
        if self.last_field is None:
            self.last_field = Field(field.width, field.height)
            self.last_field.set_all_pixels_to([-1, -1,
                                               -1])  # ensures a repaint
            pygame.draw.rect(
                self.window, [50, 50, 50],
                pygame.Rect(self.field_position[0], self.field_position[1],
                            field.width * self._pixel_width,
                            field.height * self._pixel_height))

        sizechange = 1 if offset > 0 else 0
        for y in range(0, field.height):
            for x in range(0, field.width):
                pixel_color = field.field[y][x]
                if offset == 0:
                    if pixel_color == self.last_field.field[y][x]:
                        continue
                left = (x - offset) * self._pixel_width + self.field_position[
                    0] + 1 + sizechange * 5
                top = (y - offset) * self._pixel_height + self.field_position[
                    1] + 1 + sizechange * 5
                width = self._pixel_width - 2 - sizechange * 10
                height = self._pixel_height - 2 - sizechange * 10
                pygame.draw.rect(self.window, pixel_color,
                                 pygame.Rect(left, top, width, height))

                # remember the pixel if original field
                if offset == 0:
                    self.last_field.field[y][x] = pixel_color
Exemplo n.º 11
0
def get_correct_moves_for_pawn(board, pawn, player):
    if player == PLAYER1:
        direction = 1
    else:
        direction = -1

    correct_moves = []
    possible_field = Field(pawn.x + 1, pawn.y + direction, pawn.pawn,
                           pawn.value)
    if is_correct_move(board, possible_field):
        new_board = board.copy_board()
        new_board.remove_pawn(pawn)
        if board.is_on_edge(possible_field.x, possible_field.y):
            possible_field = board.pawn_to_queen(possible_field)
        new_board.add_pawn(possible_field)
        correct_moves.append(new_board)
    possible_field = Field(pawn.x - 1, pawn.y + direction, pawn.pawn,
                           pawn.value)
    if is_correct_move(board, possible_field):
        new_board = board.copy_board()
        new_board.remove_pawn(pawn)
        if board.is_on_edge(possible_field.x, possible_field.y):
            possible_field = board.pawn_to_queen(possible_field)
        new_board.add_pawn(possible_field)
        correct_moves.append(new_board)
    return correct_moves
Exemplo n.º 12
0
def get_captures_for_pawn_left(board, pawn, player) -> (Board, None):
    if player == PLAYER1:
        direction = 1
    else:
        direction = -1

    board_with_captured = None
    if board.does_field_exist(pawn.x - 1,
                              pawn.y + direction) and board.does_field_exist(
                                  pawn.x - 2, pawn.y + (2 * direction)):
        if board.is_opponent_pawn(player, pawn.x - 1,
                                  pawn.y + direction) and board.is_empty_field(
                                      pawn.x - 2, pawn.y + (2 * direction)):
            future_pawn = Field(pawn.x - 2, pawn.y + (2 * direction),
                                pawn.pawn, pawn.value)
            opponent_pawn = Field(pawn.x - 1, pawn.y + direction, "c", 0)
            board_with_captured = board.copy_board()
            board_with_captured.remove_pawn(opponent_pawn)
            board_with_captured.remove_pawn(pawn)
            if board.is_on_edge(future_pawn.x, future_pawn.y):
                future_pawn = board.pawn_to_queen(future_pawn)
            board_with_captured.add_pawn(future_pawn)
            potential = get_captures_for_pawn_left(board_with_captured,
                                                   future_pawn, player)
            if potential:
                board_with_captured = potential
    return board_with_captured
Exemplo n.º 13
0
 def __init__(self, id, alpha, bound, origX, origY, width, height):
     Field.__init__(self, id)
     self.alpha = alpha
     self.bound = bound
     self.origX = origX
     self.origY = origY
     self.width = width
     self.height = height
Exemplo n.º 14
0
 def __init__(self, id, alpha, bound, origX, origY, width, height):
     Field.__init__(self, id)
     self.alpha = alpha
     self.bound = bound
     self.origX = origX
     self.origY = origY
     self.width = width
     self.height = height
Exemplo n.º 15
0
 def pawn_to_queen(self, pawn: Field):
     if pawn.pawn.isupper():
         return pawn
     else:
         if pawn.y == 0 or pawn.y == 7:
             pawn.pawn = pawn.pawn.upper()
             pawn.value = pawn.value * 10
     return pawn
Exemplo n.º 16
0
def simWalks(numSteps, numTrials, dClass):
    homer = dClass('Homer')
    origin = Location(0, 0)
    distances = []
    for t in range(numTrials):
        f = Field()
        f.addDrunk(homer, origin)
        distances.append(walk(f, homer, numSteps))
    return distances
Exemplo n.º 17
0
 def Fields(self):
     flds = Processible.Fields(self).union([
         Field('modeid', 'int'),
         Field('sampleid', 'int'),
         Field('weight', 'float')
     ])
     if self.weighted:
         flds = flds.union([Field('lumifactor', 'float')])
     return flds
Exemplo n.º 18
0
 def __init__(self):
     self.window = Tk()
     self.window.title('Football')
     self.canvas = Canvas(self.window, width=2*Field.X0+Field.WIDTH, height=2*Field.Y0+Field.HEIGHT)
     self.canvas.pack()
     self.field = Field(self.canvas)
     self.ball = Ball(self.canvas, self.field)
     self.scoreboard = Scoreboard(self.canvas, self.field)
     self.teams = Teams(self.canvas, self.field, self.ball)
     self.state = Game.BEGIN
Exemplo n.º 19
0
 def __init__(self):
     """
     The class represented the BattleShips game process
     """
     player_1 = input('Player 1, Enter your name: ')
     player_2 = input('Player 2, Enter your name: ')
     self.__fields = [Field(), Field()]
     self.__players = [Player(player_1), Player(player_2)]
     self.__current_player = 0
     self.__next_player = 1
Exemplo n.º 20
0
 def get_input_fields(cls) -> List[Field]:
     return super().get_input_fields() + [
         Field('EndDate', 'task end date', validate_date_string,
               'value must be date in YYYYMMDD format'),
         Field(
             'Frequency', 'task recurrence frequency',
             validate_recurrence_frequency,
             f'value must be in {[enum_value for enum_value in RecurrenceFrequency]}'
         )
     ]
Exemplo n.º 21
0
def test_decompile():
	field = Field(Example)

	source = ('[2, 4, 6, 8]', '(0, 1, 1, 0)', '(1, 2)', '(2,)', '[[1, 1], [1, 0]]',
			  'pic_int_zoom_in', 'pic_intp_select_columns', 'pic_nesw_extend', 'pic_vec_recolor_each')

	code = field.compile(Source(source))

	assert code.type == Block.type_no_error

	new_source = field.decompile(code)

	assert field.rex_vector.match(new_source[0].strip())
	assert field.rex_tuple.match(new_source[1].strip())
	assert field.rex_tuple.match(new_source[2].strip())
	assert new_source[3].strip() == '2'
	assert field.rex_picture.match(new_source[4].strip())

	new_source = field.decompile(code, pretty=False)

	assert new_source == source

	new_source = field.decompile(BopForward.bopforward_2pic_recolor_any_rtl)

	assert len(new_source) == 1

	new_source = field.decompile((Block.new_picture(list_of_list=[[4, 0, 4]]), BopForward.bopforward_pic_all_as_pat))

	assert len(new_source) == 2

	with pytest.raises(AttributeError):
		field.decompile((Block.new_picture(list_of_list=[[4, 0, 4]]), 'aa'))
Exemplo n.º 22
0
def findSolution(n, matrix):
	field = Field()
	field.createField(matrix)
	field.printField()

	solutions = Queue()

	minSolution = None
	cache = ComboCache()
	preAnsweredCache = {}
	
	for j in range(1,n+1):
		preAnsweredCache[j]= []

	for i in range(1,n+1):
		cache.clear()

		if (i-2 in preAnsweredCache):
			for sol in preAnsweredCache[i-2]:
				newSolution = Solution(field)
				newSolution.setState(solution)
				newSolution.maxGreenhouses = i
				solutions.put(newSolution)
		else:
			firstSolution = Solution(field)
			firstSolution.maxGreenhouses = i
			solutions.put(firstSolution)
		
		while (not solutions.empty()):
			solution = solutions.get()
			if (minSolution == None or solution.computeCost() < minSolution.computeCost()):
				if (solution.getNumberOfGreenhouses() == (solution.maxGreenhouses-1)):
					## find the leftmost, topmost, rightmost, bottommost 
					## uncovered points. They form your final greenhouse.
					## if left < right and top < bottom (or right > right and bottom > bottom,
					## it overlaps, and no solution using this is possible.
					if (solution.placeFinalGreenhouse()):
						cost = solution.computeCost()
						if (minSolution == None or cost < minSolution.computeCost()):
							minSolution = solution
				else:
					## iterate through the remaining uncovereds, both for start
					## and end. reject overlaps!

					for corner1 in solution.getRemaining():
						for corner2 in solution.getRemaining():				
							newSolution = Solution(field)
							newSolution.setState(solution)
							if (newSolution.placeGreenhouse(corner1.x, corner2.x, corner1.y, corner2.y)):
								if (not cache.isPresent(newSolution)):
									solutions.put(newSolution)
									preAnsweredCache[newSolution.getNumberOfGreenhouses()].append(newSolution)
									cache.insert(newSolution)
						
	minSolution.printSolution()
Exemplo n.º 23
0
def simulateWalk(steps, intentsNumber, drunkType):
    drunk = drunkType(name='Oskar')
    origin = Coordenate(0, 0)
    distances = []

    for _ in range(intentsNumber):
        field = Field()
        field.addDrunk(drunk, origin)
        walkSimulation = walk_trip(field, drunk, steps)
        distances.append(round(walkSimulation, 1))
    return distances
Exemplo n.º 24
0
 def perform_search(self):
     keywordsElement = self._get_loading_element(
         {'by': By.ID, 'value': 'sc.keyword'})
     locationElement = self._get_loading_element(
         {'by': By.ID, 'value': 'sc.location'})
     self.keywordsField = Field(keywordsElement)
     self.locationField = Field(locationElement)
     self.actionBtn = self._get_loading_element(
         {'by': By.CSS_SELECTOR, 'value': '.SearchStyles__newSearchButton'})
     self.virtualUser.perform_search(
         self.keywordsField, self.locationField, self.actionBtn)
Exemplo n.º 25
0
 def make_fields():
     fields = []
     for i in range(8):
         row = []
         for j in range(8):
             if (i + j) % 2 == 1:
                 row.append(Field(j, i, "_", 0))
             else:
                 row.append(Field(j, i, "  ", 0))
         fields.append(row)
     return fields
Exemplo n.º 26
0
 def create_pawns():
     pawns = []
     for i in range(3):
         for j in range(8):
             if (i + j) % 2 == 1:
                 pawns.append(Field(j, i, "w", 1))
     for i in range(5, 8):
         for j in range(8):
             if (i + j) % 2 == 1:
                 pawns.append(Field(j, i, "b", -1))
     return pawns
Exemplo n.º 27
0
def assert_error(source_tuple, error_msg):
    field = Field(Example)

    code = field.compile(Source(source_tuple))

    assert isinstance(code, Code)

    ret = field.run(code)

    assert isinstance(ret, Block)
    assert ret.type == Block.type_error
    assert ret.data == error_msg
Exemplo n.º 28
0
    def populate_field(field: Field, **kwargs):
        allow_blank = kwargs.get('allow_blank', False)

        while field.value is None:
            try:
                raw_input = input(f'Enter value for {field.name}: ')
                if allow_blank and raw_input == '':
                    return

                field.set(raw_input)
            except ValueError as err:
                print(err)
Exemplo n.º 29
0
def simWalks(numSteps, numTrials, dClass):
    """Assumes numSteps an int >= 0, numTrials an int > 0,
    dClass a subclass of Drunk Simulates numTrials walks of numSteps steps each.
    Returns a list of the final distances for each trial"""
    Homer = dClass()
    origin = Location(0.0, 0.0)
    distances = []
    for t in range(numTrials):
        f = Field()
        f.addDrunks(Homer, origin)
        distances.append(walk(f, Homer, numSteps))
    return distances
Exemplo n.º 30
0
def simWalks(numSteps, numTrials, dClass):
    """numSteps : 0 以上の整数
       numTrials : 正の整数
       dClass : Drunk のサブクラス
       numSteps 回移動する酔歩を, numTrials 回シミュレートする.
       各実験の初期位置と最終位置との差をリストにして出力する."""
    Homer = dClass()
    origin = Location(0.0, 0.0)
    distances = []
    for t in range(numTrials):
        f = Field()
        f.addDrunk(Homer, origin)
        distances.append(walk(f, Homer, numSteps))
    return distances
Exemplo n.º 31
0
def simWalks(numSteps, numTrials, dClass):
    """numSteps : 0 以上の整数
       numTrials : 正の整数
       dClass : Drunk のサブクラス
       numSteps 回移動する酔歩を, numTrials 回シミュレートする.
       各実験の初期位置と最終位置との差をリストにして出力する."""
    Homer = dClass()
    origin = Location(0.0, 0.0)
    distances = []
    for t in range(numTrials):
        f = Field()
        f.addDrunk(Homer, origin)
        distances.append(walk(f, Homer, numSteps))
    return distances
Exemplo n.º 32
0
	def load(self, file_name, abstract_relation):
		"""
		This loads and compiles a collection of code snippets from a text file.

		The snippets are appended to the content already in the CodeBase. Names cannot
		match any of the names already in the CodeBase.

		It requires a Relation Class for a language definition for compiling.
		"""
		field = Field(abstract_relation)

		with open(file_name, 'r') as f:
			txt = f.read().splitlines()

		if not txt[0].startswith('.bopDB'):
			raise ValueError

		name = None
		for line in txt[3:]:
			if name is None:
				if line == '.eof.':
					return

				name   = line
				source = None
				sample = None
			elif line.startswith('-'):
				source_tuple = ()
			elif line == '':
				if source is None:
					source = Source(source_tuple)
					code   = field.compile(source)
					if code.type == Block.type_error:
						raise ValueError
				else:
					self.add(code, source, name, sample)
					name = None
			else:
				if source is None:
					source_tuple = source_tuple + (line,)
				else:
					try:
						pic = eval(line)
					except Exception:
						raise ValueError

					sample = Block.new_picture(list_of_list=pic)

		raise ValueError
Exemplo n.º 33
0
class FieldController(object):
    def __init__(self):
        self.view = View()
        self.field = Field()

    def daily_show(self):
        last_rabbit_location = ""
        last_carrot_location = ""
        exception = []
        try:
            last_rabbit_location = self.field.last_borned_rabbit.location
        except Exceptions.NoMoreRabbit:
            last_rabbit_location = " "
            exception += ['No More Rabbit']
        try:
            last_carrot_location = self.field.last_created_carrot.location
        except Exceptions.NoMoreCarrot:
            last_carrot_location = " "
            exception += ['No More Carrot']
        except Exceptions.NoMoreRooms:
            # TODO handel exception
            exception += ['No More Room']

        self.view.clear()
        self.view.show(self.field.field_map,
                       self.field.date,
                       last_rabbit_location,
                       last_carrot_location,
                       self.field.number_of_rabbits,
                       self.field.number_of_carrots,
                       exception=exception)

    def start(self):
        if self.field.date == 1:
            for _ in range(2):
                self.field.add_rabbit(gender="Male")
                self.field.add_rabbit(gender="Female")
                self.field.add_carrot()
                self.field.add_carrot()
        self.daily_show()
        self.life_loop()

    def life_loop(self):
        while True:
            self.field.date += 1
            self.field.add_carrot()
            self.field.move_rabbits()
            self.daily_show()
            sleep(2)
Exemplo n.º 34
0
def simWalks(numSteps, numTrials, dClass):
    """Assumes numSteps an int >= 0, numTrials an int > 0,
         dClass a subclass of Drunk
       Simulates numTrials walks of numSteps steps each.
       Returns a list of the final distances for each trial"""
    Homer = dClass()
    origin = Location(0, 0)
    distances = []
    for t in range(numTrials):
        f = Field()
        f.addDrunk(Homer, origin)
        # distances.append(round(walk(f, Homer, numTrials), 1))
        #next line is the correction made in the text
        distances.append(round(walk(f, Homer, numSteps), 1))
    return distances
Exemplo n.º 35
0
 def get_input_fields(cls) -> List[Field]:
     return [
         Field('Name', 'task name', validate_nonempty_string,
               'value must have len > 0'),
         Field('Type', 'task type',
               lambda x: validate_value_in_set(x, cls.valid_types),
               f'value must be in {cls.valid_types}'),
         Field('StartDate', 'task start date', validate_date_string,
               'value must be date in YYYYMMDD format'),
         Field('StartTime', 'task start time', validate_time_string,
               'value must be floating-point number in [0.0, 23.75]'),
         Field('Duration', 'task duration (minutes)',
               validate_task_duration_string,
               'value must be positive integer in [0, 3600]')
     ]
Exemplo n.º 36
0
def main():

    CardSet.loadCardSet("CardSet")
    playerOne = Player("koala", CardSet.listCard)
    playerTwo = Player("panda", CardSet.listCard)
    print(sys.version)
    i = 1
    winner = None
    while winner == None :
        if i % 2 == 0 :
            winner = Field.playTurn(playerOne, playerTwo)
        else :
            winner = Field.playTurn(playerTwo, playerOne)
        i += 1
    playerOne.toString()
    playerTwo.toString()
    print("Vainqueur : ", winner.name)
Exemplo n.º 37
0
 def __init__(self, width, height):
     super(SubWindow, self).__init__()
     self.width = width
     self.height = height
     self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     self.isUntitled = True
     widget = QtGui.QScrollArea()
     self.qp = QtGui.QPainter()
     if width and height:
         self.field = Field(width, height)
         self.setWidget(self.field)
         self.life = Life(width, height, False)
         self.reset()
         self.field.cells = self.life.cells
Exemplo n.º 38
0
    def __init__(self):

        self.numSetsMade = 0
        self.numSetsTotal = 0
        self.setsListTotal = []
        self.setsMadeSoFar = []
        self.cardChoices = []
        self.deckManager = DeckManager()
        self.timedModeFlag = False
        self.gamediff = Difficulty.NOVICE
        self.timeddiff = 0
        self.numHints = 3 if self.gamediff == Difficulty.ADVANCED else 2
        self.field = Field(3,4) if self.gamediff == Difficulty.ADVANCED else Field(3,3)

        self.deckManager.placeCardsOnField(self.field)
        if self.scanSetsOnField() != 4 + (2 if self.gamediff == Difficulty.ADVANCED else 0):
            self.resetGame()
Exemplo n.º 39
0
def findSolution(n, matrix):
	field = Field()
	field.createField(matrix)
	print(n)
	field.printField()
	
	currentBest = None

	for i in range(1,n+1):
		for j in range(5):
			newSolution = findForN(i, field)
			if (currentBest == None or newSolution.getCost() < currentBest.getCost()):
				currentBest = newSolution
			
	currentBest.printSolution(field.getMaxX(),field.getMaxY())
Exemplo n.º 40
0
    def LoadNextLevel(self):
        self.level += 1
        if self.level < 9:
            source = file('LEVEL/' + str(self.level) + '.level')
            self.music_name = str('MUSIC/' + source.readline().rstrip())
            self.wave_max = int(source.readline())
            self.first_wave_time = int(source.readline())
            self.wave_time = int(source.readline())
            self.res = int(source.readline())
            self.upgrade_d = int(source.readline())
            self.basic_tower_d = int(source.readline())
            self.adv_tower_d = int(source.readline())
            i = 0
            line = source.readline()
            line = line.split()
            num_waves = int(line[0])
            wave_type = line[1]
            while (i < self.wave_max):
                if i == num_waves:
                    line = source.readline()
                    line = line.split()
                    num_waves = int(line[0])
                    wave_type = line[1]
                self.enemy_wave_description.append(wave_type)
                i += 1
                    

            #initialize map from newly loaded self
            self.the_map = Field('MAP/' + str(self.level) + '.map')
            self.map_surface = self.the_map.get_map().convert()
            self.grid = self.the_map.get_grid()
            self.towers = self.the_map.towers
            self.enemies = dict()

            self.meter = WaveMeter(self.wave_max,(self.wave_time/40),(self.first_wave_time/40),self.enemy_wave_description)
            #reset all main variables
            self.current_level = pygame.image.load('IMG/level_' + str(self.level) + '_100.png').convert_alpha() 
            self.frame = 0
            self.enemy_sent = 0
            self.enemy_max = 0
            self.enemy_level = 0
            
        else:
            self.game_state = 'end'
Exemplo n.º 41
0
    def loadFile(self, fileName):
        file = QtCore.QFile(fileName)
        if not file.open( QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, "Reading error",
                    "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return False
        instr = QtCore.QTextStream(file)
        start = False
        width = 0
        lines = []

        while not instr.atEnd():
            line = instr.readLine()
            if width < len(line):
                width = len(line)
            if line[0] != '#':
                start = True
                lines.append(line)
            if line[0] == '#' and start:
                break

        height = len(lines)   
        if not width or not height:
            return False 
        self.width = width
        self.height = height
        self.field = Field(width, height)
        self.setWidget(self.field)
        self.life = Life(width, height, False)
        self.field.cells = self.life.cells
        y=0
        for line in lines:
            x = 0
            for char in line:
                if char == '*':
                    self.life.cells[x,y] = True
                x += 1
            y += 1

        self.field.update()        
        self.setCurrentFile(fileName)
        return True
Exemplo n.º 42
0
import sys
from Field import Field
import subprocess
import platform

print("Starting Up Game")
print("This is Nogame the Game")

GameField = Field(10, 10)
GameField.addPlayer(4, 4)
GameField.Draw()
print("You see that big H?")
print("That's you,")
print("Press enter to confirm")
sys.stdin.read(1)
GameField.addTarget(1, 1)
GameField.Draw()
print("You see that T? \nThats your target. \nYou can move around with wasd.\n\nGo Get'em Tiger! ")
while(True):
    input = sys.stdin.read(2)
    output = GameField.MovePlayer(input, GameField.player)

    GameField.Draw()
    print(output)
Exemplo n.º 43
0
class GameMenue(object):
    
    def __init__(self, parent, player, modus, gui):
        self.alreadyFinished = False
        self.gui = gui
        self.modus = modus  # 0 = classic    1 = equal
        self.player = player
        self.rootNode = parent
        self.divNodeGameMenue= avg.DivNode(parent = self.rootNode, size  = self.rootNode.size, active = False)
        self.background = avg.ImageNode(parent = self.divNodeGameMenue, href = "DatBG.png", size = self.divNodeGameMenue.size)
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        self.winLooseMenu = WinLooseMenue(self.rootNode)
        self.optionMenu = OptionMenue(self.rootNode)
        self.menueLinkerXwert  = int(self.divNodeGameMenue.size[0]/2- self.divNodeGameMenue.size[0]*0.04)
        self.menueRechterXwert = int(self.divNodeGameMenue.size[0]/2+ self.divNodeGameMenue.size[0]*0.04)
        self.rahmenbreite = int(self.divNodeGameMenue.size[0]*0.025)
        self.yOben  = int(self.divNodeGameMenue.size[1] * 0.05) 
        self.untereBeschraenkung = self.divNodeGameMenue.size[1] * 0.92 - self.rahmenbreite
        self.xendFeld1 = self.menueLinkerXwert -self.rahmenbreite - self.divNodeGameMenue.size[1] * 0.03
        self.xstartFeld1, self.yUnten = self.berechneLinkesXUntenYFeld1(self.xendFeld1, self.untereBeschraenkung,self.yOben)
        sizefield = self.xendFeld1 - self.xstartFeld1
        self.xstartFeld2 = self.menueRechterXwert +self.rahmenbreite + self.divNodeGameMenue.size[1] * 0.03
        self.xendFeld2   = self.xstartFeld2 + sizefield
        self.blocksize = (self.xendFeld1 - self.xstartFeld1 )/14
        self.tetrishoehe = self.blocksize * 19
        self.round = 1
        self.rundenDauer = 180
        self.speed = [700,650,600,550,500]
        self.countOfSkillsActivated = 0
        self.inverseControlActive = False
        self.leftFreezeActive = False
        self.rightFreezeActive = False
        self.rotateFreezeActive = False
        self.speedUpActive = False
        self.makeBlockInvisibleActive = False
        self.noPointsActive = False       
        self.initSounds()
#Gui initialisierung
        self.initFeld(self.xstartFeld1, self.xendFeld1, self.yOben )
        self.initFeld(self.xstartFeld2, self.xendFeld2, self.yOben )

#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
      

        self.hoeheMitlererBalken =  self.divNodeGameMenue.size[1] * 0.20
        mittlererBalken = self.divNodeGameMenue.size[0]/2
        
        self.timelimit =  avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = 0.022*self.divNodeGameMenue.size[1], 
                                      text ="TimeLimit", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        
        while(self.timelimit.size[0]>= (self.menueRechterXwert- self.menueLinkerXwert) | (self.timelimit.size[1]>= self.divNodeGameMenue.size[1]* 0.1 )):
            self.timelimit.fontsize-=1
            if(self.timelimit.fontsize<=0):
                self.timelimit.fontsize= 1
                break
        fontS = self.timelimit.fontsize  
        self.hoeheMitlererBalken +=  fontS + fontS*0.5
#-----------------------------------------------------------------------------------------------------------------------------------------------------------                 
        self.timerLimit = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text =str(self.rundenDauer ), 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        
        self.hoeheMitlererBalken +=  4*fontS
        
        self.timeLimitCounter = self.player.setInterval(1000, self.timerLCountDown)
#----------------------------------------------------------------------------------------------------------------------------------------------------------- 
        
        self.roundText = avg.WordsNode(pos = (mittlererBalken, self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text ="Round", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken +=  fontS + fontS*0.5
#----------------------------------------------------------------------------------------------------------------------------------------------------------- 
        
        self.roundNumber = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text =str(self.round), 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken +=  4*fontS
#---------------------------------------------------------------------------------------------------------------------------------------------------------- 
        
        self.speedText = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text ="Speed", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken +=  fontS + fontS*0.5
      
        self.speedNumber = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text ="1", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken += 4*fontS

         
        self.scoreTeam1 = avg.WordsNode(pos = ((self.xstartFeld1 + self.xendFeld1)/2 , self.divNodeGameMenue.size[1] * 0.94),
                                      fontsize = 0.035*self.divNodeGameMenue.size[1], 
                                      text ="Score :   100", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
          
        self.scoreTeam2 = avg.WordsNode(pos = ((self.xstartFeld2 + self.xendFeld2)/2 , self.divNodeGameMenue.size[1] * 0.94),
                                      fontsize = 0.035*self.divNodeGameMenue.size[1], 
                                      text ="Score :   100",  
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        #Optionevents
        self.background.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.background, self.startOptionMenu)
        self.optionMenu.buttonResume.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.optionMenu.buttonResume, self.stopOptionMenue)
        self.optionMenu.buttonFinish.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.optionMenu.buttonFinish, self.finishEarly)
        self.optionMenu.buttonSound.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.optionMenu.buttonSound, self.turnSoundOff)

        self.yUnten =  self.yOben + self.tetrishoehe
        self.field1 = Field(self.xstartFeld1, self.xendFeld1, self.yOben, self.yUnten,self.blocksize,self.player,self,1, self.gui)
        self.field2 = Field(self.xstartFeld2, self.xendFeld2, self.yOben, self.yUnten,self.blocksize,self.player,self,2, self.gui)
        
        self.attackerNormalField1 = AttackerSkills(self.field1,self.player)
        self.attackerNormalField2 = AttackerSkills(self.field2,self.player)
        
        self.attackerSpezialonField1 = AttackerSpecials(self.field2, self.field1,self.player,self.gui)
        self.attackerSpezialonField2 = AttackerSpecials(self.field1, self.field2,self.player,self.gui)
        
        self.defenderSkillsField1 = DefenderSkills(self.field1, self.player)
        self.defenderSkillsField2 = DefenderSkills(self.field2, self.player)
        
        self.playSound("gameStart")
        if(self.gui.lobbyMenu.modus != 2):
            self.SkillActivator = self.player.setInterval(10000, self.activateOneSkill)
        
        
        #print "Tetrisfeldbegrenzungen:   lF1:",self.xstartFeld1,"  rF1: ",self.xendFeld1,"   lF1F2: ",self.xstartFeld2,"  rF2:  ",self.xendFeld2,"  yO: ", self.yOben," yU: ", self.yUnten
        #print "Ein Feld:  Blocksize:  ", self.blocksize, "    Hoehe:   ", self.tetrishoehe, "    Breite:  ", self.xendFeld1-self.xstartFeld1
#buttoms werden initialisiert
        

#fuehrt  Bewegung des Felds auf
    def eventMoveLinks(self,event):
        self.field1.moveLeft()
    
    def eventRotateLinks(self,event):
        self.field1.rotateLeft()

    def eventRotateRechts(self,event):
        self.field1.rotateRight()

    def eventMoveRechts(self,event):
        self.field1.moveRight()
        
    def eventSpeedDown(self,event):
        self.field1.speedDown()


#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------        
    #berechneLinkesXUntenYFeld1    
    def berechneLinkesXUntenYFeld1(self,rechteKante, untereSchranke, obereSchranke):
        linkesX = int(self.divNodeGameMenue.size[0] * 0.03) 
        size = rechteKante - linkesX
        size = self.naechsteZahlDurch14Teilbar(size)
        while(True):
            blocksize = size / 14
            tetrishoehe = blocksize *19
            if((untereSchranke - obereSchranke) >= tetrishoehe):
                return ((rechteKante- size), obereSchranke-tetrishoehe)
            else:
                size-=14
                
        
#----------------------------------------------Rundenuebergang---------------------------------------------------------------------------------------------------    
    # Time Counter Fuer Game    
    def timerLCountDown (self):
        count = int (self.timerLimit.text)
        if(self.modus == 1):#EqualModus, dh reihen loeschen bei der mitte und fallender stein wird geloescht
            if(count >=0):
                if(count <= 0):
                    self.timerLimit.text = str(-3)
                    self.rundenWechsel()
                    if(self.round > 5):
                        self.player.clearInterval(self.timeLimitCounter)
                        self.endeSpiel()
                else:
                    count -= 1
                    self.timerLimit.text = str(count)
            else:
                count+=1
                self.timerLimit.text = str(count)
                if(count >= 0):
                    self.fieldChanceRundenWechsel()
                    self.timerLimit.text = str(self.rundenDauer)
        else:
            if(count <= 0):#ClassicModus
                self.timerLimit.text = str(self.rundenDauer)
        
                self.field1.chanceSpeed(self.speed[self.round-1])
                self.field2.chanceSpeed(self.speed[self.round-1])
                self.round += 1
                if(self.round > 5):
                    self.field1.clearForNextRound()
                    self.player.clearInterval(self.timeLimitCounter)
                    self.endeSpiel()
                else:
                    self.roundNumber.text = str(self.round)
                    self.speedNumber.text = str(self.round)
            else:
                count -= 1
                self.timerLimit.text = str(count)
         
    def rundenWechsel(self):
        self.field1.clearForNextRound()
        self.field2.clearForNextRound()
        self.resetField(self.field1)
        self.resetField(self.field2)
        self.round += 1
        self.roundNumber.text = str(self.round)
        self.speedNumber.text = str(self.round)
        self.playSound("round")

        
    def fieldChanceRundenWechsel(self):
        
        self.field1.speed = self.speed[(self.round -1)]
        self.field1.timer = self.field1.player.setInterval(self.field1.speed, self.field1.gravity)
        self.field2.speed = self.speed[(self.round -1)]
        self.field2.timer = self.field2.player.setInterval(self.field2.speed, self.field2.gravity)
        self.field1.initBlock()
        self.field2.initBlock()

        
#----------------------------------------------------------------------------------------------------------------------------------------------------------------
    # beended spiel, deaktiviert alle intervalle und geht zum gametypemenue zurueck
    def endeSpiel(self, winner = "check"):
        if(not self.alreadyFinished):
            if(winner == "check"):
                scoreTeam1 = self.field1.score
                scoreTeam2 = self.field2.score
                if(scoreTeam1 == scoreTeam2):
                    winner = "Unentschieden"
                elif(scoreTeam1 > scoreTeam2):
                    winner = "Team 1 gewinnt"
                elif(scoreTeam1 < scoreTeam2):
                    winner = "Team 2 gewinnt"
            if(self.gui.lobbyMenu.modus != 2):
                self.player.clearInterval(self.SkillActivator)
            self.alreadyFinished = True
            self.field1.gravityPausieren()
            self.field2.gravityPausieren()
            self.player.clearInterval(self.timeLimitCounter)
            self.divNodeGameMenue.active = False
            self.optionMenu.divNodeOptionMenue.active = False
            self.winLooseMenu.buttonNextGame.sensitive = True
            self.winLooseMenu.buttonSomeOneWon.updateTextNode(winner)
            self.winLooseMenu.divNodeWinLooseMenue.active = True
            self.gui.sendMsgToAll("gameEnds")
            self.playSound("victory")
    
    def naechsteZahlDurch14Teilbar(self,value):
        x = value % 14
        return value - x
    
    #initialisiert das grafische feld
    def initFeld (self, startX, endX, oben):
#linker Rahmen
        avg.RectNode(parent = self.divNodeGameMenue, sensitive = False,
                                  pos = (startX -self.rahmenbreite  , oben), 
                                  fillcolor = "000000", fillopacity = 1, color = "000000", 
                                  size = avg.Point2D(self.rahmenbreite ,self.tetrishoehe) #self.divNodeGameMenue.size[1]* 0.87
                                  )
#rechter Rahmen
        avg.RectNode(parent = self.divNodeGameMenue, 
                                  pos = (endX , oben), sensitive = False,
                                  fillcolor = "000000", fillopacity = 1, color = "000000", 
                                  size = avg.Point2D(self.rahmenbreite, self.tetrishoehe)
                                  )
#Boden
        avg.RectNode(parent = self.divNodeGameMenue, sensitive = False,
                                  pos = (startX-self.rahmenbreite, self.tetrishoehe+oben), 
                                  fillcolor = "000000", fillopacity = 1, color = "000000", 
                                  size = avg.Point2D(endX-startX+2*int(self.divNodeGameMenue.size[0]*0.025) ,self.rahmenbreite)
                                  )
                                  
    #event um optionmenu zu aktivieren                              
    def startOptionMenu(self, event):
        self.divNodeGameMenue.active = False
        self.optionMenu.divNodeOptionMenue.active = True
        self.field1.gravityPausieren()
        self.player.clearInterval(self.timeLimitCounter)
    
    #event um optionmenu zu deaktivieren    
    def stopOptionMenue(self, event):
        self.divNodeGameMenue.active = True
        self.optionMenu.divNodeOptionMenue.active = False
        self.field1.gravityWiederStarten()
        self.timeLimitCounter = self.player.setInterval(1000, self.timerLCountDown)
        
    #event im menue zum beenden des spiels    
    def finishEarly(self, event):
        self.field1.score = 0
        self.field2.score = 0
        self.endeSpiel()
    #event im menue zum beenden der sounds   
    def turnSoundOff(self, event):
        text = self.optionMenu.buttonSound.getTextNode().text
        if(text == "Sound:  ON"):
            self.deactivateSound()
            self.optionMenu.buttonSound.updateTextNode("Sound:  OFF")
        else:
            self.activateSound()
            self.optionMenu.buttonSound.updateTextNode("Sound:  ON")

    #schaltet nach 2 minuten einen cooldown fuer den Angreifer frei, nur im 3 und 4 modus aktiviert
    def activateOneSkill(self): 
        randomNumber = random.randint(1,7)
        freigeschalteterBlock = ""
        if (randomNumber == 1):
            if (self.rightFreezeActive == True):
                self.activateOneSkill()
            else:
                self.rightFreezeActive = True
                self.countOfSkillsActivated += 1
                self.playSound("skillUnlocked")
                freigeschalteterBlock = "unlockRightFreeze"

        elif (randomNumber == 2):
            if (self.leftFreezeActive == True):
                self.activateOneSkill()
            else:
                self.leftFreezeActive = True
                self.countOfSkillsActivated += 1
                self.playSound("skillUnlocked")
                freigeschalteterBlock = "unlockLeftFreeze"

        elif (randomNumber == 3):
            if (self.rotateFreezeActive == True):
                self.activateOneSkill()
            else:
                self.rotateFreezeActive = True
                self.countOfSkillsActivated += 1
                self.playSound("skillUnlocked")
                freigeschalteterBlock = "unlockRotateFreeze"
        elif (randomNumber == 4):
            if (self.noPointsActive == True):
                self.activateOneSkill()
            else:
                self.noPointsActive = True
                self.countOfSkillsActivated += 1
                self.playSound("skillUnlocked")
                freigeschalteterBlock = "unlockNoPoints"

        elif (randomNumber == 5):
            if (self.inverseControlActive == True):
                self.activateOneSkill()
            else:
                self.inverseControlActive = True
                self.countOfSkillsActivated += 1
                self.playSound("skillUnlocked")
                freigeschalteterBlock = "unlockInverseControl"
        elif (randomNumber == 6):
            if (self.makeBlockInvisibleActive == True):
                self.activateOneSkill()
            else:
                self.makeBlockInvisibleActive = True
                self.countOfSkillsActivated += 1
                self.playSound("skillUnlocked")
                freigeschalteterBlock = "unlockBlockInvisible"
        else:
            if (self.speedUpActive == True):
                self.activateOneSkill()
            else:
                self.speedUpActive = True
                self.countOfSkillsActivated += 1
                self.playSound("skillUnlocked")
                freigeschalteterBlock = "unlockSpeedUp"
        if (self.countOfSkillsActivated == 7):
            self.player.clearInterval(self.SkillActivator)
        #sende
        if(freigeschalteterBlock != ""):
            if(self.gui.lobbyMenu.modus == 3):
                ip = self.gui.lobbyMenu.playerIP[2]
                print ip+ "###"+freigeschalteterBlock
                self.gui.sendMsgToOne(ip,freigeschalteterBlock)
            elif(self.gui.lobbyMenu.modus == 4):
                ip1 = self.gui.lobbyMenu.playerIP[2]
                ip2 = self.gui.lobbyMenu.playerIP[3]
                self.gui.sendMsgToOne(ip1,freigeschalteterBlock)
                self.gui.sendMsgToOne(ip2,freigeschalteterBlock)
    
    # reseted das feld    
    def resetField(self, Field):
        
        Field.inverseSteuerung = False
        Field.freezeLeft = False
        Field.freezeRight = False
        Field.freezeRotate = False
        Field.speedToGround = False
        Field.superBlock = False
        Field.bombActivated = False
        Field.thunderActivated = False
        Field.tetrisRainActivated = False
        Field.noMoneyForYou = False
        Field.rainDropCount = 0
    
    #initialisiert die sounds   
    def initSounds(self):
        self.deniedSound = avg.SoundNode(href="denied.mp3", loop=False, volume=1.0, parent = self.rootNode)
        self.skillUnlockedSound = avg.SoundNode(href="skillUnlocked.mp3", loop=False, volume=1.0, parent = self.rootNode)
        self.gameStartSound = avg.SoundNode(href="gameStart.mp3", loop=False, volume=1.0, parent = self.rootNode)
        self.rotateSound = avg.SoundNode(href="rotate.wav", loop=False, volume=1.0, parent = self.rootNode)
        self.victorySound = avg.SoundNode(href="victory.mp3", loop=False, volume=1.0, parent = self.rootNode)
        self.thunderSound = avg.SoundNode(href="thunder.wav", loop=False, volume=1.0, parent = self.rootNode)
        self.roundSound = avg.SoundNode(href="round.mp3", loop=False, volume=1.0, parent = self.rootNode)
        self.rainSound = avg.SoundNode(href="rain.mp3", loop=False, volume=1.0, parent = self.rootNode)
        self.bombSound = avg.SoundNode(href="bomb.wav", loop=False, volume=1.0, parent = self.rootNode)
        self.cashSound = avg.SoundNode(href="cash.mp3", loop=False, volume=1.0, parent = self.rootNode)
    
    #ueberprueft welchen sound er abspielen soll    
    def playSound(self, String):
        if (String == "rain"):
            self.rainSound.play()
        elif (String == "bomb"):
            self.bombSound.play()
        elif (String == "cash"):
            self.cashSound.play()
        elif (String == "round"):
            self.roundSound.play()
        elif (String == "thunder"):
            self.thunderSound.play()
        elif (String == "victory"):
            self.victorySound.play()
        elif (String == "rotate"):
            self.rotateSound.play()
        elif (String == "denied"):
            self.deniedSound.play()
        elif (String == "gameStart"):
            self.gameStartSound.play()
        elif (String == "skillUnlocked"):
            self.skillUnlockedSound.play()
        else:
            pass
    #deactivates all sound nodes    
    def deactivateSound(self): 
        self.bombSound.volume = 0.0
        self.cashSound.volume = 0.0
        self.deniedSound.volume = 0.0
        self.gameStartSound.volume = 0.0
        self.rainSound.volume = 0.0
        self.rotateSound.volume = 0.0
        self.roundSound.volume = 0.0
        self.skillUnlockedSound.volume = 0.0
        self.thunderSound.volume = 0.0
     
    #activates all sound nodes   
    def activateSound(self): 
        self.bombSound.volume = 1.0
        self.cashSound.volume = 1.0
        self.deniedSound.volume = 1.0
        self.gameStartSound.volume = 1.0
        self.rainSound.volume = 1.0
        self.rotateSound.volume = 1.0
        self.roundSound.volume = 1.0
        self.skillUnlockedSound.volume = 1.0
        self.thunderSound.volume = 1.0
Exemplo n.º 44
0
    def __init__(self, parent, player, modus, gui):
        self.alreadyFinished = False
        self.gui = gui
        self.modus = modus  # 0 = classic    1 = equal
        self.player = player
        self.rootNode = parent
        self.divNodeGameMenue= avg.DivNode(parent = self.rootNode, size  = self.rootNode.size, active = False)
        self.background = avg.ImageNode(parent = self.divNodeGameMenue, href = "DatBG.png", size = self.divNodeGameMenue.size)
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        self.winLooseMenu = WinLooseMenue(self.rootNode)
        self.optionMenu = OptionMenue(self.rootNode)
        self.menueLinkerXwert  = int(self.divNodeGameMenue.size[0]/2- self.divNodeGameMenue.size[0]*0.04)
        self.menueRechterXwert = int(self.divNodeGameMenue.size[0]/2+ self.divNodeGameMenue.size[0]*0.04)
        self.rahmenbreite = int(self.divNodeGameMenue.size[0]*0.025)
        self.yOben  = int(self.divNodeGameMenue.size[1] * 0.05) 
        self.untereBeschraenkung = self.divNodeGameMenue.size[1] * 0.92 - self.rahmenbreite
        self.xendFeld1 = self.menueLinkerXwert -self.rahmenbreite - self.divNodeGameMenue.size[1] * 0.03
        self.xstartFeld1, self.yUnten = self.berechneLinkesXUntenYFeld1(self.xendFeld1, self.untereBeschraenkung,self.yOben)
        sizefield = self.xendFeld1 - self.xstartFeld1
        self.xstartFeld2 = self.menueRechterXwert +self.rahmenbreite + self.divNodeGameMenue.size[1] * 0.03
        self.xendFeld2   = self.xstartFeld2 + sizefield
        self.blocksize = (self.xendFeld1 - self.xstartFeld1 )/14
        self.tetrishoehe = self.blocksize * 19
        self.round = 1
        self.rundenDauer = 180
        self.speed = [700,650,600,550,500]
        self.countOfSkillsActivated = 0
        self.inverseControlActive = False
        self.leftFreezeActive = False
        self.rightFreezeActive = False
        self.rotateFreezeActive = False
        self.speedUpActive = False
        self.makeBlockInvisibleActive = False
        self.noPointsActive = False       
        self.initSounds()
#Gui initialisierung
        self.initFeld(self.xstartFeld1, self.xendFeld1, self.yOben )
        self.initFeld(self.xstartFeld2, self.xendFeld2, self.yOben )

#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
      

        self.hoeheMitlererBalken =  self.divNodeGameMenue.size[1] * 0.20
        mittlererBalken = self.divNodeGameMenue.size[0]/2
        
        self.timelimit =  avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = 0.022*self.divNodeGameMenue.size[1], 
                                      text ="TimeLimit", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        
        while(self.timelimit.size[0]>= (self.menueRechterXwert- self.menueLinkerXwert) | (self.timelimit.size[1]>= self.divNodeGameMenue.size[1]* 0.1 )):
            self.timelimit.fontsize-=1
            if(self.timelimit.fontsize<=0):
                self.timelimit.fontsize= 1
                break
        fontS = self.timelimit.fontsize  
        self.hoeheMitlererBalken +=  fontS + fontS*0.5
#-----------------------------------------------------------------------------------------------------------------------------------------------------------                 
        self.timerLimit = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text =str(self.rundenDauer ), 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        
        self.hoeheMitlererBalken +=  4*fontS
        
        self.timeLimitCounter = self.player.setInterval(1000, self.timerLCountDown)
#----------------------------------------------------------------------------------------------------------------------------------------------------------- 
        
        self.roundText = avg.WordsNode(pos = (mittlererBalken, self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text ="Round", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken +=  fontS + fontS*0.5
#----------------------------------------------------------------------------------------------------------------------------------------------------------- 
        
        self.roundNumber = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text =str(self.round), 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken +=  4*fontS
#---------------------------------------------------------------------------------------------------------------------------------------------------------- 
        
        self.speedText = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text ="Speed", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken +=  fontS + fontS*0.5
      
        self.speedNumber = avg.WordsNode(pos = (mittlererBalken , self.hoeheMitlererBalken),
                                      fontsize = fontS, 
                                      text ="1", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        self.hoeheMitlererBalken += 4*fontS

         
        self.scoreTeam1 = avg.WordsNode(pos = ((self.xstartFeld1 + self.xendFeld1)/2 , self.divNodeGameMenue.size[1] * 0.94),
                                      fontsize = 0.035*self.divNodeGameMenue.size[1], 
                                      text ="Score :   100", 
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
          
        self.scoreTeam2 = avg.WordsNode(pos = ((self.xstartFeld2 + self.xendFeld2)/2 , self.divNodeGameMenue.size[1] * 0.94),
                                      fontsize = 0.035*self.divNodeGameMenue.size[1], 
                                      text ="Score :   100",  
                                      parent = self.divNodeGameMenue, 
                                      color = "F0F0F0", font = "arial", 
                                      alignment = "center",
                                      sensitive = False)
        #Optionevents
        self.background.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.background, self.startOptionMenu)
        self.optionMenu.buttonResume.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.optionMenu.buttonResume, self.stopOptionMenue)
        self.optionMenu.buttonFinish.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.optionMenu.buttonFinish, self.finishEarly)
        self.optionMenu.buttonSound.connectEventHandler(avg.CURSORDOWN, avg.TOUCH, self.optionMenu.buttonSound, self.turnSoundOff)

        self.yUnten =  self.yOben + self.tetrishoehe
        self.field1 = Field(self.xstartFeld1, self.xendFeld1, self.yOben, self.yUnten,self.blocksize,self.player,self,1, self.gui)
        self.field2 = Field(self.xstartFeld2, self.xendFeld2, self.yOben, self.yUnten,self.blocksize,self.player,self,2, self.gui)
        
        self.attackerNormalField1 = AttackerSkills(self.field1,self.player)
        self.attackerNormalField2 = AttackerSkills(self.field2,self.player)
        
        self.attackerSpezialonField1 = AttackerSpecials(self.field2, self.field1,self.player,self.gui)
        self.attackerSpezialonField2 = AttackerSpecials(self.field1, self.field2,self.player,self.gui)
        
        self.defenderSkillsField1 = DefenderSkills(self.field1, self.player)
        self.defenderSkillsField2 = DefenderSkills(self.field2, self.player)
        
        self.playSound("gameStart")
        if(self.gui.lobbyMenu.modus != 2):
            self.SkillActivator = self.player.setInterval(10000, self.activateOneSkill)
Exemplo n.º 45
0
 def __init__(self, id, alpha):
     Field.__init__(self, id)
     self.alpha = alpha
Exemplo n.º 46
0
#test class to view map design, not used in game

import pygame
from pygame.locals import *
from Field import Field
import sys

filename = sys.argv[1]      #read command line argument for map file name
source = file(filename)

pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption(filename)

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill(((255, 255, 255)))

the_map = Field(filename)
map_surface = the_map.get_map().convert()
background.blit(map_surface, (0,0))

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    
    screen.blit(background, (0,0))
    pygame.display.flip()
Exemplo n.º 47
0
class Dungeon(Scene):
    def __init__(self, engine):
        self.engine = engine
        
        name = self.engine.dungeon                    #name of the dungeon
        path = os.path.join("places", name)           #path to the dungeon
        
        self.dungeonini = Configuration(os.path.join("..", "data", path, "dungeon.ini")).dungeon
                                                      #config file
        self.formations = [f.strip() for f in self.dungeonini.formations.split(",")]
        self.otherevents = [e.strip() for e in self.dungeonini.events.split(",")]
        self.field = Field(self, path)                #the field data (grid)
        
        #ogg or mp3 support for background music
        self.music = BGMObj(os.path.join(path, "bgm.mp3"), fullpath = True)
        if not self.music:
            self.music = BGMObj(os.path.join(path, "bgm.ogg"), fullpath = True)
            
                
        w,h = self.engine.w, self.engine.h        
        
        #background image
        self.background = ImgObj(os.path.join(path, "background.png"))
        self.background.setScale(self.engine.w, self.engine.h, inPixels = True)
        self.background.setPosition(w/2,h/2)
        
        #displays the current map direction
        self.compassbase = ImgObj(os.path.join("scenes", "dungeon", "compassbase.png"))
        self.compassbase.setPosition(w*.1, h*.1)
        self.compassbase.setScale(256, 256, True)
        self.compass = ImgObj(os.path.join("scenes", "dungeon", "compass.png"))
        self.compass.setPosition(w*.1, h*.1)
        self.compass.setScale(256, 256, True)
        
        #displays coordinates of the player
        self.font = FontObj("default.ttf", size = 32)
        self.font.setPosition(w*.5,h*.1)
        
        #displays player height
        self.bigFont = FontObj("default.ttf", size = 72)
        self.bigFont.setPosition(w*.8,h*.9)
        
        self.selectedPos = self.field.playerPos       #selected position for movement
        self.distance = 0
        
        #camera controls
        self.position = [w/2,h/2]
        self.panX = w/2
        self.panY = h/2
        self.cameraMotion = False
        self.angle = 135.0
        if self.field.playerPos[0] > self.field.dimensions[0]/2:
            if self.field.playerPos[1] > self.field.dimensions[1]/2:
                self.angle = 225.0
            else:
                self.angle = 135.0
        else:
            if self.field.playerPos[1] > self.field.dimensions[1]/2:
                self.angle = 45.0
            else:
                self.angle = 315.0
          
        
        self.mode = 0                                 #0 = view, 1 = action menu, 2 = move
        
        self.actionMenu = MenuObj(self, ["Move", "Menu", "Escape"], (w*.8, h*.25), window = "window.png")
        
        self.moveKeys = {}                            #keys used for tile selection
        self.updateKeys()
        
        
    #makes sure to flip input keys for selecting a tile when the map is rotated
    # so it makes sense
    # down is towards the camera, up is away
    def updateKeys(self):
        if self.angle == 45.0 or self.angle == 305.0:
            self.moveKeys[Input.DnButton] = [(self.selectedPos[0], self.selectedPos[1] + 1), 1]
            self.moveKeys[Input.UpButton] = [(self.selectedPos[0], self.selectedPos[1] - 1),-1]
        else:
            self.moveKeys[Input.UpButton] = [(self.selectedPos[0], self.selectedPos[1] + 1), 1]
            self.moveKeys[Input.DnButton] = [(self.selectedPos[0], self.selectedPos[1] - 1),-1]
        
        if self.angle == 45.0 or self.angle == 215.0:
            self.moveKeys[Input.RtButton] = [(self.selectedPos[0] + 1, self.selectedPos[1]), 1]
            self.moveKeys[Input.LtButton] = [(self.selectedPos[0] - 1, self.selectedPos[1]),-1]
        else:
            self.moveKeys[Input.LtButton] = [(self.selectedPos[0] + 1, self.selectedPos[1]), 1]
            self.moveKeys[Input.RtButton] = [(self.selectedPos[0] - 1, self.selectedPos[1]),-1]
          
        
    def keyPressed(self, key, char):
      
        #view mode
        #  allows panning and rotating of the map
        if self.mode == 0:
            if key == Input.CButton:
                self.angle += 90.0
                self.updateKeys()
            
            if key == Input.DButton:
                self.angle -= 90.0
                self.updateKeys()
            
            if key == Input.RtButton:
                self.panX += _panRate
            if key == Input.LtButton:
                self.panX -= _panRate
            if key == Input.UpButton:
                self.panY += _panRate
            if key == Input.DnButton:
                self.panY -= _panRate
            
            
            #open action menu
            if key == Input.AButton:
                self.mode = 1
                
            #resets pan position to center
            if key == Input.BButton:
                self.panX = w/2
                self.panY = h/2
                                
        #selecting action
        elif self.mode == 1:
            self.actionMenu.keyPressed(key)
            
            if key == Input.BButton:
                self.mode = 0
                
        #selecting tile to move to
        elif self.mode == 2:
            if key in self.moveKeys.keys():
                try:
                    heightdiff = self.field.grid[self.moveKeys[key][0]].height - self.field.grid[self.field.playerPos].height
                    newDistance = self.distance + self.moveKeys[key][1]
                    if not (abs(heightdiff) > 1 or abs(newDistance) > 1):
                        self.selectedPos = self.moveKeys[key][0]
                        self.distance = newDistance
                except:
                    return
                
            self.field.setSelected(self.selectedPos)
            self.field.updateList()
            self.updateKeys()
                               
            #move player to selected position
            if key == Input.AButton:
                self.distance = 0
                self.field.playerPos = self.selectedPos
                self.field.grid[self.field.playerPos].show()
                self.field.deselect()
                self.field.updateList()
                self.mode = 0
                
            #cancel movement
            if key == Input.BButton:
                self.selectedPos = self.field.playerPos
                self.field.deselect()
                self.field.updateList()
                self.mode = 1

    #menu input
    def select(self, index):
        if index == 0:
            self.mode = 2
            self.field.setSelected(self.selectedPos)
            self.field.updateList()
            
        #leave dungeon
        elif index == 2:
            self.engine.dungeon = None
            self.engine.viewport.changeScene("Maplist")
            
    def panTo(self, newPosition):
        #maker sure new position is a list, not tuple
        newPosition = list(newPosition)
        
        #force to new position when selecting tiles
        if self.mode == 2:
            self.position = newPosition
            
        self.cameraMotion = False
        if self.position[0] is not newPosition[0]:
            if abs(newPosition[0] - self.position[0]) > .5:
              self.position[0] += (newPosition[0]-self.position[0])*.05
            else:
              self.position[0] = newPosition[0]
            self.cameraMotion = True
        if self.position[1] is not newPosition[1]:
            if abs(newPosition[1] - self.position[1]) > .5:
                self.position[1] += (newPosition[1]-self.position[1])*.05
            else:
                self.position[1] = newPosition[1]
            self.cameraMotion = True
        
    def render(self, visibility):
        w,h = self.engine.w, self.engine.h        
        
        self.panTo((self.panX, self.panY))
        if not self.mode == 0:
            self.panX = w/2
            self.panY = h/2
            
        if self.mode == 2:
            self.field.setCenter(self.selectedPos)
        else:
            self.field.setCenter()
                
        glPushMatrix()
        glTranslatef(1,1,-1000)
        self.background.draw()
        glPopMatrix()
                
        glPushMatrix()
        glTranslatef(self.position[0],self.position[1],-32.0*(max(self.field.dimensions[0],self.field.dimensions[1])+max(self.field.playerPos[0], self.field.playerPos[1])))
        if not self.field.rotateTo(self.angle):
            if self.angle > 360:
                self.angle %= 360
                self.field.angle = self.angle
            if self.angle < 0:
                self.angle += 360
                self.field.angle = self.angle
        else:
            self.cameraMotion = True
        self.field.render()
        glPopMatrix()
        
        self.bigFont.setText("%iH" % self.field.grid[self.selectedPos].height)
        self.bigFont.draw()
        
        '''Debug Position
        if self.mode == 2:
            location = "%s > %s" % (str(self.field.playerPos), str(self.selectedPos))
        else:
            location = "%s" % str(self.field.playerPos)
        self.font.setText(location)
        self.font.draw()
        '''
        
        self.compassbase.draw()
        self.compass.setAngle(self.field.angle)
        self.compass.draw()
        
        if self.mode == 1:
            self.actionMenu.render()
Exemplo n.º 48
0
B = 0.1 # [T]
E = 0.0 # [V/m]


V0 = numpy.array([1e5, 2e5, 1.5e5]) # initial velocity, [m/s]
X0 = numpy.array([0., 0., 0.]) # initial position


electrons = numpy.empty(Ne, dtype=Particle)
ions = numpy.empty(Ni, dtype=Particle)


electrons[0] = Particle(X0, V0, -e, me, dt_e)


field = Field(Nx, Ny, Nz, Lx, Ly, Lz)
field.initE(E)
field.initB(B)

trace = numpy.zeros((3, 100))

for i in range(100):
    field.updateTho(electrons, ions)

    field.updateParticleProps(electrons)

    for particle in electrons:
        particle.updateVX()

    print(i, electrons[0].X)
    trace[:, i] = electrons[0].X.copy()
Exemplo n.º 49
0
class SubWindow(QtGui.QScrollArea):
    sequenceNumber = 1
    x = 0
    y = 0
    timerId = 0
    step = 2
    delay = 50
    cellsCount = 0

    def __init__(self, width, height):
        super(SubWindow, self).__init__()
        self.width = width
        self.height = height
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.isUntitled = True
        widget = QtGui.QScrollArea()
        self.qp = QtGui.QPainter()
        if width and height:
            self.field = Field(width, height)
            self.setWidget(self.field)
            self.life = Life(width, height, False)
            self.reset()
            self.field.cells = self.life.cells

    def isSimulate(self):
        if self.timerId:
            return True
        return False

    def reset(self):
        self.life.reset(self.width, self.height)
        self.field.cells = self.life.cells
        self.field.update()
        if self.timerId:
            self.killTimer(self.timerId)
            self.timerId = 0

    def changeSpeed(self, speed):
        self.delay = speed
        if self.timerId:
            self.killTimer(self.timerId)
            self.timerId = self.startTimer(speed)

    def play(self):
        if not self.timerId:
            self.timerId = self.startTimer(self.delay)
        else:
            self.killTimer(self.timerId)
            self.timerId = 0

    def nextStep(self):
        self.field.cells = self.life.simulate()
        self.field.update()

    def timerEvent(self, event):
        self.field.cells = self.life.simulate()
        self.field.update()

    def currentFile(self):
        return self.curFile

    def new(self):
        self.isUntitled = True
        self.curFile = "Game %d" % SubWindow.sequenceNumber
        SubWindow.sequenceNumber += 1
        self.setWindowTitle(self.curFile + '[*]')

    def loadFile(self, fileName):
        file = QtCore.QFile(fileName)
        if not file.open( QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, "Reading error",
                    "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return False
        instr = QtCore.QTextStream(file)
        start = False
        width = 0
        lines = []

        while not instr.atEnd():
            line = instr.readLine()
            if width < len(line):
                width = len(line)
            if line[0] != '#':
                start = True
                lines.append(line)
            if line[0] == '#' and start:
                break

        height = len(lines)   
        if not width or not height:
            return False 
        self.width = width
        self.height = height
        self.field = Field(width, height)
        self.setWidget(self.field)
        self.life = Life(width, height, False)
        self.field.cells = self.life.cells
        y=0
        for line in lines:
            x = 0
            for char in line:
                if char == '*':
                    self.life.cells[x,y] = True
                x += 1
            y += 1

        self.field.update()        
        self.setCurrentFile(fileName)
        return True

    def save(self):
        if self.isUntitled:
            return self.saveAs()
        else:
            return self.saveFile(self.curFile)

    def saveAs(self):
        fileName, filtr = QtGui.QFileDialog.getSaveFileName(self, "Save As",
                self.curFile+'.lif')
        if not fileName:
            return False

        return self.saveFile(fileName)

    def saveFile(self, fileName):
        file = QtCore.QFile(fileName)

        if not file.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, "Writing error",
                    "Cannot write file %s:\n%s." % (fileName, file.errorString()))
            return False
        outstr = QtCore.QTextStream(file)
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
        for cells in array(self.life.cells).T:
            for cell in cells:
                if cell:
                    outstr << '*'
                else:
                    outstr << '.'
            outstr << "\n"
        QtGui.QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        return True

    def setCurrentFile(self, fileName):
        self.curFile = QtCore.QFileInfo(fileName).canonicalFilePath()
        self.isUntitled = False
        self.setWindowTitle(self.userFriendlyCurrentFile() + "[*]")

    def userFriendlyCurrentFile(self):
        return self.strippedName(self.curFile)

    def currentFile(self):
        return self.curFile

    def strippedName(self, fullFileName):
        return QtCore.QFileInfo(fullFileName).fileName()
Exemplo n.º 50
0
def jouer():

    pygame.init()
    fenetre = pygame.display.set_mode(screen_size)

    # definir tous fonds
    fondEcran = ["salle", "Terrain", "terrain3", "terrain4", "terrain5", "terrain6", "panda_roux"]
    #choix aléatoire du fond
    numFond = random.randint(0, len(fondEcran) - 1)
    fond = pygame.image.load(fondEcran[numFond] + ".png").convert_alpha()
    menu_fond = pygame.image.load("fondPython.jpeg").convert()
    fenetre.blit(menu_fond, (0,0))

    carte_hand = 0, 500, 1300, 800


    carte_posx = 200

    fields = []

    eposy = 100
    menus = [
                {"element" : pygame.image.load("bouton_1_vsIA.png").convert_alpha(), "name" : "jouer VS IA", "posx" : 10, "posy" : 100 },
                {"element" : pygame.image.load("pvp.png").convert_alpha(), "name" : "jouer VS joueur", "posx" : 900, "posy" : 100 },
                {"element" : pygame.image.load("bouton_quitter.png").convert_alpha(), "name" : "quitter", "posx" : 30, "posy" : 250 }
            ]

    endOfRound = {"button" : pygame.image.load("endOfRound.png").convert_alpha(), "name" : "yop", "posx" : 1000, "posy" : 350}
    for i, menu in enumerate(menus) :
        menu_size = menu["element"].get_rect()
        menu["posx"] = (screen_size[0] / 2) - (menu_size[2] / 2) 
        menu["posy"] = eposy
        fenetre.blit(menu["element"], (menu["posx"], menu["posy"]))
        eposy += (menu_size[3] / 2) + menu_size[3]

    pygame.display.flip()

    mode_game = 0
    continuer = 1
    continuer_menu = 1
    continuer_game = 1
    continuer_gameMenu = 0
    saisi_carte = 0
    saisi_attack = 0
    carte_selection_id = 0
    carte_selection = ()
    carte_attack_id = 0
    carte_attack = ()
    deplacement = 5
    positionOk = 0
    full = 0
    pygame.key.set_repeat(400, 30)
    winner = None
    turn = ["one", "two"]


    while continuer : # boucle général
        if continuer_menu == 1:
            fenetre.blit(menu_fond, (0,0))
            for menu in menus :
                fenetre.blit(menu["element"], (menu["posx"], menu["posy"]))

            pygame.display.flip()

        while continuer_menu: # boucle du menu
            for event in pygame.event.get():   #On parcours la liste de tous les événements reçus
                if event.type == QUIT: #Si un de ces événements est de type QUIT
                    continuer_game = 0
                    continuer_menu = 0
                    winner = False
                    continuer = 0

                if event.type == KEYDOWN : # lorsqu'on appui sur un touche du clavier

                    if event.key == K_ESCAPE: # esc on quitte le jeu
                        continuer_game = 0
                        continuer_menu = 0
                        winner = False
                        continuer = 0

                if event.type == MOUSEBUTTONUP: 

                    eposx = event.pos[0]
                    eposy = event.pos[1]
                    if event.button == 1 :
                        for menu in menus:
                            menu_size = menu["element"].get_rect()
                            posx, posy = menu["posx"], menu["posy"]
                            if( ( eposx >= posx and eposx <= (menu_size[2] + posx) ) and ( eposy >= posy and eposy <= (menu_size[3] + posy) ) ):
                                if menu["name"] == "jouer VS IA" :
                                    mode_game = 1
                                    continuer_menu = 0
                                    continuer_game = 1
                                    continuer = 1
                                    #initialiser les cartes du joueur 1
                                    CardSet.loadCardSet("cardSet")
                                    playerOne = Player("koala", CardSet.listCardG, False)
                                    #initilaiser les cartes du joueur 2
                                    CardSet.loadCardSet("cardSet2")
                                    playerTwo = Player("panda", CardSet.listCardG, True)
                                    winner = None
                                    t = random.randint(0, len(turn) - 1)
                                    turnIdx = t
                                    i = 0
                                    #fenetre = pygame.display.set_mode(screen_size, FULLSCREEN)

                                if menu["name"] == "jouer VS joueur" :
                                    mode_game = 2
                                    continuer_menu = 0
                                    continuer_game = 1
                                    continuer = 1
                                    #initialiser les cartes du joueur 1
                                    CardSet.loadCardSet("cardSet")
                                    playerOne = Player("koala", CardSet.listCardG, False)
                                    #initilaiser les cartes du joueur 2
                                    CardSet.loadCardSet("cardSet2")
                                    playerTwo = Player("panda", CardSet.listCardG, True)
                                    winner = None
                                    t = random.randint(0, len(turn) - 1)
                                    turnIdx = t
                                    i = 0
                                    #fenetre = pygame.display.set_mode(screen_size, FULLSCREEN)

                                if menu["name"] == "quitter" :
                                    mode_game = 0
                                    continuer_menu = 0
                                    continuer_game = 0
                                    winner = False
                                    continuer = 0

        while winner == None :
            continuer_game = 1
            if full :
                fenetre = pygame.display.set_mode(screen_size, FULLSCREEN)
            else :
                fenetre = pygame.display.set_mode(screen_size)
            
            lifeBack,lifeBackEnemy,life,lifeEnemy, playerOne, playerTwo = carteHandAndField(playerOne, playerTwo)

            fenetre.blit(lifeBackEnemy, (0, 0))
            while continuer_game: # boucle du jeu

                fenetre.blit(fond, (0, 0))
                cartePosition(fenetre, playerOne, playerTwo, endOfRound)

                # health player and enemy
                posLifeBack = screen_size[0] - 120, (screen_size[1] - 100)
                posLifeBackEnemy = screen_size[0] - 120, 5
                fenetre.blit(lifeBack, posLifeBack)
                fenetre.blit(lifeBackEnemy, posLifeBackEnemy)
                lifeBackSize = lifeBack.get_rect()
                lifeBackEnemySize = lifeBackEnemy.get_rect()
                fenetre.blit(life, (posLifeBack[0] + lifeBackSize[2] / 2 - 15, posLifeBack[1] + lifeBackSize[3] / 2))
                fenetre.blit(lifeEnemy, (posLifeBackEnemy[0] + lifeBackEnemySize[2] / 2 - 15, posLifeBackEnemy[1] + lifeBackEnemySize[3] / 2))

                # mana player and enemy
                fenetre.blit(pygame.image.load("mana.png").convert_alpha(), (screen_size[0] - 50, 40))
                fenetre.blit(pygame.image.load("mana.png").convert_alpha(), (screen_size[0] - 50,screen_size[1] - 60))
                if(playerTwo.mana > 0):
                    fenetre.blit(pygame.image.load(str(playerTwo.mana) + ".png").convert_alpha(), (screen_size[0] - 35,55))
                else:
                    fenetre.blit(pygame.image.load("0.png").convert_alpha(), (screen_size[0] - 35,55))
                if(playerOne.mana > 0):
                    fenetre.blit(pygame.image.load(str(playerOne.mana) + ".png").convert_alpha(), (screen_size[0] - 35,screen_size[1] - 45))
                else :
                    fenetre.blit(pygame.image.load("0.png").convert_alpha(), (screen_size[0] - 35,screen_size[1] - 45))

                pygame.display.flip()

                for event in pygame.event.get():   #On parcours la liste de tous les événements reçus
                    if event.type == QUIT: #Si un de ces événements est de type QUIT
                        continuer_menu = 0
                        continuer_game = 0
                        winner = False
                        continuer = 0      #On arrête la boucle

                    if event.type == KEYDOWN : # lorsqu'on appui sur un touche du clavier

                        if event.key == K_ESCAPE: # esc on retourne au menu du jeu
                            continuer_game = 1
                            continuer_menu = 0
                            continuer_gameMenu = 1
                            continuer = 1

                    if event.type == MOUSEBUTTONUP:

                        eposx = event.pos[0]
                        eposy = event.pos[1]
                        if event.button == 1:
                            print("saisi_carte : " + str(saisi_carte))
                            print("saisi_attack : " + str(saisi_attack))
                        if saisi_carte == 0 :
                            if event.button == 1:
                                for i, carte in enumerate(playerOne.hand):
                                    carte_size = carte.carte["carte"].get_rect()
                                    posx, posy = carte.carte["posx"], carte.carte["posy"]
                                    if ( ( eposx >= posx and eposx <= (carte_size[2] + posx) ) and ( eposy >= posy and eposy <= (carte_size[3] + posy) ) ):
                                        pygame.mouse.set_cursor(*pygame.cursors.arrow)
                                        saisi_attack = 0
                                        saisi_carte = 1
                                        carte_selection = carte
                                        carte_selection_id = i
                                
                                roundButton_size = endOfRound["button"].get_rect()
                                if ( ( eposx >= endOfRound["posx"] and eposx <= (roundButton_size[2] + endOfRound["posx"]) ) and ( eposy >= endOfRound["posy"] and eposy <= (roundButton_size[3] + endOfRound["posy"]) ) ):
                                    for c in playerOne.field :
                                        c.carte["statu"] = 0
                                    pygame.mouse.set_cursor(*pygame.cursors.arrow)
                                    saisi_attack = 0
                                    playerTwo.pickUp(playerTwo.deck)
                                    if mode_game == 1 :
                                        winner = Field.playTurn2(playerTwo, playerOne)
                                        playerOne.pickUp(playerOne.deck)
                                        saisi_attack = 0
                                        continuer_game = 0
                                    elif mode_game == 2 :
                                        fenetre.blit(fond, (0, 0))
                                        fenetre.blit(pygame.image.load("wait.png").convert_alpha(), (0, 0))
                                        pygame.display.flip()
                                        time.sleep(5)
                                        playerOne, playerTwo = playerTwo, playerOne
                                        carteHandAndField(playerOne, playerTwo)
                                        saisi_attack = 0
                                        continuer_game = 0
                        else :
                            saisi_carte = 2
                            carte_selection_id = 0
                            if ( (eposx >= carte_hand[0] and eposx < carte_hand[2] ) and (eposy < carte_hand[1]) ):
                                if(carte.carte["cost"] <= playerOne.mana) :
                                    playerOne.deploy(playerTwo, carte)
                                    Power.attackServantMultiple(playerTwo, carte)
                                    Power.addHpMaxMultiple(playerOne, playerTwo, carte)
                                    Power.pickupCard(playerOne, carte)
                                    Power.dropCard(carte, playerTwo)
                                    if len(playerTwo.field) > 0 :
                                        for c in playerTwo.field :
                                            carte_size = c.carte["carte"].get_rect()
                                            posx, posy = c.carte["posx"], c.carte["posy"]
                                            if ( (event.button == 1) and ( eposx >= posx and eposx <= (carte_size[2] + posx) ) and ( eposy >= posy and eposy <= (carte_size[3] + posy) ) ):
                                                Power.attackServant(playerOne, playerTwo, carte)
                                                Power.addHpMax(playerOne, playerTwo, carte)
                                    print("cout mana : " + str(carte.carte["cost"]))
                            continuer_game = 0

                        if saisi_attack == 0 and saisi_carte == 0 :
                            print("saisi == 0")
                            if event.button == 1 :
                                for i, carte in enumerate(playerOne.field):
                                    carte_size = carte.carte["carte"].get_rect()
                                    posx, posy = carte.carte["posx"], carte.carte["posy"]
                                    if ( ( eposx >= posx and eposx <= (carte_size[2] + posx) ) and ( eposy >= posy and eposy <= (carte_size[3] + posy) ) ):
                                        if( carte.carte["statu"] == 0 ) :
                                            saisi_attack = 1
                                            pygame.mouse.set_cursor(*pygame.cursors.diamond)
                                            carte_attack = carte
                                            carte_attack_id = i

                        if saisi_attack != 0 :
                            if event.button == 1 :
                                lifeBackEnemySize = lifeBackEnemy.get_rect()
                                xPos = posLifeBackEnemy[0] + lifeBackEnemySize[2] / 2 - 15
                                yPos = posLifeBackEnemy[1] + lifeBackEnemySize[3] / 2
                                if ( ( eposx >= xPos and eposx <= (lifeBackEnemySize[2] + xPos) ) and ( eposy >= yPos and eposy <= (lifeBackEnemySize[3] + yPos) ) ):
                                    #attack les points de vie adverse
                                    pygame.mouse.set_cursor(*pygame.cursors.arrow)
                                    carte_attack.newFight(playerOne, playerTwo)
                                    carte_attack.carte["statu"] = 1
                                    saisi_attack = 0
                                    continuer_game = 0
                                for i, carte in enumerate(playerTwo.field):
                                    carte_size = carte.carte["carte"].get_rect()
                                    posx, posy = carte.carte["posx"], carte.carte["posy"]
                                    if ( ( eposx >= posx and eposx <= (carte_size[2] + posx) ) and ( eposy >= posy and eposy <= (carte_size[3] + posy) ) ):
                                        # attack carte adverse
                                        print("attack")
                                        carte_attack.newFight(playerOne, playerTwo, carte)
                                        pygame.mouse.set_cursor(*pygame.cursors.arrow)
                                        carte_attack.carte["statu"] = 1
                                        saisi_attack = 0
                                        continuer_game = 0
                                        break
                                    if ( ( eposx < posx and eposx > (carte_size[2] + posx) ) and ( eposy < posy and eposy > (carte_size[3] + posy) ) or ( eposx > xPos and eposx < (lifeBackEnemySize[2] + xPos) ) and ( eposy < yPos and eposy > (lifeBackEnemySize[3] + yPos) )):
                                        pygame.mouse.set_cursor(*pygame.cursors.arrow)
                                        saisi_attack = 0

                    if saisi_carte == 1 :
                        if event.type == MOUSEMOTION :
                            eposx = event.pos[0]
                            eposy = event.pos[1]
                            carte = playerOne.hand[carte_selection_id]
                            carte.carte["posx"], carte.carte["posy"] = (event.pos[0] - (carte_size[2] / 2) ), (event.pos[1] - (carte_size[3] / 2) )
                            pygame.display.flip()

                if saisi_carte == 2:
                    saisi_carte = 0


            while continuer_gameMenu :
                full, continuer_gameMenu, winner, continuer_game = menuJeux(fenetre)

            if(playerOne.health <= 0):
                winner = playerTwo.name
                continuer_game = 0
                continuer_menu = 1
            if(playerTwo.health <= 0):
                winner = playerOne.name
                continuer_game = 0
                continuer_menu = 1
            if(winner != None):
                print("Winner : " + str(winner))
Exemplo n.º 51
0
def findSolution(n, matrix):
	field = Field()
	field.createField(matrix)
	print(n)
	field.printField()

	solutions = Queue()

	minSolution = None
	solution = Solution(field)
	
	greenhouses = []
	for i in range(len(field.getCoords())):
		corner1 = field.getCoords()[i]
		for j in range(i,len(field.getCoords())):
			corner2 = field.getCoords()[j]
			greenhouse = Greenhouse(corner1.x,corner2.x,corner1.y,corner2.y)
			for coord in field.getCoords():
				if greenhouse.containsCoord(coord.x, coord.y):
					greenhouse.addContainedCoordinate(coord)
			if (greenhouse.getWastedCoordinates() < 10):
				greenhouses.append(greenhouse)
			# if (corner1.y==6 and corner1.x==2 and 
				# greenhouse.getNumberOfContainedCoordinates() == 10 and
				# greenhouse.getWastedCoordinates() == 0):
				# solution = []
				# solution.append(greenhouse)
				# newSolution = Solution(field)
				# newSolution.setGreenhouses(solution)
				# print(len(greenhouses))
				# newSolution.printSolution()			
								
	sorted(greenhouses, key=Greenhouse.getWastedCoordinates, reverse=True)
	nextQueue = Queue()
			
	for i in range(1,n+1):
		print(i)
		if (not nextQueue.empty()):
			solutions = nextQueue
		else:
			solutions.put((0,[]))
		
		while(not solutions.empty()):
			# print(solutions.qsize())
			sol = solutions.get()
			index = sol[0]
			solution = sol[1]
			
			if (len(solution) == i-1):
				# nextQueue.put((0,list(solution)))
				left = None
				right = None
				top = None
				bottom = None
				for coord in field.getCoords():
					inGreenhouse = False
					for greenhouse in solution:
						inGreenhouse = inGreenhouse or greenhouse.containsCoord(coord.x,coord.y)
					if (not inGreenhouse):
						if (left == None or coord.x < left):
							left = coord.x
						if (right == None or coord.x > right):
							right = coord.x
							top = coord.y
						if (top == None or coord.y < top):
						if (bottom == None or coord.y > bottom):
							bottom = coord.y
				
				if (not left == None):
					greenhouse = Greenhouse(left,right,top,bottom)
								
					overlaps = False
					for setGreenhouse in solution:
						if (setGreenhouse.overlaps(greenhouse)):
							overlaps = True
							break
					
					if (not overlaps):
						solution.append(greenhouse)
						newSolution = Solution(field)
						newSolution.setGreenhouses(solution)
						if (minSolution == None or newSolution.computeCost() < minSolution.computeCost()):
							minSolution = newSolution
				
			else:
				for ind in range(len(greenhouses)):
					overlaps = False
					greenhouse = greenhouses[ind]
					for setGreenhouse in solution:
						if (setGreenhouse.overlaps(greenhouse)):
							overlaps = True
							break
					
					if (not overlaps):
						newSolution = list(solution)
						newSolution.append(greenhouse)
						solutions.put((ind,newSolution))
						
	minSolution.printSolution()

f = open('rectangles.txt')
wholeFile = f.read()
tasks = wholeFile.split("\n\n")
task = tasks[2]
lines = task.split("\n")
n = int(lines[0])
matrix = "\n".join(lines[1:])
findSolution(n,matrix)
Exemplo n.º 52
0
class Game(object):

    def __init__(self):
        #filename variables
        self.music_name = ''
        self.map_name = ''
        self.level_image = ''
        #total enemy waves
        self.wave_max = 0
        #time before first wave
        self.first_wave_time = 0
        #time between waves after first
        self.wave_time = 0
        #starting player self
        self.start_res = 0
        #letter length for words in typer
        self.basic_tower_d = 3
        self.adv_tower_d = 3
        self.upgrade_d = 3
        self.enemy_wave_description = list()

        self.level = 0

        self.game_state = 'start_menu'
        
        #display frame counter
        self.frame = 0
        #total number of enemies sent
        self.enemy_sent = 0
        #total number of enemies that needs to be sent
        self.enemy_max = 0
        #enemy level
        self.enemy_level = 0
        #user resource total
        self.res = 700

        #map for current level
        self.the_map = Field('MAP/1.map')
        self.map_surface = self.the_map.get_map().convert()
        self.grid = self.the_map.get_grid()
        self.towers = self.the_map.towers
        self.enemies = dict()

        #initialize typer
        self.typer = Typer(3,None,1,0,0)
        self.typer.kill()


        self.time = 0
        self.typing_timer = 0

        self.wave_meter = None
        
        #title screen images
        self.title1 = pygame.image.load('IMG/title1.png').convert()
        self.title2 = pygame.image.load('IMG/title2.png').convert()
        #game over image
        self.the_end = pygame.image.load('IMG/end.png').convert()

        self.res_img = pygame.image.load('IMG/res_75.png').convert_alpha()
        self.level_finish = pygame.image.load('IMG/level_finish.png').convert()
        self.loading = pygame.image.load('IMG/loading.png').convert_alpha()
        self.help_screen = pygame.image.load('IMG/help.png').convert()

    #load a new level
    def LoadNextLevel(self):
        self.level += 1
        if self.level < 9:
            source = file('LEVEL/' + str(self.level) + '.level')
            self.music_name = str('MUSIC/' + source.readline().rstrip())
            self.wave_max = int(source.readline())
            self.first_wave_time = int(source.readline())
            self.wave_time = int(source.readline())
            self.res = int(source.readline())
            self.upgrade_d = int(source.readline())
            self.basic_tower_d = int(source.readline())
            self.adv_tower_d = int(source.readline())
            i = 0
            line = source.readline()
            line = line.split()
            num_waves = int(line[0])
            wave_type = line[1]
            while (i < self.wave_max):
                if i == num_waves:
                    line = source.readline()
                    line = line.split()
                    num_waves = int(line[0])
                    wave_type = line[1]
                self.enemy_wave_description.append(wave_type)
                i += 1
                    

            #initialize map from newly loaded self
            self.the_map = Field('MAP/' + str(self.level) + '.map')
            self.map_surface = self.the_map.get_map().convert()
            self.grid = self.the_map.get_grid()
            self.towers = self.the_map.towers
            self.enemies = dict()

            self.meter = WaveMeter(self.wave_max,(self.wave_time/40),(self.first_wave_time/40),self.enemy_wave_description)
            #reset all main variables
            self.current_level = pygame.image.load('IMG/level_' + str(self.level) + '_100.png').convert_alpha() 
            self.frame = 0
            self.enemy_sent = 0
            self.enemy_max = 0
            self.enemy_level = 0
            
        else:
            self.game_state = 'end'


    def Update(self,time):
        self.time = time
        self.frame+= 1
        
        if self.game_state == 'main':
        
            #update typing time if active
            if self.typer.active:
                self.typing_timer+= self.time
                
            #adds a resource every second
            if (self.frame % 40) == 0:
                self.res+= 1
            
            #sends a new enemy (if not at max) every 0.5 second
            if (self.frame%20) == 0 and self.enemy_sent < self.enemy_max :
                self.enemies[self.enemy_sent] = Enemy(self.enemy_wave_description[self.enemy_level],self.enemy_level, self.the_map.path, self.level)
                self.enemy_sent+= 1
            
            #adds another wave of enemies to be sent if time == wave_time
            if (self.frame % self.wave_time) == 0 and self.enemy_level < self.wave_max:
                self.enemy_max+= 10
                self.enemy_level+= 1
                self.frame = 0
            
            #all towers within range of enemy fire at first available
            all_dead = True
            for j in self.enemies:
                if self.enemies[j].alive:
                    all_dead = False
                    self.enemies[j].move(self.time)
                    for i in self.towers:
                        if dist(self.towers[i].center,self.enemies[j].loc) <= self.towers[i].range and self.towers[i].cool <= 0:
                            self.towers[i].fire(self.enemies[j])
                            if self.enemies[j].hp <= 0:
                                self.enemies[j].alive = False
                                self.res+= self.enemies[j].reward
                
                #if enemy has reached home base, end game
                if self.enemies[j].tile.kind == 'home base':
                    self.game_state = 'end'

            #update dams on the map
            self.the_map.update_dams(self.time)
            
            #if everything is dead and all waves sent, end level
            if all_dead and self.enemy_level == self.wave_max:
                self.game_state = 'end_level'
        
        if self.game_state == 'loading':
            #stop music
            pygame.mixer.stop()
            #load next level
            self.LoadNextLevel()
            #if game is not over play new music
            if self.game_state != 'end':
                music = pygame.mixer.Sound(self.music_name)
                music.play(-1)
                self.game_state = 'main'
        
        
    def ActivateTyper(self,x,y,typer_type):
        if typer_type == 'upgrade' and self.res >= 80:
            current_tile = self.grid[y][x]
            if (current_tile.kind == 'tower' and current_tile.upgrades < 10):
                pygame.mouse.set_visible(False)
                self.typer = Typer(self.upgrade_d,'upgrade',1,y,x)
                self.typing_timer = -1
        elif typer_type == 'tower' and self.res >= 150:
            current_tile = self.grid[y][x]
            if (current_tile.kind == 'grass'):
                pygame.mouse.set_visible(False)
                self.typer = Typer(self.basic_tower_d,'tower',2,y,x)
                self.typing_timer = -1
        elif typer_type == 'rapid' and self.res >= 300:
            current_tile = self.grid[y][x]
            if (current_tile.kind == 'tower' and current_tile.title == 'Basic Tower'):
                pygame.mouse.set_visible(False)
                self.typer = Typer(self.adv_tower_d,'rapid',3,y,x)
                self.typing_timer = -1
        elif typer_type == 'snipe' and self.res >= 500:
            current_tile = self.grid[y][x]
            if (current_tile.kind == 'tower' and current_tile.title == 'Basic Tower'):
                pygame.mouse.set_visible(False)
                self.typer = Typer(self.adv_tower_d,'snipe',3,y,x)
                self.typing_timer = -1
        elif typer_type == 'dam' and self.res >= 50:
            current_tile = self.grid[y][x]
            if (current_tile.kind == 'road'):
                pygame.mouse.set_visible(False)
                self.typer = Typer(self.upgrade_d,'dam',1,y,x)
                self.typing_timer = -1
        
        


    #execute on completion of a typing challenge
    def TypeComplete(self):
        if self.typer.type == 'tower':
            self.the_map.add_tower(self.typer.y,self.typer.x)
            tower = self.grid[self.typer.y][self.typer.x]
            tower.skill_modifier(self.typer.wrong,self.typing_timer)
            self.res-= 150
        elif self.typer.type == 'upgrade':
            current_tile = self.grid[self.typer.y][self.typer.x]
            current_tile.upgrade(self.typer.wrong,self.typing_timer)
            self.res-= 80
        elif self.typer.type == 'rapid':
            tower = self.grid[self.typer.y][self.typer.x]
            tower.rapid_upgrade(self.typer.wrong,self.typing_timer)
            self.res-= 300
        elif self.typer.type == 'snipe':
            tower = self.grid[self.typer.y][self.typer.x]
            tower.snipe_upgrade(self.typer.wrong,self.typing_timer)
            self.res-= 500
        elif self.typer.type == 'dam':
            self.the_map.add_dam(self.typer.y,self.typer.x)
            self.res-= 50


    def KillTyper(self):
        self.typer.kill()
Exemplo n.º 53
0
class Game(object):

    ## Game constructor
    # @param self The object pointer
    ## @var numSetsMade
    # The total number of sets the user has made so far.
    ## @var setsListTotal
    # A list of Sets the Game object maintains when it scans the field during game initialization.
    # This data field is primarily used to test the correctness of the sets from the field.
    ## @var setsMadeSoFar
    # A list that keeps track of the sets the user has made so far.
    ## @var numSetsTotal
    # The absolute total number of sets that are on the field to be found.
    ## @var cardChoices
    # A list that keeps track of the current set choices the users has made.
    # Once the user has made 3 card choices (i.e. len(_cardChoices) == 3), the Game Object verifies the Set.
    ## @var deckManager
    # Object which manages the use of the Beginner sized deck and the Normal size deck in gameplay.
    ## @var timerModeFlag
    # Boolean that determines whether the game should be run in timed mode.
    ## @var gamediff
    # Difficulty of the Game itself (a.k.a. the number of cards), Beginner/Novice uses 9 cards on the field, Advanced uses 12.
    # Default difficulty is Novice. (0 = Beginner and _beginnerFlag = True, 0 = Novice and _beginnerFlag = False, 2 = Advanced)
    ## @var timediff
    # Determines the difficulty of timed mode.
    # Easy by default when timed mode is turned on (0 = Easy, 1 = Medium, 2 = Hard).
    # Higher difficulties means less time to find sets. Game is in untimed mode by default
    ## @var numHints
    # Number of hints allotted to the user whenever a new game is started.
    ## @var field
    # An instance of a _Field object that the Game object uses to scan for sets,
    # reference field indices for card choices, etc.

    def __init__(self):

        self.numSetsMade = 0
        self.numSetsTotal = 0
        self.setsListTotal = []
        self.setsMadeSoFar = []
        self.cardChoices = []
        self.deckManager = DeckManager()
        self.timedModeFlag = False
        self.gamediff = Difficulty.NOVICE
        self.timeddiff = 0
        self.numHints = 3 if self.gamediff == Difficulty.ADVANCED else 2
        self.field = Field(3,4) if self.gamediff == Difficulty.ADVANCED else Field(3,3)

        self.deckManager.placeCardsOnField(self.field)
        if self.scanSetsOnField() != 4 + (2 if self.gamediff == Difficulty.ADVANCED else 0):
            self.resetGame()

    ## resets all data for the Game, this method was created because it was
    #  preferable than having overhead with creating a brand new instance and garbage collection
    #  If the number of sets found during the scan doesn't satisfy the required number of sets,
    #  redo the reset.
    # @param self The object pointer
    def resetGame(self):

        while True:
            self.numSetsMade = 0
            self.numSetsTotal = 0
            self.numHints = 3 if self.gamediff == Difficulty.ADVANCED else 2
            del self.setsListTotal[:]
            del self.setsMadeSoFar[:]
            del self.cardChoices[:]

            self.deckManager.collectCardsFromField(self.field)
            self.field.reset(3,3+(1 if self.gamediff == Difficulty.ADVANCED else 0)) #reset the existing field instance rather than create a new instance (a new instance doesn't work for some reason)
            self.deckManager.placeCardsOnField(self.field)
            
            if self.scanSetsOnField() == 4 + (2 if self.gamediff == Difficulty.ADVANCED else 0):
                break

    ##Checks over the field array to check all possible sets
    # @param self The object pointer
    # @return The number of sets found during the scan.
    def scanSetsOnField(self):

        rows = len(self.field)
        cols = len(self.field[0])
        for it in itertools.combinations(xrange(rows*cols), 3):
            i,j,k = it[0],it[1],it[2]
            c1 = self.field[i//cols][i%cols]
            c2 = self.field[j//cols][j%cols]
            c3 = self.field[k//cols][k%cols]
            if not self.verifySet([c1, c2, c3]):
                self.setsListTotal.append([i, j, k])
                if len(self.setsListTotal) == 4 + (2 if self.gamediff == Difficulty.ADVANCED else 0):
                    break
        self.numSetsTotal = len(self.setsListTotal)
        return self.numSetsTotal

    ##Given a list of EXACTLY 3 Card Objects, this method checks the attributes of the cards to
    # see if the cards form a given set. If so, return 'None', if not return the 2 attributes that violate the SET rule.
    # @param self The object pointer
    # @param ls The list of Card Objects (of length 3) whose attributes may or may not form a set.
    # @return None if the cards in the list form a set.
    # @return a 2-length tuple of string attributes that violate the set rule.
    def verifySet(self,ls):

        assert len(ls) == 3
        assert type(ls[0]) == Card
        assert type(ls[1]) == Card
        assert type(ls[2]) == Card
        
        d1 = ls[0].__dict__
        d2 = ls[1].__dict__
        d3 = ls[2].__dict__
        for attr in Card.attrdict:
            i,j,k = d1[attr],d2[attr],d3[attr]
            violators = self._verifyHelper([i, j, k])
            if violators:
                assert len(violators) == 2
                return Card.attrdict[attr][violators[0]], Card.attrdict[attr][violators[1]]
                #if the cards picked aren't a set then we return from the function.
                #We return the string attributes that violate the SET rule.

    ## A simple helper method for the verifySet function that actually checks the attributes
    #  @param A 3-length list of set attributes to determine if they violate the set rule of not
    #  @return A 2-length tuple of string attributes that violated the set rule, or None otherwise.
    def _verifyHelper(self,attributes):

        assert len(attributes) == 3
        if attributes[0] == attributes[1] and attributes[0] != attributes[2]:
            return attributes[0], attributes[2]

        if attributes[1] == attributes[2] and attributes[1] != attributes[0]:
            return attributes[1], attributes[0]

        if attributes[0] == attributes[2] and attributes[0] != attributes[1]:
            return attributes[0], attributes[1]

    ## Primary method used for testing the validity of the current card choices.
    #  It returns one of the following: A tuple of strings indicating the attributes
    #  that violated the set rule, or an integer indicating other wise.
    #  @return (1 == Repeated Set, 2 == Successful Set, (str,str) == choices don't form a set)
    def validateSet(self):

        assert len(self.cardChoices)
        choices = [i for i in self.cardChoices]
        if choices in self.setsMadeSoFar:
            return 1
        result = self.verifySet([self.field[i//self.field.cols()][i%self.field.cols()] for i in self.cardChoices])
        if not result:
            self.setsMadeSoFar.append(choices)
            self.numSetsMade+=1
            assert self.numSetsMade == len(self.setsMadeSoFar)
            return 2
        else:
            return result

    ## Primary method for processing _cardChoices. The length of the choice list must be less than 3 upon calling
    #  this function. If the choices passed in the function already exists in the choice list, it is removed.
    #  If the choices list hasn't reached 3 yet, returns 0. Otherwise, we call the validateSet() method and return
    #  the method's return value.
    #  @param self The object pointer
    #  @param i the card id on the field to be added to the card choices.
    #  @return 0 if the choice list hasn't reached length 3 yet
    #  @return 3 if a choice is to be removed from set.)
    #  @return a result from self.validateSet()
    def addCardChoice(self,i):

        assert len(self.cardChoices) < 3
        if i in self.cardChoices:
            self.cardChoices.remove(i)
            return 3
        else:
            self.cardChoices.append(i)
            if len(self.cardChoices) == 3:
                try:
                    self.cardChoices.sort()
                    return self.validateSet() #returns None if Set is valid, A tuple of card attributes otherwise.
                finally:
                    del self.cardChoices[:]
        return 0

    ##Sets the game difficulty of the current game.
    # Returns True if the difficulty change was successful, False if it wasn't.
    def changeGameDifficulty(self,difficulty):
        if self.gamediff == difficulty:
            return False
        if self.gamediff != difficulty:
            if self.gamediff == Difficulty.BEGINNER or difficulty == Difficulty.BEGINNER:
                self.deckManager.collectCardsFromField(self.field)
                self.deckManager.switchDecks()
        self.gamediff = difficulty
        return True

    ##Helper method which calculates the numbers of sets remaining to find.
    # @param self The Object Pointer
    # @return The number of sets remaining on the field, or an error code representing a specific error.

    def callHint(self):
        if not self.numSetsRemaining():
            return HintErrorCode.GAMEOVER
        if not self.numHints:
            return HintErrorCode.OUTOFHINTS
        result = set(map(tuple,self.setsListTotal)) - set(map(tuple,self.setsMadeSoFar))
        result2 = set(result.pop()) - set(self.cardChoices)
        self.numHints-=1
        return result2.pop()
        #Complex function to choose a card on the field that's in a set that hasn't been made yet.
        #A shame that sets aren't indexable...or that you can't have a set of lists...

    def numSetsRemaining(self):

        return self.numSetsTotal-self.numSetsMade
Exemplo n.º 54
0
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
            self.FONT = self.boss.FONT
        else:
            self.boss = None
            self.FONT = "Dearest.ttf"

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        # Creation of two players
        self.player1 = Player(1)
        self.player2 = Player(-1)
        self.players = {1 : self.player1, -1 : self.player2}
        self.player1Hand = self.player1.hand
        self.player2Hand = self.player2.hand

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        # played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        self.position = None
        self.CARD = None
        self.infoCARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard, self)
        self.emptySquare = 9

        self.alphaAnimation = 255

        # Manage the winner congratulations font
        self.winner = Text("", self.FONT, white, 60)

        # Manage the display of the name of the card selected
        self.cardName = None

        # Do we show the name of the card selected?
        self.selectedCardName = 1
Exemplo n.º 55
0
 def parseXml(node):
     city = City()
     city.name = node.getAttribute("name")
     city.field = Field.parseXml(node.firstChild)
     return city
Exemplo n.º 56
0
class Application():
    """Main class of the game, manage the window"""
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
            self.FONT = self.boss.FONT
        else:
            self.boss = None
            self.FONT = "Dearest.ttf"

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        # Creation of two players
        self.player1 = Player(1)
        self.player2 = Player(-1)
        self.players = {1 : self.player1, -1 : self.player2}
        self.player1Hand = self.player1.hand
        self.player2Hand = self.player2.hand

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        # played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        self.position = None
        self.CARD = None
        self.infoCARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard, self)
        self.emptySquare = 9

        self.alphaAnimation = 255

        # Manage the winner congratulations font
        self.winner = Text("", self.FONT, white, 60)

        # Manage the display of the name of the card selected
        self.cardName = None

        # Do we show the name of the card selected?
        self.selectedCardName = 1


    def update(self):
        """Updates all the sprites on the window"""
        self.screen.blit(self.background, self.background.get_rect())
        self.screen.blit(self.field.surface, self.field.rect)

        for card in self.player1Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
              self.CARD.borderRect.topleft = self.CARD.rect.topleft
              self.screen.blit(self.CARD.border, self.CARD.borderRect)

        for card in self.player2Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
              self.CARD.borderRect.topleft = self.CARD.rect.topleft
              self.screen.blit(self.CARD.border, self.CARD.borderRect)

        self.scorePlayer1.update()
        self.scorePlayer2.update()
        self.screen.blit(self.scorePlayer1.surface, self.scorePlayer1.rect)
        self.screen.blit(self.scorePlayer2.surface, self.scorePlayer2.rect)
        if self.winner.text != "":
            self.winner.changeText()
            self.screen.blit(self.winner.surface, self.winner.rect)

        if self.selectedCardName != 0: 
            self.showName(1)
            self.showName(-1)

        if self.cardName != None:
                self.screen.blit(self.backCard, self.backCardRect)
                self.screen.blit(self.cardName.surface, self.cardName.rect)
                self.cardName = None

        if self.infoCARD == None:
        # If we aren't showing the about popup. Because About need to blit one
        # more thing before doing the following commands.
            pygame.display.flip()
            self.clock.tick(self.fps)

    def main(self):
        """Main part handling the game"""
        self.cardsOwner()
        self.update()
        while 1:
            if self.animation == 1:
                # We continue the animation
                self.putCard()
                self.update()
            else:
                # We over the animation and now the next player have to play.
                if self.sensAnimation == 1:
                    self.player = self.player * -1
                    self.sensAnimation = 0

            for event in pygame.event.get():
                if event.type == MOUSEBUTTONUP and self.animation == 0:
                    if event.button == 3 and self.winner.text == "":
                        if self.getCard(0):
                            self.showAbout()
                    if self.winner.text == "" and event.button == 1:
                        self.infoCARD = None
                        self.players[self.player].playCard(self)
                elif event.type == QUIT:
                    audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                    setConfig(audio)
                    self.field.saveState()
                    pygame.quit()
                    sys.exit()
                else:
                    # We get the status of all key on keyboard.
                    # Then we select the one at place 27: Escape.
                    # We can do this only if we ran the game
                    # with Menu.py and not directly from main.py
                    if pygame.key.get_pressed()[27] and self.boss != None:
                        self.boss.main()

            pygame.display.flip()
            self.clock.tick(self.fps)

    def putCard(self):
        """Animation of a card put on the field"""

        if self.CARD.inHand == 1:
        # We check if self..CARD is in the player's Hand
            self.Sound.playPutCard()

        # We drop the card off the Hand
        if self.CARD.inHand == 1:
            self.CARD.inHand = 0

        # Depending of the direction of the animation, we make the card
        # being invisible or visible again.
        if self.sensAnimation == 0:
            self.alphaAnimation -= 25 + (self.fps / 30.0 * 5)
            if self.alphaAnimation < 0:
                self.alphaAnimation = 0
            self.CARD.image.set_alpha(self.alphaAnimation)
            self.CARD.rect.centerx += 2 * self.player
        elif self.sensAnimation == 1:
            self.alphaAnimation += 25 + (self.fps / 30.0 * 5)
            if self.alphaAnimation > 255:
                self.alphaAnimation = 255
            self.CARD.image.set_alpha(self.alphaAnimation)

        # We change the position of the card and the animation's direction
        if self.CARD.image.get_alpha() <= 25:
            self.CARD.rect = self.Square
            self.sensAnimation = 1

        if self.CARD.image.get_alpha() == 255 and self.sensAnimation == 1:
            # We have put the card on the field and the animation is over.
            # We compare the elements to give potential malus/bonus.
            # And we have to look if that card captured some of the
            # ennemy's.
            self.animation = 0
            squareElement = self.field.elementName[self.numberSquare]
            if squareElement != None:
                self.Sound.playElement(squareElement)
            if self.CARD.elementName == squareElement \
            and squareElement != None:
                self.CARD.addModifier(1)
            else:
                if squareElement != None:
                    self.CARD.addModifier(-1)
            adjacentCards = self.getAdjacent()
            capturedCard = adjacent(self.CARD, adjacentCards)
            self.changeOwner(capturedCard)
            self.emptySquare -= 1
            self.CARD = None

        if self.emptySquare == 0:
            self.winAnimation()

    def selectedCard(self):
        """Player has selected a card
        But not yet a place on the field"""
        for i in [1, 2, 3, 4, 5]:
            self.CARD.rect.centerx += 4 * self.player
            self.update()

    def deselectedCard(self):
        """Finally, the player wants an other card"""
        for i in [1, 2, 3, 4, 5]:
            self.CARD.rect.centerx -= 4 * self.player
        self.CARD = None
        self.update()

    def squareFilled(self):
        """Say if there is already a card in the square"""
        for card in self.player1Hand.cards:
            if card.rect == self.Square:
                return 1
        for card in self.player2Hand.cards:
            if card.rect == self.Square:
                return 1
        return 0

    def cardsOwner(self):
        """Which cards is owned by who?"""
        cardPlayer = 0
        cardPlayer += self.player1Hand.cardsOwner()
        self.scorePlayer1.updateScore(cardPlayer)
        self.scorePlayer2.updateScore(10 - cardPlayer)

    def getAdjacent(self):
        """Get all the adjacent cards of the first one put"""
        posx, posy = self.CARD.rect.topleft
        adjacentCards = [None, None, None, None]
        if self.player == 1:
            for card in self.player2Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        elif self.player == -1:
            for card in self.player1Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        return adjacentCards

    def changeOwner(self, cards):
        for card in cards:
            if card.owner == 1:
                self.player1Hand.cards.remove(card)
                self.player2Hand.cards.append(card)
            if card.owner == -1:
                self.player2Hand.cards.remove(card)
                self.player1Hand.cards.append(card)
            self.capturedAnimation(card)
        self.cardsOwner()

    def capturedAnimation(self, card):
        """Shows a little animation when capturing card"""
        # We want the sound of the card put played before doing anything more
        self.update()
        while (pygame.mixer.get_busy()):
            pass

        # self.Sound.capturedCard.play()
        width = card.rect.width  # we expect 113. If not please change format.
        height = card.image.get_rect().height  # Here we expect 139.
        topleft = list(card.rect.topleft)
        step = 30 - (self.fps / 30 * 3)

        while(width != 10):
            width -= step
            if width < 10:
                width = 10
            topleft[0] += step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        card.owner *= -1
        card.changeOwner()

        while (width != 113):
            width += step
            if width > 113:
                width = 113
            topleft[0] -= step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        # If card has a bonus or malus, we have to re-draw it on the card
        if card.modifierValue != 0:
            card.image.blit(card.modifierBack.surface, card.modifierBack.rect)
            card.image.blit(card.modifier.surface, card.modifier.rect)

    def winAnimation(self):
        """Show who won the game"""
        if self.scorePlayer1.score > self.scorePlayer2.score:
            self.winner.text = _("Blue win!")
            self.winner.rect.topleft = self.backgroundRect.midtop
            self.winner.rect.x -= 20
            self.winner.color = blue
        elif self.scorePlayer2.score > self.scorePlayer1.score:
            self.winner.text = _("Red win!")
            self.winner.rect.topright = self.backgroundRect.midtop
            self.winner.rect.x += 20
            self.winner.color = red
        else:
            self.winner.text = _("Equality!")
            self.winner.rect.topleft = self.backgroundRect.midtop
            self.winner.color = white

        self.winner.changeColor()
        self.winner.rect.y += 10

    def getCard(self, player):
        """Return the card at pygame.mouse.get_pos() coordinates """
        coords = pygame.mouse.get_pos()
        if player == 1:
            card = self.player1Hand.getCard(coords)
            if card >= 0:
                if self.CARD != None:
                    self.deselectedCard()
                self.CARD = self.player1Hand.cards[card]
        elif player == -1:
            card = self.player2Hand.getCard(coords)
            if card >= 0:
                if self.CARD != None:
                    self.deselectedCard()
                self.CARD = self.player2Hand.cards[card]
        elif player == 0:
            #If we get a right-click, then we want to print the About
            #popup even if it is an ennemy's card
            card = self.player1Hand.getCard(coords)
            if card != None:
                self.infoCARD = self.player1Hand.cards[card].About
            else:
                card = self.player2Hand.getCard(coords)
                if card != None:
                    self.infoCARD = self.player2Hand.cards[card].About
        if card != None:
            return 1
        return 0

    def showAbout(self):
        """Show some info on the card if we do a right-click on it"""
        width = 0
        quit = 0
        maxWidth = 450
        COLORRED = (200,0,0,125)
        COLORBLUE = (0,0,200,125)
        event = None
        if self.infoCARD.boss.owner == 1:
            COLOR = COLORBLUE
        elif self.infoCARD.boss.owner == -1:
            COLOR = COLORRED

        background = pygame.Surface((width, 140), SRCALPHA)
        rect = background.get_rect()
        background.fill(COLOR)

        if self.infoCARD.boss.owner == 1:
            rect.topleft = self.infoCARD.boss.rect.topright
        elif self.infoCARD.boss.owner == -1:
            rect.topright = self.infoCARD.boss.rect.topleft

        while 1:
            self.update()
            self.screen.blit(background,rect)
            pygame.display.flip()
            self.clock.tick(self.fps)

            if width < maxWidth and quit == 0:
                width += 40 - (self.fps / 30.0 * 5) 
                if width > maxWidth:
                    width = maxWidth
                background = pygame.Surface((width, 140), SRCALPHA)
                rect = background.get_rect()
                background.fill(COLOR)
                if self.infoCARD.boss.owner == 1:
                    rect.topleft = self.infoCARD.boss.rect.topright
                elif self.infoCARD.boss.owner == -1:
                    rect.topright = self.infoCARD.boss.rect.topleft

            if quit == 1:
                width -= 40 - (self.fps / 30.0 * 5)
                if width < 0:
                    width = 0
                background = pygame.Surface((width, 140), SRCALPHA)
                rect = background.get_rect()
                background.fill(COLOR)
                if self.infoCARD.boss.owner == 1:
                    rect.topleft = self.infoCARD.boss.rect.topright
                elif self.infoCARD.boss.owner == -1:
                    rect.topright = self.infoCARD.boss.rect.topleft

            if width == 0:
                if quit == 1:
                    self.update()
                    return
                quit = 1

            if width == maxWidth and quit == 0:
                background.fill(COLOR)
                background.blit(self.infoCARD.surface, self.infoCARD.rect)
                self.update()
                self.screen.blit(background,rect)
                pygame.display.flip()
                self.clock.tick(self.fps)
                event = pygame.event.wait()

            if width == 0:
                self.infoCARD = None
                self.update()
                return 0

            if event and event.type == MOUSEBUTTONUP:
                quit = 1
            elif event and event.type == QUIT:
                audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                setConfig(audio)
                pygame.quit()
                sys.exit()

        return 0

    def showName(self, player):
        """Show the name of the card selected at the bottom of the window"""
        self.backCard, self.backCardRect = loadImage("name.png")

        if player == 1:
            for card in self.player1Hand.cards:
                if card == self.CARD:
                    name = self.CARD.name
                    self.cardName = Text(name, self.FONT, white, 40)
        elif player == -1:
            for card in self.player2Hand.cards:
                if card == self.CARD:
                    name = self.CARD.name
                    self.cardName = Text(name, self.FONT, white, 40)

        if self.cardName != None:
            self.cardName.rect.midbottom = self.backgroundRect.midbottom
            self.cardName.rect.y -= 10
            self.backCardRect.center = self.cardName.rect.center
Exemplo n.º 57
0

X0_e = numpy.zeros((Ne, 3))  # initial velocity of electrons, [m/s]
X0_i = numpy.zeros((Ni, 3))  # initial velocity of ions, [m/s]

electrons = numpy.empty(Ne, dtype=Particle)
ions = numpy.empty(Ni, dtype=Particle)


for i in range(Ne):
    electrons[i] = Particle(X0_e[i, :], V0_e[i, :], -e, me, dt_e)
for i in range(Ni):
    ions[i] = Particle(X0_i[i, :], V0_i[i, :], e, mi, dt_i)


field = Field(Nx, Ny, Nz, Lx, Ly, Lz)
field.initE(E)
field.initB(B)

trace_i = numpy.zeros((Ne, 3, 100))
trace_e = numpy.zeros((Ni, 3, 100))

for i in range(100):
    field.updateTho(electrons, ions)

    field.solveE(eps0)

    field.updateParticleProps(electrons)
    field.updateParticleProps(ions)

    for particle in electrons:
Exemplo n.º 58
0
 def __init__(self, engine):
     self.engine = engine
     
     name = self.engine.dungeon                    #name of the dungeon
     path = os.path.join("places", name)           #path to the dungeon
     
     self.dungeonini = Configuration(os.path.join("..", "data", path, "dungeon.ini")).dungeon
                                                   #config file
     self.formations = [f.strip() for f in self.dungeonini.formations.split(",")]
     self.otherevents = [e.strip() for e in self.dungeonini.events.split(",")]
     self.field = Field(self, path)                #the field data (grid)
     
     #ogg or mp3 support for background music
     self.music = BGMObj(os.path.join(path, "bgm.mp3"), fullpath = True)
     if not self.music:
         self.music = BGMObj(os.path.join(path, "bgm.ogg"), fullpath = True)
         
             
     w,h = self.engine.w, self.engine.h        
     
     #background image
     self.background = ImgObj(os.path.join(path, "background.png"))
     self.background.setScale(self.engine.w, self.engine.h, inPixels = True)
     self.background.setPosition(w/2,h/2)
     
     #displays the current map direction
     self.compassbase = ImgObj(os.path.join("scenes", "dungeon", "compassbase.png"))
     self.compassbase.setPosition(w*.1, h*.1)
     self.compassbase.setScale(256, 256, True)
     self.compass = ImgObj(os.path.join("scenes", "dungeon", "compass.png"))
     self.compass.setPosition(w*.1, h*.1)
     self.compass.setScale(256, 256, True)
     
     #displays coordinates of the player
     self.font = FontObj("default.ttf", size = 32)
     self.font.setPosition(w*.5,h*.1)
     
     #displays player height
     self.bigFont = FontObj("default.ttf", size = 72)
     self.bigFont.setPosition(w*.8,h*.9)
     
     self.selectedPos = self.field.playerPos       #selected position for movement
     self.distance = 0
     
     #camera controls
     self.position = [w/2,h/2]
     self.panX = w/2
     self.panY = h/2
     self.cameraMotion = False
     self.angle = 135.0
     if self.field.playerPos[0] > self.field.dimensions[0]/2:
         if self.field.playerPos[1] > self.field.dimensions[1]/2:
             self.angle = 225.0
         else:
             self.angle = 135.0
     else:
         if self.field.playerPos[1] > self.field.dimensions[1]/2:
             self.angle = 45.0
         else:
             self.angle = 315.0
       
     
     self.mode = 0                                 #0 = view, 1 = action menu, 2 = move
     
     self.actionMenu = MenuObj(self, ["Move", "Menu", "Escape"], (w*.8, h*.25), window = "window.png")
     
     self.moveKeys = {}                            #keys used for tile selection
     self.updateKeys()
Exemplo n.º 59
0
    def __init__(self):
        #filename variables
        self.music_name = ''
        self.map_name = ''
        self.level_image = ''
        #total enemy waves
        self.wave_max = 0
        #time before first wave
        self.first_wave_time = 0
        #time between waves after first
        self.wave_time = 0
        #starting player self
        self.start_res = 0
        #letter length for words in typer
        self.basic_tower_d = 3
        self.adv_tower_d = 3
        self.upgrade_d = 3
        self.enemy_wave_description = list()

        self.level = 0

        self.game_state = 'start_menu'
        
        #display frame counter
        self.frame = 0
        #total number of enemies sent
        self.enemy_sent = 0
        #total number of enemies that needs to be sent
        self.enemy_max = 0
        #enemy level
        self.enemy_level = 0
        #user resource total
        self.res = 700

        #map for current level
        self.the_map = Field('MAP/1.map')
        self.map_surface = self.the_map.get_map().convert()
        self.grid = self.the_map.get_grid()
        self.towers = self.the_map.towers
        self.enemies = dict()

        #initialize typer
        self.typer = Typer(3,None,1,0,0)
        self.typer.kill()


        self.time = 0
        self.typing_timer = 0

        self.wave_meter = None
        
        #title screen images
        self.title1 = pygame.image.load('IMG/title1.png').convert()
        self.title2 = pygame.image.load('IMG/title2.png').convert()
        #game over image
        self.the_end = pygame.image.load('IMG/end.png').convert()

        self.res_img = pygame.image.load('IMG/res_75.png').convert_alpha()
        self.level_finish = pygame.image.load('IMG/level_finish.png').convert()
        self.loading = pygame.image.load('IMG/loading.png').convert_alpha()
        self.help_screen = pygame.image.load('IMG/help.png').convert()
Exemplo n.º 60
0
 def emplaceField(self, row, column):
     field = Field(row, column)
     field.setGameWindow(self)
     field.clicked.connect(self.revealFieldWrapper)
     self.boardLayout.addWidget(field, row, column)
     self.fields[row][column] = field