Пример #1
0
 def __init__(self):
     self.ready_to_service_events_str = gready_to_service_events_str
     Chip.__init__(self)
     if "JITTER_DISTRIBUTION_CURVE" in os.environ.keys():
         self.jitter_distribution_curve = int(
             os.environ["JITTER_DISTRIBUTION_CURVE"])
     else:
         self.jitter_distribution_curve = None
Пример #2
0
	def __init__(self):

		# set working directory
		abspath = os.path.abspath(__file__)
		dname = os.path.dirname(abspath)
		os.chdir(dname)
		print('Current directory: ' + subprocess.check_output('pwd').decode("utf-8"))

		# setting up motors
		print('Initializing motors')
		ports = faulhaber_port_numbers()
		self.motors = Motors(ports)

		# seting up camera
		print('Initializing camera')
		self.camera =  Camera(
			starting_exposure = 2745,
			color_mode = ids.ids_core.COLOR_BAYER_16
			)

		# setting up arduino communication
		print('Initializing arduino connection')
		self.arduino_conn = arduino_connection()

		self.cluster_size_threshold = 1000
		self.by_size = False
		self.nominal_laser_intensity = 41
		self.correct_for_laser = True

		print('Initializing mologram position control')
		self.chip = Chip(self.motors)

		print('Done')

		print('System booted normally')		
Пример #3
0
 def act_with_key(self):
     """調べたりする
     """
     # 押下時のみ反応させる
     if pyxel.btn(pyxel.KEY_SPACE):
         asset_id = self._check_forward()
         # 敵
         if Chip.is_enemy(asset_id):
             Dialog.draw("Enemy")
         # アイテム
         elif Chip.is_item(asset_id):
             Dialog.draw("Item")
             # 何かする
             # (i, j) = self._get_forward_map_pos()
             # self.map.set_map(i, j, 10)
         # カベ
         elif Chip.is_wall(asset_id):
             Dialog.draw("Wall")
Пример #4
0
def selfMode():
    global pauseCounter, objects, speed, score, bkgX, bkgX2
    global fallSpeed, event, powerups
    run = True
    avocado.falling = False
    score = 0
    while run:
        if pauseCounter > 0:
            pauseCounter += 1
            # delay before showing game over
            if pauseCounter * 40 > fallSpeed:
                gameOverScreen()

        newList = copy.copy(objects)
        for item in objects:
            # if instance of star, remove star from screen
            if item.collide(avocado.hitBox):
                if isinstance(item, Star):
                    newList.pop(objects.index(item))
                    score += 1
                elif isinstance(item, Chip):
                    avocado.jumping = True
                else:
                    avocado.sliding = True
            item.x -= 3
            # off the screen, get rid of the object
            if item.x < item.width * -3:
                newList.pop(newList.index(item))
        objects = newList
        # move background back leftwards
        bkgX -= 3
        # move background at different position
        bkgX2 -= 3
        # first background starts until the negative
        # width of the background
        if bkgX < bkg.get_width() * -1:
            bkgX = bkg.get_width()
        if bkgX2 < bkg.get_width() * -1:
            bkgX2 = bkg.get_width()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()
            if event.type == USEREVENT + 1:
                speed += 20
            if event.type == USEREVENT + 2:
                # every second, add star to screen
                rand = random.randrange(0, 2)
                if rand == 0:
                    objects.append(Chip(810, 340, 64, 64))
                else:
                    objects.append(Star(810, 340, 64, 64))

        clock.tick(speed)
        redrawWindow()
Пример #5
0
    def is_wall(self, i, j):
        # Check if a given coordinate is a wall
        # outside the map
        if i < 0 or self.MAP_WIDTH <= i:
            return True
        if j < 0 or self.MAP_HEIGHT <= j:
            return True

        # wall
        v = self.map[j][i]
        return Chip.is_wall(v)
Пример #6
0
 def get_bet(self):
     while True:
         try:
             bet_chips = int(input('How many chips would you like to bet ?'))
             chips = Chip()
             if bet_chips > chips.total:
                 print(f'You have {chips.total}, Please enter valid number')
             else:
                 return bet_chips
         except:
             print('Invalid number')
             continue
Пример #7
0
    def makeMove(self, view, col):
            
        if( self.chipCount > 0):

            for r in range(view.board.rows-1, -1, -1):
                if ((view.board.grid[r][col] == None)):
                    c1 = Chip(self.id, r, col, self.color)
                    view.board.grid[r][col] = c1 #make a chip at that area.
                    self.chipCount = self.chipCount - 1 #subtract a chip
                    view.display()
                    return view.board.checkIfWinner(c1) #check board at that position
        else:
            print(self.name + " has run out of chips!")
Пример #8
0
    def _get_forward_map_pos(self) -> tuple:
        """前方のmap座標を取得
        """
        cx, cy = Chip.get_center(self.x, self.y)
        h = Chip.IMG_HEIGHT
        w = Chip.IMGBANK_WIDTH
        if self.direction == "N":
            cy -= h
        elif self.direction == "E":
            cx += w
        elif self.direction == "W":
            cx -= w + 1  # TODO: 統一的に書いてほしい
        else:
            cy += h

        (i, j) = Map.to_map(cx, cy)
        return (i, j)
Пример #9
0
def play():
    deck = Deck()
    deck.shuffle()

    player_hand = Hand()
    player_hand.add_card(deck.deal())
    player_hand.add_card(deck.deal())

    player_chip = Chip()
    take_bet(player_chip)

    dealer_hand = Hand()
    dealer_hand.add_card(deck.deal())
    dealer_hand.add_card(deck.deal())

    show_card(player_hand, dealer_hand)

    while playing:
        hit_or_stand(deck, player_hand)
        show_card(player_hand, dealer_hand)
        if player_hand.value > 21:
            player_busted(player_hand, dealer_hand, player_chip)
            break

    if player_hand.value <= 21:

        while dealer_hand.value < 17:
            hit_hand(deck, dealer_hand)

        if dealer_hand.value > 21:
            dealer_busted(player_hand, dealer_hand, player_chip)
        elif dealer_hand.value > player_hand.value:
            dealer_won(player_hand, dealer_hand, player_chip)
        elif dealer_hand.value < player_hand.value:
            player_won(player_hand, dealer_hand, player_chip)
        else:
            push(player_hand, dealer_hand)

    print('player total chips are at {}'.format(player_chip.total))
Пример #10
0
class Setup:

	def __init__(self):

		# set working directory
		abspath = os.path.abspath(__file__)
		dname = os.path.dirname(abspath)
		os.chdir(dname)
		print('Current directory: ' + subprocess.check_output('pwd').decode("utf-8"))

		# setting up motors
		print('Initializing motors')
		ports = faulhaber_port_numbers()
		self.motors = Motors(ports)

		# seting up camera
		print('Initializing camera')
		self.camera =  Camera(
			starting_exposure = 2745,
			color_mode = ids.ids_core.COLOR_BAYER_16
			)

		# setting up arduino communication
		print('Initializing arduino connection')
		self.arduino_conn = arduino_connection()

		self.cluster_size_threshold = 1000
		self.by_size = False
		self.nominal_laser_intensity = 41
		self.correct_for_laser = True

		print('Initializing mologram position control')
		self.chip = Chip(self.motors)

		print('Done')

		print('System booted normally')		

	def photodiode_intensity(self):
		val = self.arduino_conn.read()
		val = ord(val)

		return val

	def calib(self):
		self.motors.calib()
		self.chip.move_to('B,1,1')

	def binary_search(
		self,
		increment,
		evaluate,
		starting_step,
		final_step,
		starting_direction,
		condition,
		max_difference
		):
		
		# initialize search parameters
		step = starting_step
		direction = starting_direction
		
		new_score, old_score, i = 0,0,0

		# divide
		while (abs(step) > final_step):
			
			# initialize score
			old_score = evaluate()
			increment(direction*step)
			new_score = evaluate()
				
			print('Exposure: ' + str(self.camera.exposure) + ', step: ' + str(step))
			print('New score: ' + str(new_score) + ', old score: ' + str(old_score))
			
			# keep incrementing until reach a local extrema
			while condition(old_score,new_score,direction,step):
				
				increment(direction*step)

				old_score = new_score
				new_score = evaluate()
				
				buffer_length = 3
				for i in range(buffer_length-1):
					new_scores[i] = old_scores[i+1]

				new_scores[buffer_length-1] = new_score				
				
				print('Exposure: ' + str(self.camera.exposure) + ', step: ' + str(step))
				print('New score: ' + str(new_score) + ', old score: ' + str(old_score))
			
			# update search parameters
			step *= 0.5
			direction *= -1
			
			i += 1
			if i > 100:
				return

	def max_pixel(self):
		num_pixels = 50
		buffer_length = 5
		values = np.empty(buffer_length)
		
		for i in range(buffer_length):  
			img,retval = self.camera.get_raw_img()
			values[i] = np.mean(heapq.nlargest(num_pixels, img.flatten()))
			#values[i] = np.max(img.flatten())
			
		value = np.mean(values)
		
		return value

	def adjust_exposure(self):
		saturation_value = 4095
		margin = 1

		final_step = 0.5
		max_difference = 5
		
		# condition = lambda old_score,new_score,direction: \
		#     (new_score >= old_score - margin) and not(new_score == 255 and direction == 1)
		
		condition = lambda old_score,new_score,direction,step: \
			(((new_score < saturation_value/2) and (direction ==  1))  or \
			((new_score > saturation_value/2) and (direction == -1)))  and \
			(abs(step) > final_step)

		
		self.binary_search(
			increment = lambda x: self.camera.set_exposure(self.camera.exposure + x),
			evaluate  = lambda: self.mologram_intensity(avg = True)[0],
			starting_step = 64,
			final_step = final_step,
			starting_direction = -1,
			condition = condition,
			max_difference = 5
		)
		
	def adjust_focus(self):
		saturation_value = 4095
		margin           = 20000
		max_difference   = 5000
		final_step       = 1
		starting_step    = 40

		evaluate  = lambda: processing.image_score(self.camera.get_raw_img()[0])
		increment = lambda x: self.motors.z.move_um(x)

		init_eval = evaluate()
		
		condition = lambda old_score,new_score,direction,step: \
			(new_score <= old_score + margin) #and \
			#((direction == 1) and (new_score >= saturation_value))
		
		self.binary_search(
			increment = increment,
			evaluate  = evaluate,
			starting_step = starting_step,
			final_step = final_step,
			starting_direction = 1,
			condition = condition,
			max_difference = max_difference
		)

		if evaluate() < init_eval:
			self.binary_search(
				increment = increment,
				evaluate  = evaluate,
				starting_step = starting_step,
				final_step = final_step,
				starting_direction = -1,
				condition = condition,
				max_difference = max_difference
			)
		
	def adjust_coupling(self):
		saturation_value = 4095
		margin = 5
		
		condition = lambda old_score,new_score,direction,step: \
			(new_score >= old_score - margin) and \
			((direction == 1) and (new_score >= saturation_value))
		
		self.binary_search(
			increment = lambda x: self.motors.TE.move_degrees(x),
			evaluate  = lambda: self.mologram_intensity(avg = True)[0],
			starting_step = 0.1,
			final_step = 0.01,
			starting_direction = 1,
			condition = condition,
			max_difference = 1
		)
Пример #11
0
 def draw_chip(cls, i, j, asset_id):
     """map座標(i, j)にasset_idのマップチップを描画
     """
     # Convert to screen coordinates of the chip image
     x, y = cls.to_screen(i, j)
     Chip.draw_asset(x, y, asset_id)
Пример #12
0
 def draw(self):
     asset_id = self._get_asset_id()
     Chip.draw_asset(self.x, self.y, asset_id)
     self.act_with_key()
Пример #13
0
                label = tk.Label(cacheL1P0C0,
                                 textvariable=dirVar,
                                 relief="solid",
                                 borderwidth=1)
                label.config(font=('Arial', 12))
            label.grid(row=row, column=column, sticky='news')
            cacheL1P0C0.columnconfigure(column, weight=1)

    stringvarsChips.append(thisVars)

UIManager = FrontEndManager(stringvarsChips[0], stringvarsChips[1],
                            stringvarsChips[2], stringvarsChips[3],
                            stringvarsChips[4], stringvarsChips[5],
                            stringvarsChips[6], PInstructionsVars[0],
                            PInstructionsVars[1], PInstructionsVars[2],
                            PInstructionsVars[3])

logging.info("Memoria principal inicializada")
mainMemory = Memory(UIManager)

connectionBus = []

logging.info('Chip 0 inicializado')
chip0 = Chip(0, mainMemory, UIManager, connectionBus)
logging.info('Chip 1 inicializado')
chip1 = Chip(1, mainMemory, UIManager, connectionBus)

chip0.start()
chip1.start()

root.mainloop()
Пример #14
0
def playHardGame():
    global pauseCounter, objects, speed, score, bkgX, bkgX2
    global fallSpeed, event, powerups
    run = True
    avocado.falling = False
    score = 0
    while run:
        if pauseCounter > 0:
            pauseCounter += 1
            # delay gives about 2 seconds
            if pauseCounter * 40 > fallSpeed:
                gameOverScreen()

        newList = copy.copy(objects)
        for item in objects:
            # if instance of star, remove star from screen
            if item.collide(avocado.hitBox):
                if isinstance(item, Star):
                    newList.pop(objects.index(item))
                    score += 1
                else:
                    avocado.falling = True
                    if pauseCounter == 0:
                        fallSpeed = speed
                        pauseCounter = 1
            item.x -= 7
            # off the screen, get rid of the object
            if item.x < item.width * -3:
                newList.pop(newList.index(item))
        objects = newList

        # move background back leftwards
        bkgX -= 7
        # move background at different position
        bkgX2 -= 7
        # first background starts until the negative
        # width of the background
        if bkgX < bkg.get_width() * -1:
            bkgX = bkg.get_width()
        if bkgX2 < bkg.get_width() * -1:
            bkgX2 = bkg.get_width()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()
            if event.type == USEREVENT + 5:
                speed += 60
            if event.type == USEREVENT + 6:
                # every second, add star to screen
                rand = random.randrange(0, 3)
                if rand == 0:
                    objects.append(Chip(810, 340, 64, 64))
                elif rand == 1:
                    objects.append(Star(810, 340, 64, 64))
                else:
                    objects.append(Onion(810, -0.5, 48, 320))

        keys = pygame.key.get_pressed()

        if keys[pygame.K_UP]:
            if not (avocado.jumping):
                avocado.jumping = True

        if keys[pygame.K_DOWN]:
            if not (avocado.sliding):
                avocado.sliding = True

        clock.tick(speed)
        redrawWindow()
Пример #15
0
 def __init__(self, name, total=100):
     self.name = name
     self.chip = Chip(total)
     self.hand = Hand()
     self.blackjack = False
     self.bust = False
Пример #16
0
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 09:52:41 2019

@author: pprashan
"""

from Deck import Deck
from Hand import Hand
from Chip import Chip
import Utils
 
playing = True


player_chips = Chip()   
#the game
    
while True:
    print('Welcome to BlackJack! Get as close to 21 as you can without going over!\n\
    Dealer hits until she reaches 17. Aces count as 1 or 11.')
    
    deck = Deck()
    deck.shuffle()
    
    player_hand = Hand()
    dealer_hand = Hand()
    
    player_hand.add_card(deck.deal())
    player_hand.add_card(deck.deal())
    
Пример #17
0
 def __init__(self):
     self.cards = [] # cards the player has
     self.aceCount = 0 # Ace card the player has
     self.points = 0 # total value of cards
     self.chips = Chip()