2015年6月29日 星期一

Python筆記:基本語法

Arithmetic

print int(3.14159)              #3
print type(3), type(3.14159)    #int float
print float(3)                  #3.0

#floating point number have around 15 decimal digits of accuracy
print 3.1415926535897932384626433832795028841971     #3.14159265359

#If one operand is a decimal (float), the answer is decimal
print 1.0 / 3, 5.0 / 2.0        #0.333333333333 2.5

Variables

命名方式為字母或是“_”
Dynamic
#The ones digit of a number
num = 49
tens = num // 10
ones = num % 10
print tens, ones
print 10 * tens + ones, num

Function

def triangle_area(base, height):     
    area = (1.0 / 2) * base * height 
    return area                      

a1 = triangle_area(3, 8)
print a1
def hello():
    print "Hello, world!"

hello()      
h = hello()  
print h 
Python modules - extra functions implemented outside basic Python.
import math         #access to standard math functions, e.g; trig
print math.pi   #3.14159265359

Conditions

#Return True if year is a leap year, false otherwise
def is_leap_year(year):
    if (year % 400) == 0:
        return True
    elif (year % 100) == 0:
        return False
    elif (year % 4) == 0:
        return True
    else:
        return False

year = 2012
leap_year = is_leap_year(year)
    
if leap_year:
    print year, "is a leap year"
else:
    print year, "is not a leap year"



2015年6月28日 星期日

iOS筆記:Block & Dynamic Behavior

Block


Block是iOS 4.0 以後才有的語法, 看起來就像一個function.可以傳送參數至block,也可以從block回傳值.跟一般的function的差別在於,block可以被定義在"函式"與"方法"中,並且存取任意定義在有效範圍block外的變數.

其語法如下:
螢幕快照 2015-06-27 上午12.45.12.png

Example

void printMessage (void)
{
    NSLog (@"qwertyuio");
}

用block的作法如下:

^(void) /(void)可省略
{
    NSLog (@"qwertyuio");
}
void (^printFoo)(void) = ^(void)
{
    NSLog (@"qwertyuio");
};
printFoo();

UIView Animation

Animation class method in UIView

+ (void)animateWithDuration:(NSTimeInterval)duration #how long you want it to take for thing to appear on screen.(It does what's in block immediately)But the appearance of it is going to happen over time.

                      delay:(NSTimeInterval)delay #how long to wait to start doing it.
                    options:(UIViewAnimationOptions)options
                 animations:(void (^)(void))animations #in this block is where you change "frame, transform and alpha".
                 completion:(void (^)(BOOL finished))completion; #do another animation,when the animation completes.
[UIView animateWithDuration:3.0 #經過三秒才完成這個Animation.但是alpha值會在執行code時馬上改變
                      delay:0.0
                    options:UIViewAnimationOptionBeginFromCurrentState
                 animations:^{ myView.alpha = 0.0; }
                 completion:^(BOOL fin) { if (fin) [myView removeFromSuperview]; }];

UIViewAnimationOptions螢幕快照 2015-06-27 上午1.48.57.png

另外常用的還有(void)transitionWithView:和(void)transitionFromView: toView:.

Dynamic Animation

Set up physics relating animatable objects and let them run until they resolve to stasis.Easily possible to set it up so that stasis never occurs, but that could be performance problem.

只要物件繼承UIView類別,就自動擁有動態行為的能力.

STEPS

1. Create a UIDynamicAnimator
UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:aView];
#If animating views, all views must be in a view hierarchy with reference view at the top.
2. Add UIDynamicBehaviors to it (gravity, collisions, etc.)
#Create and add UIDynamicBehaviors.
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] init]; 
[animator addBehavior:gravity];
3. Add UIDynamicItems (usually UIViews) to the UIDynamicBehaviors.
id <UIDynamicItem> item2 = ...; 
[gravity addItem:item2];

#The items have to implement the UIDynamicItem protocol ... @protocol UIDynamicItem @property (readonly) CGRect bounds; #drawing area of the item. @property (readwrite) CGPoint center; #the position of the item. @property (readwrite) CGAffineTransform transform; @end
-(void)updateItemUsingCurrentState:(id <UIDynamicItem>)item; #If you change center or transform while animator is running, you must call UIDynamicAnimator’s

UIGravityBehavior

模擬物件受到引力後的等加速度運動.
@property CGFloat angle; #設定重力的方向
@property CGFloat magnitude;  1.0 is 1000 points/s/s

UICollisionBehavior

碰撞時的行為,相當於讓物件的移動有個邊界範圍.例如球掉到地上後會彈跳一下下再停止.

@property
UICollisionBehaviorMode collisionMode; # Items, Boundaries, Everything (default) #定義item之間是相互碰撞彈開或是只從邊界碰撞彈開. - (void)addBoundaryWithIdentifier:(NSString *)identifier forPath:(UIBezierPath *)path; @property BOOL translatesReferenceBoundsIntoBoundary; #設定邊界

UIAttachmentBehavior

讓兩個物件(其中一個可以是某個座標點),讓他們互相黏起來.只要有一個物件移動,另外一個就會跟著動.
- (instancetype)initWithItem:(id <UIDynamicItem>)item attachedToAnchor:(CGPoint)anchor; #不用alloc/init初始化而是搭配initwithItem.
- (instancetype)initWithItem:(id <UIDynamicItem>)i1 attachedToItem:(id <UIDynamicItem>)i2; 
- (instancetype)initWithItem:(id <UIDynamicItem>)item offsetFromCenter:(CGPoint)offset ... 
@property (readwrite) CGFloat length; // distance between attached things (settable!) Can also control damping and frequency of oscillations.
@property (readwrite) CGPoint anchorPoint; // can be reset at any time

UISnapBehavior 

設定一個座標點後,物件會自動“撲向”那個座標點.



- (instancetype)initWithItem:(id <UIDynamicItem>)item snapToPoint:(CGPoint)point;
Imagine four springs at four corners around the item in the new spot.
You can control the damping of these four springs with @property CGFloat damping;.

UIPushBehavior

將物件往某一個方向推動.有兩種施力方式,一種為推一下就停止,物件就會依照慣性原理等速度移動.另一種則是推力一直不斷的加在物件上,一直維持著等速度的移動.
@property UIPushBehaviorMode mode; # Continuous or Instantaneous
@property CGVector pushDirection;
@property CGFloat magnitude/angle; # magnitude 1.0 moves a 100x100 view at 100 pts/s/s
the behavior will be sent this message when its animator changes.
- (void)willMoveToAnimator:(UIDynamicAnimator *)animator;

範例:



- (UIDynamicAnimator *)animator
{
    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.gameView];
    }
    return _animator;
}
- (UIGravityBehavior *)gravity
{
    if (!_gravity) {
        _gravity = [[UIGravityBehavior alloc] init];
        [self.animator addBehavior:_gravity];
    }
    return _gravity;
}
- (void)drop
{
    CGRect frame;
    frame.origin = CGPointZero;
    frame.size = DROP_SIZE;
    int x = (arc4random()%(int)self.gameView.bounds.size.width) / DROP_SIZE.width;
    frame.origin.x = x * DROP_SIZE.width;
    UIView *dropView = [[UIView alloc] initWithFrame:frame];
    [self.gameView addSubview:dropView];
    
    [self.gravity addItem:dropView];
}
參考網址:
Standford CS193P
http://adoptioncurve.net/archives/2013/02/blocks-in-objective-c-without-tears/