25 พฤศจิกายน 2558

Lab Raspberry Pi

class Student:
    def __init__(self,name,id,score):
        self.st_name=name
        self.st_id=id
        self.st_score=score

    def display(self):
        print("Name :",self.st_name)
        print("ID :",self.st_id)
        print("Score :",self.st_score)
        print("-----------------------")

    def getScore(self):
        return self.st_score

    def setScore(self,sc):
        self.st_score = sc

def findGrade(std):
    score = std.getScore()
    if (score >= 80) :
        return "A"
    elif (score >= 70) :
        return "B"
    elif (score >= 60) :
        return "C"
    elif (score >= 50) :
        return "D"
    else : return "F"

def countGrade(std,grade):
    i = 0
    count = 0
    while(i<len(std)):
        if(findGrade(std[i])==grade):
            count+=1
        i+=1
    return count

def showAllGrade(std):
    i = 0
    while(i<len(std)):
        print("Grade :",findGrade(std[i]))
        std[i].display()
        i+=1

def setup():
    std_data = [Student("bas",10075,65),
           Student("nop",20046,85),
           Student("toffi",30092,78),
           Student("Aun",20143,59)]

    print("Grade :",findGrade(std_data[1]))
    print(countGrade(std_data,"C"))
    showAllGrade(std_data)

setup()









2 พฤศจิกายน 2558

Lab8 JAVA

public class Student {
  private String st_name;
  private int st_id;
  private int st_age;
  private float st_weight;
  private float st_height;
  public Student(String name ,int id ,int age ,int weight ,int height){
    this.st_name = name;
    this.st_id = id;
    this.st_age = age ;
    this.st_weight = weight;
    this.st_height = height;
  }
  public void display(){
    System.out.println("Name : "+this.st_name);
    System.out.println("ID : "+this.st_id);
    System.out.println("Age : "+this.st_age);
    System.out.println("Weight : "+this.st_weight);
    System.out.println("Height : "+this.st_height);
  }
  public float getWeight(){
    return this.st_weight;
  }
  public float getHeight(){
    return this.st_height;
  }
  public int getAge(){
    return this.st_age;
  }
  public int getID(){
    return this.st_id;
  }
  public static void main (String[] agrs) {
    Student[] st_record  = {new Student("Tar",10016,21,69,179),
                            new Student("Tape",10032,21,90,174),
                            new Student("Bas",10032,19,69,175),
                            new Student("Top",10091,21,92,178),
                            new Student("Karn",10130,18,65,184)};
    displayStData(st_record);
    showBmi(st_record);
    showAvgAge(st_record);
    sortRecordByAge(st_record);
    findMinWeight(st_record);
   
  }
  public static void displayStData(Student[] std){
    int i = 0;
    while (i<std.length) {
      std[i].display();
      System.out.println("----------------------------------");
      i+=1;
    }
  }
  public static void showBmi(Student[] std){
    int i = 0;
    int count = 1;
    while (i<std.length) {
      float bmi = std[i].getWeight() / ((std[i].getHeight()/100)*(std[i].getHeight()/100));
      String bmi_f = String.format("%.2f",bmi);
        if (bmi > 25){
          System.out.println("No : "+count);
          std[i].display();
          System.out.printf("BMI : "+bmi_f);
          System.out.println();
          System.out.println("----------------------------------");
          count+=1;
      }
      i+=1;
    }
  }
  public static void showAvgAge(Student[] std){
    int i = 0;
    int count = 0;
    int sum_age = 0;
    while (i < std.length) {
      sum_age += std[i].getAge();
      if (std[i].getAge() < 30){
        count+=1;
      }
      i+=1;
    }
    float avg_age = sum_age/std.length;
    System.out.println("Average age of students : "+avg_age);
    System.out.println("----------------------------------");
  }
  public static void sortRecordByAge(Student[] std){
    int i = 0;
    while (i < std.length) {
      if (i!=std.length-1 && std[i].getAge() > std[i+1].getAge()) {
        int j  = i;
        while (j >= 0) {
          if (std[j].getAge() > std[j+1].getAge()) {
            Student data_copy = std[j];
            std[j] = std[j+1];
            std[j+1] = data_copy;
            j-=1;
          }
          else {
            break;
          }
        }
      }
      i+=1;
    }
    System.out.println("Sort record by age");
    System.out.println("////////////////////////////////");
    displayStData(std);
  }
  public static void findMinWeight(Student[] std){
    int i = 0;
    int count = 1;
    float min_w = std[0].getWeight();
    System.out.println("Student weight < 70");
    System.out.println("////////////////////////////////");
    while (i<std.length){
      if (std[i].getWeight() < min_w){
        min_w = std[i].getWeight();
      }
      if (std[i].getWeight() < 70){
        System.out.println("No : "+count);
        std[i].display();
        System.out.println("----------------------------------");
        count+=1;
      }
      i+=1;
    }
    System.out.println("Minimum weight of students : "+min_w);
    System.out.println("----------------------------------");
  }
}

Lab7 Class and method

class student:
    def __init__(self, st_name, st_id, st_age, st_weight, st_height):
        self.name = st_name
        self.id = st_id
        self.age = st_age
        self.weight = st_weight
        self.height = st_height
    def stData(self):
        print("Name :",self.name)
        print("ID :",self.id)
        print("Age :",self.age)
        print("Weight :",self.weight)
        print("Height :",self.height)
       
    def getWeight(self):
        return self.weight
    def getHeight(self):
        return self.height
    def getAge(self):
        return self.age
    def getID(self):
        return self.id
       
 

def setup():
   
    tar = student("tar",10012,21,69,179)
    tape = student("tape",10032,21,90,174)
    bas = student("bas",10075,19,69,175)
    top = student("top",10091,21,92,178)
    karn = student("karn",10130,18,60,184)
    st_record = [top,tape,tar,karn,bas]
 
    displayStData(st_record)
    showBmi(st_record)
    showAge(st_record)
    sortRecord(st_record)
    stWeight(st_record)
             
def displayStData(student):
    i = 0
    while i < len(student):
        student[i].stData()
        print("------------------------")
        i+=1

def showBmi(student):
    i = 0
    count = 1
    while i < len(student):
        #bmi=float("{0:.2f}".format(student[i].getWeight()/((student[i].getHeight()/100)**2)))
        bmi=float(format(student[i].getHeight()/((student[i].getHeight()/100)**2),'.2f'))
        #bmi = student[i].getWeight()/(student[i].getHeight()/100)**2
        if bmi > 25:
            print("No :",count)
            student[i].stData()
            print("Bmi :",bmi)
            print("------------------------")
            count+=1
        i+=1

def showAge(student):
    i = 0
    count = 0
    sum_age = 0
    while i < len(student):
        sum_age += student[i].getAge()
        if student[i].getAge() < 30:
            count+=1
        i+=1
    avg_age = sum_age/len(student)
    print("Average age of students :",avg_age)
    print("------------------------")

def sortRecord(student):  
    i = 0
    while i < len(student) :
        if i!=len(student)-1 and student[i].getAge() > student[i+1].getAge():
            j = i
            while j >= 0:
                if student[j].getAge() > student[j+1].getAge():
                    dataCopy = student[j]
                    student[j] = student[j+1]
                    student[j+1] = dataCopy
                    j-=1
                else :
                    break
        i+=1
    print("Sort record by age")
    print("------------------------")
    displayStData(student)

def stWeight(student):
    i = 0
    count = 1
    min_weight = student[0].getWeight()
    while i < len(student):
        if student[i].getWeight() < min_weight:
            min_weight = student[i].getWeight()
        if student[i].getWeight() < 70:
            print("No :",count)
            student[i].stData()
            print("------------------------")
            count+=1
        i+=1
    print("Minimum weight of students :",min_weight)
    print("------------------------")
       
setup()

26 ตุลาคม 2558

Lab6 Matrix

def setup():
   matrix = [[1,2,3], [6,5,4], [7,8,9]]
   matrix2  =[[7,3,3], [6,1,2], [5,6,1]]
   print("matrix 1 :")
   displayMatrix(matrix)
   print()
   print("matrix 2 :")
   displayMatrix(matrix2)
   print()
   addMatrix(matrix,matrix2)
   print()
   subtractMatrix(matrix , matrix2)
   print()
   multiplyMatrix(matrix, matrix2)
   print()
   transposeMatrix(matrix)


def displayMatrix(matrix):
   row = 0
   while(row<len(matrix)):
      column = 0
      while(column<len(matrix[row])):
         print(matrix[row][column]," ",end="")
         column+=1
      print()
      row+=1
   
def addMatrix(matrix, matrix2):
   row = 0
   print("Add matrix :")
   while(row<len(matrix)):
      column = 0
      while(column<len(matrix[row])):
         print(matrix[row][column]+matrix2[row][column]," ",end="")
         column+=1
      print()
      row+=1
def subtractMatrix(matrix , matrix2):
   row = 0
   print("Subtract matrix :")
   while(row<len(matrix)):
      column = 0
      while(column<len(matrix[row])):
         print(matrix[row][column]-matrix2[row][column]," ",end="")
         column+=1
      print()
      row+=1

def multiplyMatrix(matrix1, matrix2):
   if(len(matrix1[0])==len(matrix2)):#if(column number of matrix1 == row number of matrix2)
      row = 0  
      print("Multiply matrix :")
      while(row<len(matrix1)):#loop for shift row of multiplicand matrix
         column = 0
         while(column<len(matrix2[row])):#loop for shift column of multiplier matrix
            k = 0
            val = 0
            while(k<len(matrix1[row])):#loop for shift column of multiplicand matrix and shift row of multiplier matrix
               val += matrix1[row][k]*matrix2[k][column]#matrix_row[i]_column[k]*matrix2_row[k]_column[j]
               k+=1
            print(val," ",end="")
            column+=1
         print()
         row+=100
   else:
      print("Can't multiply matrix")
      print("Column number of multiplicand matrix not equal row number of multiplier matrix")
   
   
def transpose(matrix):
    i = 0
    j = 0
    while i < len(matrix):
         j += i
         while (j < len(matrix[i])):
            dataCopy = matrix[i][j]
            matrix[i][j] = matrix[j][i]
            matrix[j][i] = dataCopy
            j+=1
         print(matrix[i])
         j = 0
         i+=1
    displayMatrix(matrix)
   


setup()

Lab6 Write letter

def setup():
   A = ["     #     ",
        "    # #    ",
        "   #   #   ",
        "  #######  ",
        " #       # ",
        "#         #"]
   B = ["#########",
        "#       #",
        "#######  ",
        "#      # ",
        "#       #",
        "######## ",]
   C = [" ########",
        "#        ",
        "#        ",
        "#        ",
        "#        ",
        " ########"]
   D = ["#######  ",
        "#      # ",
        "#       #",
        "#       #",
        "#      # ",
        "#######  ",]
   E = ["#########",
        "#        ",
        "#######  ",
        "#        ",
        "#        ",
        "#########"]
   i = 0
 
   while(i<len(A)):
      print(A[i]," ",B[i]," ",C[i]," ",D[i]," ",E[i])
      i+=1
     
setup()

Lab6 Chairs in the building

def setup():
   floor1 = [20,43,32,43]
   floor2 = [39,33,24,43]
   floor3 = [25,22,30,43]
   building = [floor1,floor2,floor3]
   totalChairs(building)
   maxFloor(building)
   maxRoom(building)

def totalChairs(building):
   total_chairs = 0
   i = 0
   while(i<len(building)):
      j = 0
      while(j<len(building[i])):
            total_chairs += building[i][j]
            j+=1
      i+=1
   print("Total chairs in the building :",total_chairs)
   print("-----------------------------------------------------------------")

def maxFloor(building):
   i = 0
   max_chair = 0;
   i_max = 0;
   print("Index of the floor with maximum number of chairs")
   while(i<len(building)):
      j = 0
      total_chairs = 0
      while(j<len(building[i])):
            total_chairs += building[i][j]
            j+=1
      if(total_chairs>max_chair):
         max_chair = total_chairs
         i_max = i
      i+=1
   print("Index of floor : ",i_max,"(",max_chair,")",sep="")
   print("-----------------------------------------------------------------")

def maxRoom(building):
   i = 0
   max_chair_room = 0
   while(i<len(building)):
      j = 0
      while(j<len(building[i])):
         if(building[i][j]>max_chair_room):
            max_chair_room=building[i][j]
         j+=1
      i+=1

   count_room = 0
   i = 0
   print("Indices the rooms with maximum number of chairs ")
   while(i<len(building)):
      j = 0
      while(j<len(building[i])):
         if(building[i][j]==max_chair_room):
            print("Index of room :",j," | ","Index of floor :",i)
         j+=1
      i+=1
   print("-----------------------------------------------------------------")
 
setup()

Lab6 Parallel array

def setup():
   st_name = ["Tar","Tape","Bas","Top","Karn"]
   st_id = [10012,10032,10075,10091,10130]
   st_age = [21,21,19,21,18]
   st_weight = [72,93,69,91,68]
   st_height = [179,178,174,172,184]
 
   stData(st_name, st_id, st_age, st_weight, st_height)
   stBmi(st_name, st_id, st_age, st_weight, st_height)
   stAge(st_name, st_id, st_age, st_weight, st_height)
   stWeight(st_name, st_id, st_age, st_weight, st_height)
 
def stData(name,id,age,w,h):
   i = 0
   while(i<len(name)):
      print("Name :",name[i])
      print("ID :",id[i])
      print("Age :",age[i])
      print("Weight :",w[i])
      print("Height :",h[i])
      print("------------------------")
      i+=1

def stBmi(name,id,age,w,h):
   i = 0
   count = 1
   bmi = [0]*5
   while(i<len(w)):
      #bmi[i]=float("{0:.2f}".format(w[i]/((h[i]/100)*(h[i]/100))))
      bmi[i]=float(format((w[i]/((h[i]/100)*(h[i]/100))),'.2f'))
      if(bmi[i]>25):
         print("No.",count,sep="")
         print("Name :",name[i])
         print("ID :",id[i])
         print("Age :",age[i])
         print("Weight :",w[i])
         print("Height :",h[i])
         print("Bmi :",bmi[i])
         print("------------------------")
         count+=1
      i+=1
   print ("BMI :",bmi)
   print("------------------------")

def stAge(name,id,age,w,h):
   i = 0
   sum_age = 0
   while(i<len(age)):
      sum_age += age[i]
      i+=1
   
   avg_age = sum_age/len(name)
   print("Average age :",avg_age)
   print("------------------------")

def sortRecord(name,id,age,weight,height):
    i = 0
    while (i<len(age)):
        if(i!=len(age)-1 and age[i]>age[i+1]):
            j = i
            while (j >= 0):
                if(age[j]>age[j+1]):
                    copy_age = age[j]
                    copy_name = name[j]
                    copy_id = id[j]
                    copy_weight = weight[j]
                    copy_height = height[i]
                    age[j] = age[j+1]
                    age[j+1] = copy_age
                    name[j] = name[j+1]
                    name[j+1] = copy_name
                    id[j] = id[j+1]
                    id[j+1] = copy_id
                    weight[j] = weight[j+1]
                    weight[j+1] = copy_weight
                    height[j] = height[j+1]
                    height[j+1] = copy_height
                    j-=1
                else :
                    break
        i+=1
    print("Sort record by age")
    print("------------------------")
    stData(name,id,age,weight,height)

def stWeight(name,id,age,w,h):
   i = 0
   min_weight = w[0]
   count = 1
   while(i<len(w)):
      if(w[i]<min_weight):
         min_weight = w[i]
      if(w[i]<70):
         print("No.",count,sep="")
         print("Name :",name[i])
         print("ID :",id[i])
         print("Age :",age[i])
         print("Weight :",w[i])
         print("Height :",h[i])
         print("------------------------")
         count+=1
      i+=1
   print("Minimum weight of students :",min_weight)
   print("------------------------")

setup()

5 ตุลาคม 2558

Lab5 Final

def setup():
   text1 = "Thailand  "
   print(text1)
   assert my_count(text1) ==2
   print("my_count",my_count(text1))
   assert my_find(text1) ==3
   print("my_find",my_find(text1))
   assert my_replace(text1) == "Thaithai"
   print("my_replace",my_replace2(text1))
   print("my_strip",my_strip(text1))
   print("my_startswith",my_startswith(text1))
   print("my_endswith",my_endswith(text1))

def my_count(text):
   find = "a"
   countFind = 0
   i = 0
   while(i<len(text)):
      if(find == text[i]):
         countFind +=1
      i+=1
   return countFind

def my_find(text):
   find = "i"
   indexFind = 0
   i = 0
   while(i<len(text)):
      if(find == text[i]):
         indexFind = i
      i+=1
   return indexFind

def my_replace(text):
   find = "land"
   replace = "thai"
   newText = ""
   i = 0
   i_find = 0
   while(i<len(text)):
      if(text[i]==find[i_find]):
         checkAll = 0
         while (checkAll < len(find)):
            if(find[i_find]==text[i+i_find]):
               i_find+=1
               checkAll+=1
            else:
               newText = newText+text[i]
               i_find = 0
               checkAll = len(find)
            if(i_find==len(find)):
               n = 0
               m = len(replace)
               i_replace = 0
               while(n < m):
                  newText = newText+replace[i_replace]
                  i_replace +=1
                  n+=1
               i +=len(find)-1
               i_find = 0
      else :
         if(text[i] != " "):
             newText = newText+ text[i]
      i+=1
   return newText

def my_strip(text):
   newText = ""
   i=0
   while(i < len(text)):
      if(text[i] != " "):
            newText = newText+ text[i]
      i+=1
   return newText

def my_startswith(text):
   find = "Sun"
   i = 0
   while(i < len(text)):
      if(find[i] == text[i]):
         j =0
         while(j < len(find)):
            if(text[i+j] == find[j]):
               j +=1
               if (j == len(find)):
                  return True
            else :
               return False
      else :
          return False

def my_endswith(text):
   find = "and"
   i = len(text)-1
   i_find = len(find)-1
   while(i > 0):
      if(find[i_find] == text[i]):
         checkAll = 0
         while(checkAll < len(find)):
            if(text[i-checkAll] == find[i_find-checkAll]):
               checkAll +=1
               if (checkAll == len(find)):
                  return True
            else :
               return False
      else :
          return False

setup()
       

Lab5 Draft

def setup():
   val_array = [8,-2,20,-12,-9,20,2,-6,20,4]
   display_value_array_and_index(val_array)
   print("")
   find_max_val_array(val_array)
   print("")
   find_first_last_index_max_val(val_array)
   print("")
   find_sum_array(val_array)
   print("")
   find_sum_of_positive_val_in_array(val_array)
   print("")
   find_count_num_of_positive_val_in_array(val_array)
   print("")
   find_avg_values_array(val_array)
   print("")
   inc_dec_val_array(val_array)

def display_value_array_and_index(a):
   i = 0
   while(i < len(a)):
      val = a[i]
      print ("index",i," ",end="")
      print ("value =",val)
      i+=1
############################################################################
def find_max_val_array(a):
   i = 0
   max_val = 0
   index_max = 0
   while(i < len(a)):
      value_in_array = a[i]
      if (max_val < value_in_array):
         max_val = value_in_array
         index_max = i
      i+=1
   print ("Maximum value in array =",max_val)
############################################################################
def find_first_last_index_max_val(a):
#Find index of (the first) maximum value in array
   max_val = 0
   first_max_i = 0
   i = 0
   while(i < len(a)):
      if(max_val<a[i]):
         max_val = a[i]
         first_max_i = i
      i+=1
#Find index of (the last) maximum value in array
   max_val = 0
   last_max_i = 0
   i  = (len(a)-1)
   while(i > (-1)):
      if(max_val<a[i]):
         max_val = a[i]
         last_max_i = i
      i-=1
   
   print("The First maximum value","Index :","%2.0d"%first_max_i," Value :",max_val)
   #i=0
   #while(i < len(a)):
      #if(i >first_max_i and i < last_max_i and a[i]==max_val):
         #print("Index :","%2.0d"%i,"   ","Value :",a[i])
      #i+=1
   print("The Last maximum value"," Index :","%2.0d"%last_max_i," Value :",max_val)
############################################################################
def find_sum_array(a):
   i = 0
   sum_array = 0
   print ("Sum of values in array = ",end="")
   while(i < len(a)):
      sum_array += a[i]
      if(a[i]>0):
         print(a[i],end="")
      else :
         print("(",a[i],")",end="",sep="")
      if(i==(len(a)-1)):
         print(" = ",end="")
      else:
         print("+",end="")
      i+=1
   print (sum_array)
############################################################################
def find_sum_of_positive_val_in_array(a):
   i = 0
   sum_array = 0
   print ("Sum of positive values in array = ",end="")
   while(i < len(a)):
      if(a[i]>=0):
         sum_array += a[i]
         print(a[i],end="")
         if(i==(len(a)-1)):
            print(" = ",end="")
         else:
            print("+",end="")
      i+=1
   print (sum_array)
############################################################################
def find_count_num_of_positive_val_in_array(a):
   i = 0
   sum_array = 0
   num_positive_array = 0
   print ("Count number of positive values in array = ",end="")
   while(i < len(a)):
      if(a[i]>=0):
         num_positive_array+=1
      i+=1
   print (num_positive_array,"number (",end="")
   i=0
   while(i < len(a)):
      if(a[i]>=0):
         print(a[i],end="")
         if(i==(len(a)-1)):
            print(")")
         else:
            print(",",end="")
      i+=1
############################################################################
def find_avg_values_array(a):
   i = 0
   sum_array = 0
   print ("Average of values in array = (",end="")
   while(i < len(a)):
      sum_array += a[i]
      if(a[i]>0):
         print(a[i],end="")
      else :
         print("(",a[i],")",end="",sep="")
      if(i==(len(a)-1)):
         print(")/",len(a)," = ",end="",sep="")
      else:
         print("+",end="")
      i+=1
   avg_array = sum_array/len(a)
   print (avg_array)
############################################################################
def inc_dec_val_array(a):
   print("Increase/decrease values in array")
   mode_inc_dec = input("Increase Press 'i'     Decrease Press 'd'")
   print()
   mode_fixed_percent = input("by Fixed value Press 'f'    by Percentage Press 'p'")
   print()
   val = int(input("Please type value"))
   print()
   i = 0
   if (mode_inc_dec == 'i' or mode_inc_dec == 'I'):
      if(mode_fixed_percent == 'f' or mode_fixed_percent == 'F'):
         while(i < len(a)):
            a[i]+=val
            i+=1
      elif(mode_fixed_percent == 'p' or mode_fixed_percent == 'P'):
         while(i < len(a)):
            if(a[i]<0):
               a[i]-=((val/100)*a[i])
            else : a[i]+=((val/100)*a[i])
            i+=1
   if (mode_inc_dec == 'd' or mode_inc_dec == 'D'):
      if(mode_fixed_percent == 'f' or mode_fixed_percent == 'F'):
         while(i < len(a)):
            a[i]+=-val
            i+=1
      elif(mode_fixed_percent == 'p' or mode_fixed_percent == 'P'):
         while(i < len(a)):
            if(a[i]<0):
               a[i]+=((val/100)*a[i])
            else : a[i]-=((val/100)*a[i])
            i+=1
   print("Value in array =",a)
 
setup()

28 กันยายน 2558

Lab5 - convert a number from base 10 to base 2

def setup():
   base10 = 19
   base2 = ""
   while (base10 > 0 ):
      base2 = str(base10%2)+base2
      base10 = base10//2
      print(base2)
   print(base2)
setup()

21 กันยายน 2558

Lab4x Loan payment

def setup():
  monthly_loan_payment(5000, 12, 1);

def monthly_loan_payment(loan_amount, interest_rate, loan_term):
   ratepermonth = (interest_rate/100)/12
   paypermonth = loan_amount*(ratepermonth/(1-pow(1+ratepermonth, -(loan_term*12))))#M=P*(J/(1-(1+J)^-n)
   unpaid = loan_amount
   total_interest = 0
   month = 1
   print("Monthly Loan Payment");
   print("Payment No.  Interest   Principal   Unpaid Balance   Total Interest")
   while (month <= (loan_term*12)):
      interest = ratepermonth*unpaid
      total_interest+=interest
      principal = paypermonth-interest
      unpaid = abs(unpaid-principal)
      print("   ","%0.2d"%month,end="")
      print("        ","$","%5.2f"% interest,end="",sep="")
      print("     ","$","%6.2f"% principal,end="",sep="")
      print("       ","$","%7.2f"% unpaid,end="",sep="")
      print("         ","$","%6.2f"% total_interest,sep="")
      month+=1

setup()

Lab4x Multiplication table

def setup():
   multi_table = 25
   max_multiplier = 12
   multiplier=1
   print("Multiplication Table","'",multi_table,"'");
   while (multiplier <= max_multiplier):
      result = multi_table*multiplier
      print(multi_table,"x",multiplier,"=",result)
      multiplier+=1
 
setup()

Lab4x Sum of Prime Number

def setup():
   max_val = 20
   prime_num = 2
   sum_prime = 0
   print("Sum of Prime number from 1 to",max_val,"(",end="")
   while (prime_num <= max_val):
      if (check_prime_num(prime_num)):
         print(prime_num,",",sep="",end="")
         sum_prime += prime_num
      prime_num+=1
   print(")")
   print("'",sum_prime,"'",sep="")
 

def check_prime_num(p_num):
   divisor = 2
   while (divisor<p_num):
      if (p_num%divisor==0):
         return False
      divisor+=1
   return True

setup()

20 กันยายน 2558

Lab4x Sum of Integers

def setup():
   max_val = 10
   count=0
   result=0
   while (count <= max_val):
      result += count
      count+=1
   print("Sum of Integers from 1 to",max_val,"=",end="")
   print(" '",result,"'",sep="")
setup()

Lab4x Leap year

def setup():
  year = 2015
  if (year%400==0):
    print(year," is leap year")
  elif (year%100==0):
    print(year," isn't leap year")
  elif (year%4==0):
    print(year," is leap year")
  else:
    print(year," isn't "+"leap year")
             
setup()

Lab4x Grade

def setup():
   score = 49
   print("Your score =",score)
   if (score>=80):
      print("Grade A ")
   elif (score>=70):
      print("Grade B ")
   elif (score>=60):
      print("Grade C ")
   elif (score>=50):
      print("Grade D ")
   else:
      print("Grade F ")

setup()

14 กันยายน 2558

Lab4x BMI

def setup():
#//----- Define value -----//
   weight_ = 68
   height_ = 174

#//----- Calculate -----//
   bmi = format(cal_bmi(weight_,height_),'.2f')

#//----- Show Value ----//
   print('weight_ = ',weight_,'kg')
   print('height_ = ',height_,'cm')
   print('Body mass index(BMI) = ', bmi)

def cal_bmi(w,h):#//Create function BMI calculation
   val_bmi = w/((h/100)*(h/100))#//Formula of BMI
   return val_bmi

setup()

Lab4x Circumference

def setup():
   radius = 10
   circumference = format(cal_cir(radius),'.2f')
   area = format(cal_area(radius),'.2f')
   print ("Circumference = ",circumference,"cm")
   print ("Area =",area, "cm2")

#Create function circumference calculation  
def cal_cir(r):
   val_cir = (22/7)*2*r
   return val_cir

#Create function area calculation
def cal_area(r):
   val_area = (22/7)*r*r
   return val_area

setup()

Lab4 Doraemon book

void setup() {
  size(800, 800);
  background(#F6B0D8);
}

int move_X = 0;
int move_Y = 0;
void draw() {
  int X = 0;
  int Y = 0;
  int max_book = 4;
  int pre_book = 1;
  background(#F6B0D8);
  while (pre_book<=max_book) {
    draw_book(move_X+X, move_Y+Y);
    Y+= 364;
    if (pre_book%2==0) {
      X=304;
      Y=0;
    }
    pre_book++;
  }
  if (key=='w'||key=='W') {
    move_Y-=2;
    if (move_Y<=-442) {
      move_Y=-442;
    }
  }
  if (key=='s'||key=='S') {
    move_Y+=2;
    if (move_Y>=358) {
      move_Y=358;
    }
  }
  if (key=='a'||key=='A') {
    move_X-=2;
    if (move_X<=-402) {
      move_X=-402;
    }
  }
  if (key=='d'||key=='D') {
    move_X+=2;
    if (move_X>=397) {
      move_X=397;
    }
  }
}

void draw_book(int pos_x, int pos_y) {

  strokeJoin(ROUND);
  //----- front page -----//
  strokeWeight(2);
  fill(#323C5D);
  rect(pos_x+100, pos_y+100, 270, 340);

  //----- behind doraemon background -----//
  noStroke();
  fill(#FCE314);
  rect(pos_x+125, pos_y+220, 220, 205);

  //----- name book background -----//
  fill(255);
  rect(pos_x+125, pos_y+130, 220, 50);
  //----- name book -----//
  fill(0);
  textSize(35);
  text("DORAEMON", pos_x+133, pos_y+167);

  //----- book page -----//
  strokeWeight(2);
  stroke(0);
  fill(255);
  quad(pos_x+100, pos_y+100, pos_x+130, pos_y+80, pos_x+400, pos_y+80, pos_x+370, pos_y+100);
  quad(pos_x+370, pos_y+100, pos_x+400, pos_y+80, pos_x+400, pos_y+420, pos_x+370, pos_y+440);
  strokeWeight(1);
  line(pos_x+106, pos_y+96, pos_x+376, pos_y+96);
  line(pos_x+112, pos_y+92, pos_x+382, pos_y+92);
  line(pos_x+118, pos_y+88, pos_x+388, pos_y+88);
  line(pos_x+124, pos_y+84, pos_x+394, pos_y+84);
  line(pos_x+376, pos_y+96, pos_x+376, pos_y+436);
  line(pos_x+382, pos_y+92, pos_x+382, pos_y+432);
  line(pos_x+388, pos_y+88, pos_x+388, pos_y+428);
  line(pos_x+394, pos_y+84, pos_x+394, pos_y+424);

  //----- Doraemon -----//
  strokeWeight(3);
  stroke(#325D87);
  //----- face -----//
  fill(#4F81BC);
  ellipse(pos_x+235, pos_y+320, 200, 175);
  fill(255);
  ellipse(pos_x+235, pos_y+334, 140, 125);

  //----- eyes -----//
  fill(255);
  ellipse(pos_x+215, pos_y+274, 37, 50);
  ellipse(pos_x+255, pos_y+274, 37, 50);
  fill(#325D87);
  ellipse(pos_x+220, pos_y+279, 8, 8);
  strokeWeight(4);
  arc(pos_x+248, pos_y+281, 6, 6, PI, TWO_PI);
  strokeWeight(3);

  //----- nose -----//
  fill(#FE0000);
  ellipse(pos_x+235, pos_y+301, 20, 20);

  //----- mounth -----//
  noFill();
  arc(pos_x+235, pos_y+350, 100, 50, 0, PI);
  line(pos_x+235, pos_y+312, pos_x+235, pos_y+375);

  //----- Whiskers -----//
  line(pos_x+220, pos_y+320, pos_x+177, pos_y+315);
  line(pos_x+220, pos_y+325, pos_x+175, pos_y+325);
  line(pos_x+220, pos_y+330, pos_x+177, pos_y+335);

  line(pos_x+250, pos_y+320, pos_x+293, pos_y+315);
  line(pos_x+250, pos_y+325, pos_x+295, pos_y+325);
  line(pos_x+250, pos_y+330, pos_x+293, pos_y+335);

  //----- collar -----//
  fill(#FD0000);
  rect(pos_x+185, pos_y+395, 100, 13);

  //----- bell -----//
  fill(#FCBE0C);
  ellipse(pos_x+235, pos_y+394, 20, 20);

  //----- hands -----//
  fill(255);
  ellipse(pos_x+180, pos_y+395, 30, 28);
  ellipse(pos_x+290, pos_y+395, 30, 28);
}

Lab4 Capt

float move = 0;
float pos_x_shield = 370;
float speed = 2;
int max_shield = 4;
boolean start_fw = true;
boolean start_bw;

void setup() {
  size(600, 600);
  background(#0D0D0D);
}

void draw() {
  background(#0D0D0D);
  int Y = 0;
  int X = 0;
  int pre_shield =1;
  textSize(550);
  text("A", 100, 500);// A font
 
  while (pre_shield<=max_shield) {
    draw_capt(move, Y, X);
    X+=250;
    if (pre_shield%2==0) {
      Y=-200;
      X=0;
    }
    if (pre_shield%4==0) {
      Y=200;
      X=0;
    }
    pre_shield++;
  }
 
  if (start_fw == true) {
    move +=speed;
    pos_x_shield +=speed;
    if (pos_x_shield >= 485) {
      start_fw = false;
      start_bw = true;
    }
  }

  if (start_bw == true) {
    move -=speed;
    pos_x_shield -=speed;
    if (pos_x_shield <= -140) {
      start_fw = true;
      start_bw = false;
    }
  }
 
  fill(255);
  textSize(15);
  text("speed "+speed, 20, 20);

  //----- title -----//
  textSize(30);
  text("CAPTAIN AMERICA", 162, 570);
}

void draw_capt(float pos_x, float pos_y, float x) {
  noStroke();
  fill(255);

  //----- Shield -----//
  fill(#EE0000);
  ellipse(pos_x_shield+x, pos_y+300, 250, 250);
  fill(255);
  ellipse(pos_x+370+x, pos_y+300, 210, 210);
  fill(#EE0000);
  ellipse(pos_x+370+x, pos_y+300, 170, 170);
  fill(#000080);
  ellipse(pos_x+370+x, pos_y+300, 130, 130);

  //----- Star -----//
  beginShape();
  fill(255);
  //fill((random(0, 255)), (random(0, 255)), (random(0, 255)));
  vertex(pos_x+370+x, pos_y+243);
  vertex(pos_x+382.5+x, pos_y+280.5);
  vertex(pos_x+420+x, pos_y+280.5);
  vertex(pos_x+395+x, pos_y+305.5);
  vertex(pos_x+407.5+x, pos_y+343);
  vertex(pos_x+370+x, pos_y+318);
  vertex(pos_x+332.5+x, pos_y+343);
  vertex(pos_x+345+x, pos_y+305.5);
  vertex(pos_x+320+x, pos_y+280.5);
  vertex(pos_x+357.5+x, pos_y+280.5);
  endShape(CLOSE);
}
void keyPressed() {
  if (keyCode==UP)speed+=0.5;
  if (keyCode==DOWN)speed-=0.5;
  if (speed<=2)speed=2;
  if (speed>=30)speed=30;
}
void mousePressed() {
  if (mouseButton == LEFT) {
    max_shield++;
    {
      if (max_shield>=6)max_shield=6;
    }
  } else if (mouseButton == RIGHT) {
    max_shield--;
    {
      if (max_shield<=1)max_shield=1;
    }
  }
}

Lab4 Flock birds

float wing_y;
float bird_y;
int size_draw = 40;
boolean wing_up;
boolean wing_down;
int max_bird = 3;

void setup() {
  size(600, 600);
  background(255);
  mouseX=width/2;
  mouseY=height/2;
  wing_up = true;
}

void draw() {
  int present_bird = 1;
  int X = 0;
  int Y = 0;
  background(255);

  if (mouseY<size_draw*2) {
    mouseY=size_draw*2;
  }
  if (mouseX<size_draw) {
    mouseX = size_draw;
  }

  while (present_bird <= max_bird) {
    draw_bird(mouseX+X, mouseY+Y, size_draw, bird_y);
    X += size_draw*3;
    if (present_bird%4==0) {
      X=0;
      Y-=size_draw*1.1;
    }
    present_bird++;
  }

  if (wing_up == true) {
    wing_y-= size_draw*0.15;
    bird_y-= size_draw*0.01;
    if (wing_y <= -(size_draw*0.7)) {
      wing_up = false;
      wing_down = true;
    }
  }

  if (wing_down == true) {
    wing_y+= size_draw*0.15;
    bird_y+= size_draw*0.01;
    if (wing_y >= (size_draw*0.7)) {
      wing_up = true;
      wing_down = false;
    }
  }
}

void draw_bird(float mouse_x, float mouse_y, float s_draw, float bird_y) {
  fill(#D30327);
  strokeWeight(s_draw*0.2);
  line(mouse_x, mouse_y-(s_draw*0.5), mouse_x-(s_draw*1.3), mouse_y+wing_y-(s_draw*0.5));//left wing
  line(mouse_x, mouse_y-(s_draw*0.5), mouse_x+(s_draw*1.3), mouse_y+wing_y-(s_draw*0.5));//right wing
  strokeWeight(s_draw*0.05);
  ellipse(mouse_x, mouse_y-(s_draw*0.5)+bird_y, s_draw, s_draw);//body
  strokeWeight(1);
  fill(255);
  ellipse(mouse_x-(s_draw*0.22), mouse_y-(s_draw*0.6)+bird_y, s_draw*0.3, s_draw*0.35);//left white eye
  ellipse(mouse_x+(s_draw*0.22), mouse_y-(s_draw*0.6)+bird_y, s_draw*0.3, s_draw*0.35);//right white eye
  fill(0);
  ellipse(mouse_x-(s_draw*0.22), mouse_y-(s_draw*0.6)+bird_y, s_draw*0.1, s_draw*0.1);//left black eye
  ellipse(mouse_x+(s_draw*0.22), mouse_y-(s_draw*0.6)+bird_y, s_draw*0.1, s_draw*0.1);//right black eye
  fill(#F9BC09);
  triangle(mouse_x-(s_draw*0.17), mouse_y-(s_draw*0.35)+bird_y, mouse_x+(s_draw*0.17), mouse_y-(s_draw*0.35)+bird_y, mouse_x, mouse_y-(s_draw*0.05)+bird_y); //mounth
}

void keyPressed() {
  if (keyCode==UP) {
    size_draw++;
    if (size_draw>=90)size_draw=90;
  }
  if (keyCode==DOWN) {
    size_draw--;
    if (size_draw<=20)size_draw=20;
  }
}
void mousePressed() {
  if (mouseButton == LEFT) {
    max_bird++;
  } else if (mouseButton == RIGHT) {
    max_bird--;
    {
      if (max_bird<=1)max_bird=1;
    }
  }
}

Lab4 Balloon

int max_balloon = 4;
int size_draw = 50;
float Y = height;
void setup() {
  size(600, 600);
}


void draw() {
  int present_balloon = 1;
  float X = 0;
  background(0);
  if (Y < height*0.16) {
    fill(#00FD00);
  } else if (Y < height*0.33) {
    fill(#A0FA00);
  } else if (Y < height*0.5) {
    fill(#F2FB01);
  } else if (Y < height*0.66) {
    fill(#EFA200);
  } else if (Y < height*0.83) {
    fill(#EB6100);
  } else {
    fill(#D00022);
  }

  while (present_balloon <= max_balloon) {
    draw_balloon(X, Y);
    X += size_draw*1.2;
    present_balloon++;
  }

  Y-=2;
  if (Y<=(-size_draw*2))Y=height;
}

void draw_balloon(float pos_x, float pos_y) {
  stroke(#009CDA);
  strokeWeight(size_draw*0.05);
  float radius = size_draw;
  float string_length = size_draw*2;
  line(pos_x+(size_draw*0.6), pos_y, pos_x+(size_draw*0.6), pos_y+string_length);
  ellipse(pos_x+(size_draw*0.6), pos_y, radius, radius);
}

void keyPressed() {
  if (keyCode==UP) {
    size_draw++;
    if (size_draw>=90)size_draw=90;
  }
  if (keyCode==DOWN) {
    size_draw--;
    if (size_draw<=20)size_draw=20;
  }
}
void mousePressed() {
  if (mouseButton == LEFT) {
    max_balloon++;
  } else if (mouseButton == RIGHT) {
    max_balloon--;
    {
      if (max_balloon<=1)max_balloon=1;
    }
  }
}

Lab4 Loan Payment

void setup() {
  size(685, 500);
  background(0);
  fill(255);
  monthly_loan_payment(5000, 12, 1);
}
void monthly_loan_payment(float loan_amount, float interest_rate, int loan_term) {
  float ratepermonth = (interest_rate/100)/12;
  float paypermonth = loan_amount*(ratepermonth/(1-pow(1+ratepermonth, -(loan_term*12))));//M=P*(J/(1-(1+J)^-n))
  float unpaid = loan_amount;
  float total_interest = 0;
  int month = 1;
  textSize(25);
  text("Monthly Loan Payment", 205, 30);
  textSize(17);
  text("Payment No.        Interest        Principal        Unpaid Balance        Total Interest", 20, 70);
  int Y =110;
  while (month <= (loan_term*12)) {
    float interest = ratepermonth*unpaid;
    total_interest+=interest;
    float principal = paypermonth-interest;
    unpaid = abs(unpaid-principal);
    text(nf(month, 2), 60, Y);
    text("$"+nf(interest, 1, 2), 168, Y);
    text("$"+nf(principal, 1, 2), 272, Y);
    text("$"+nf(unpaid, 1, 2), 408, Y);
    text("$"+nf(total_interest, 3, 2), 576, Y);
    Y+=30;
    month++;
  }
}

Lab4 Sum of Prime number

void setup() {
  size(350, 100);
  background(0);
  int max_val = 10;
  int p_num =2;
  int sum=0;
  while (p_num <= max_val) {
    if (prime_number(p_num)) {
      sum += p_num;
      println(sum);
    }
    p_num++;
  }
  textSize(18);
  textAlign(CENTER);
  text("Sum of Prime number from 1 to "+max_val, width/2, height/2-20);
  text("'"+sum+"'", width/2, height/2+20);
}

boolean prime_number(int p_num) {
  boolean result = true;
  int divisor = 2;
  while (divisor<p_num) {
    if (p_num%divisor==0) {
      result = false;
      break;
    }
    result = true;
    divisor++;
  }
  return result;
}

Lab4 Multiplication Table

void setup() {
  size(250, 300);
  background(0);
  int multi_table = 25;
  int max_multiplier_value = 12;
  int x=1;
  textSize(18);
  text("Multiplication Table "+"'"+multi_table+"'", 10, 20);
  while (x <= max_multiplier_value) {
    int result = multi_table*x;
    text(multi_table+" x "+x+" = "+result, 10, 30+(20*x));
    x++;
  }
}

Lab4 Sum of Integers

void setup() {
  size(300, 100);
  background(0);
  int max_val = 99;
  int x=0;
  int sum=0;
  while (x <= max_val) {
    sum += x;
    x++;
  }
  textSize(18);
  textAlign(CENTER);
  text("Sum of Integers from 1 to "+max_val, width/2, height/2-20);
  text("'"+sum+"'", width/2, height/2+20);
}

9 กันยายน 2558

Lab3 Grade from Score

void setup() {
  size(300, 150);
  background(0);
  int score = 49;
  fill(255);
  textAlign(CENTER);
  textSize(25);
  text("Your score = "+score, width/2, height/2-20);
  if (score>=80) {
    text("Grade A ", width/2, height/2+20);
  } else if (score>=70) {
    text("Grade B ", width/2, height/2+20);
  } else if (score>=60) {
    text("Grade C ", width/2, height/2+20);
  } else if (score>=50) {
    text("Grade D ", width/2, height/2+20);
  } else {
    text("Grade F ", width/2, height/2+20);
  }
}


Lab3 Power of 10


void setup() {
size(300, 100);
background(0);
fill(255);
textAlign(CENTER);
textSize(25);
int number=6;
power_of_ten(number);
}

void power_of_ten(int num) {
if (num == 6) {
text("10^"+num+" = "+"Million", width/2, (height/2)+5);
} else if (num == 9) {
text("10^"+num+" = "+"'Billion'", width/2, (height/2)+5);
} else if (num == 12) {
text("10^"+num+" = "+"Trillion", width/2, (height/2)+5);
} else if (num == 15) {
text("10^"+num+" = "+"'Quadrillion'", width/2, (height/2)+5);
} else if (num == 18) {
text("10^"+num+" = "+"'Quintillion'", width/2, (height/2)+5);
} else if (num == 21) {
text("10^"+num+" = "+"'Sextillion'", width/2, (height/2)+5);
} else if (num == 30) {
text("10^"+num+" = "+"'Nonillion'", width/2, (height/2)+5);
} else if (num == 100) {
text("10^"+num+" = "+"'Googol'", width/2, (height/2)+5);
} else {
text("10^"+num+" = "+"No Word", width/2, (height/2)+5);
}
}




Lab3 Leap Year

void setup() {
  int year = 2015;
  size(270, 80);
  background(0);
  fill(255);
  textAlign(CENTER);
  textSize(25);

  if (year%400==0) {
    text(year+" is "+"leap year", width/2, height/2 );
  } else if (year%100==0) {
    text(year+" isn't "+"leap year", width/2, height/2 );
  } else if (year%4==0) {
    text(year+" is "+"leap year", width/2, height/2 );
  } else {
    text(year+" isn't "+"leap year", width/2, height/2 );
  }
}

Lab3 Flying bird

float wing_y;
int size_draw = 50;
boolean w_up;
boolean w_down;
void setup() {
  size(400, 500);
  background(255);
  mouseX=width/2;
  mouseY=height/2;
  w_up = true;
}

void draw() {
  background(255);
  draw_bird(mouseX, mouseY, size_draw);
  if (w_up == true) {
    if (mouseY<=100)wing_y-= size_draw*0.30;
    if (mouseY>100&&mouseY<=200)wing_y-= size_draw*0.20;
    if (mouseY>200&&mouseY<=300)wing_y-= size_draw*0.15;
    if (mouseY>300&&mouseY<=400)wing_y-= size_draw*0.10;
    if (mouseY>400&&mouseY<=500)wing_y-= size_draw*0.07;
    if (wing_y <= -(size_draw*0.5)) {
      w_up = false;
      w_down = true;
    }
  }
  if (w_down == true) {
    if (mouseY<=100)wing_y+= size_draw*0.30;
    if (mouseY>100&&mouseY<=200)wing_y+= size_draw*0.20;
    if (mouseY>200&&mouseY<=300)wing_y+= size_draw*0.15;
    if (mouseY>300&&mouseY<=400)wing_y+= size_draw*0.10;
    if (mouseY>400&&mouseY<=500)wing_y+= size_draw*0.07;
    if (wing_y >= (size_draw*0.5)) {
      w_up = true;
      w_down = false;
    }
  }
  if (keyCode==UP) {
    size_draw++;
    if (size_draw>=110)size_draw=110;
  }
  if (keyCode==DOWN) {
    size_draw--;
    if (size_draw<=50)size_draw=50;
  }
}

void draw_bird(int mouse_x, int mouse_y, int s_draw) {
  fill(#D30327);
  strokeWeight(s_draw*0.2);
  line(mouse_x, mouse_y-(s_draw*0.5), mouse_x-(s_draw*1.3), mouse_y+wing_y-(s_draw*0.5));
  line(mouse_x, mouse_y-(s_draw*0.5), mouse_x+(s_draw*1.3), mouse_y+wing_y-(s_draw*0.5));
  strokeWeight(s_draw*0.05);
  ellipse(mouse_x, mouse_y-(s_draw*0.5), s_draw, s_draw);
  strokeWeight(1);
  fill(255);
  ellipse(mouse_x-(s_draw*0.22), mouse_y-(s_draw*0.6), s_draw*0.3, s_draw*0.35);
  ellipse(mouse_x+(s_draw*0.22), mouse_y-(s_draw*0.6), s_draw*0.3, s_draw*0.35);
  fill(0);
  ellipse(mouse_x-(s_draw*0.22), mouse_y-(s_draw*0.6), s_draw*0.1, s_draw*0.1);
  ellipse(mouse_x+(s_draw*0.22), mouse_y-(s_draw*0.6), s_draw*0.1, s_draw*0.1);
  fill(#F9BC09);
  triangle(mouse_x-(s_draw*0.17), mouse_y-(s_draw*0.35), mouse_x+(s_draw*0.17),
    mouse_y-(s_draw*0.35), mouse_x, mouse_y-(s_draw*0.05));
}

Lab3 Martin (interaction)

int pos_x;
int pos_y;
color clr_x_sign;
color clr_positive_sign;
void setup(){
size (600,600);
background(0);
frameRate(30);
clr_x_sign = color(255);
clr_positive_sign = color(255);
}

void draw(){
draw_martin(pos_x,pos_y);
if(key=='w'||key=='W'){
pos_y-=2;
if(pos_y<=-33){ pos_y=-33; } } if(key=='s'||key=='S'){ pos_y+=2; if(pos_y>=230){
pos_y=230;
}
}
if(key=='a'||key=='A'){
pos_x-=2;
if(pos_x<=-56){ pos_x=-56; } } if(key=='d'||key=='D'){ pos_x+=2; if(pos_x>=55){
pos_x=55;
}
}
}

void draw_martin(int x , int y){
background(0);
//----- Frame -----//
noStroke();
rect(x+60,y+35,480,280,2); // Frame outside
fill(0);
rect(x+100,y+75,400,200,2);// Frame inside

//----- Positive Sign -----//
fill(clr_positive_sign);
rect(x+140,y+155,140,40,2);
rect(x+190,y+105,40,140,2);

//----- X Sign -----//
fill(clr_x_sign);
quad(x+349,y+105,x+460,y+216,x+431,y+245,x+320,y+134);
quad(x+431,y+105,x+460,y+134,x+349,y+245,x+320,y+216);

//----- Tiltle -----//
fill(255);
PFont font;
font = loadFont("Arial-Black-52.vlw");
textFont(font);
textSize(52);
text("MAR", x+65 , y+365);
text("IN", x+232 , y+365);
text("GARRI", x+313 , y+365);

//----- Positive Sign Tiltle -----//
rect(x+195,y+341,36,10);
rect(x+208,y+328,10,36);
//----- X Sign Tiltle -----//
quad(x+503,y+328,x+533,y+358,x+526,y+365,x+496,y+335);
quad(x+526,y+328,x+533,y+335,x+503,y+365,x+496,y+358);
}

void keyPressed(){
if(key=='z'||key=='Z'){
clr_x_sign = color(random(0,255),random(0,255),random(0,255));
}
if(key=='x'||key=='X'){
clr_positive_sign = color(random(0,255),random(0,255),random(0,255));
}
if(key=='r'||key=='R'){
clr_x_sign = color(255);
clr_positive_sign = color(255);
}
}




Lab3 Doraemon book (interaction)


int pos_x;
int pos_y;
color clr_bg_dora;

void setup() {
size(500, 500);
background(#F6B0D8);
frameRate(25);
clr_bg_dora = color(255);
}

void draw(){
draw_book(pos_x , pos_y);
if(key=='w'||key=='W'){
pos_y-=1;
if(pos_y<=-78){ pos_y=-78; } } if(key=='s'||key=='S'){ pos_y+=1; if(pos_y>=57){
pos_y=57;
}
}
if(key=='a'||key=='A'){
pos_x-=1;
if(pos_x<=-98){ pos_x=-98; } } if(key=='d'||key=='D'){ pos_x+=1; if(pos_x>=98){
pos_x=98;
}
}

}

void draw_book(int pos_x, int pos_y){
background(#F6B0D8);
strokeJoin(ROUND);
//----- front page -----//
strokeWeight(2);
fill(#323C5D);
rect(pos_x+100,pos_y+100,270,340);

//----- behind doraemon background -----//
noStroke();
fill(#FCE314);
rect(pos_x+125,pos_y+220,220,205);

//----- name book background -----//
fill(clr_bg_dora);
rect(pos_x+125,pos_y+130,220,50);
//----- name book -----//
fill(0);
textSize(35);
text("DORAEMON", pos_x+133, pos_y+167);

//----- book page -----//
strokeWeight(2);
stroke(0);
fill(255);
quad(pos_x+100,pos_y+100,pos_x+130,pos_y+80,pos_x+400,pos_y+80,pos_x+370,pos_y+100);
quad(pos_x+370,pos_y+100,pos_x+400,pos_y+80,pos_x+400,pos_y+420,pos_x+370,pos_y+440);
strokeWeight(1);
line(pos_x+106,pos_y+96,pos_x+376,pos_y+96);
line(pos_x+112,pos_y+92,pos_x+382,pos_y+92);
line(pos_x+118,pos_y+88,pos_x+388,pos_y+88);
line(pos_x+124,pos_y+84,pos_x+394,pos_y+84);
line(pos_x+376,pos_y+96,pos_x+376,pos_y+436);
line(pos_x+382,pos_y+92,pos_x+382,pos_y+432);
line(pos_x+388,pos_y+88,pos_x+388,pos_y+428);
line(pos_x+394,pos_y+84,pos_x+394,pos_y+424);

//----- Doraemon -----//
strokeWeight(3);
stroke(#325D87);
//----- face -----//
fill(#4F81BC);
ellipse(pos_x+235,pos_y+320,200,175);
fill(255);
ellipse(pos_x+235,pos_y+334,140,125);

//----- eyes -----//
fill(255);
ellipse(pos_x+215,pos_y+274,37,50);
ellipse(pos_x+255,pos_y+274,37,50);
fill(#325D87);
ellipse(pos_x+220,pos_y+279,8,8);
strokeWeight(4);
arc(pos_x+248,pos_y+281,6,6,PI,TWO_PI);
strokeWeight(3);

//----- nose -----//
fill(#FE0000);
ellipse(pos_x+235,pos_y+301,20,20);

//----- mounth -----//
noFill();
arc(pos_x+235,pos_y+350,100,50,0,PI);
line(pos_x+235,pos_y+312,pos_x+235,pos_y+375);

//----- Whiskers -----//
line(pos_x+220,pos_y+320,pos_x+177,pos_y+315);
line(pos_x+220,pos_y+325,pos_x+175,pos_y+325);
line(pos_x+220,pos_y+330,pos_x+177,pos_y+335);

line(pos_x+250,pos_y+320,pos_x+293,pos_y+315);
line(pos_x+250,pos_y+325,pos_x+295,pos_y+325);
line(pos_x+250,pos_y+330,pos_x+293,pos_y+335);

//----- collar -----//
fill(#FD0000);
rect(pos_x+185,pos_y+395,100,13);

//----- bell -----//
fill(#FCBE0C);
ellipse(pos_x+235,pos_y+394,20,20);

//----- hands -----//
fill(255);
ellipse(pos_x+180,pos_y+395,30,28);
ellipse(pos_x+290,pos_y+395,30,28);

}

void keyPressed(){
if(key=='c'||key=='C'){
clr_bg_dora = color(random(0,255),random(0,255),random(0,255));
}
if(key=='r'||key=='R'){
clr_bg_dora = color(255);
}
}





31 สิงหาคม 2558

Lab3 Capt (interaction)

float move = 0;
float size_draw = 250;
float pos_x_shield = 370;
float speed;
color cl_star;
boolean start_fw;
boolean start_bw;

void setup() {
size(600, 600);
background(#0D0D0D);
start_fw=true;
speed=2;
}

void draw() {
draw_capt(move);
if (start_fw == true) {
move +=speed;
pos_x_shield +=speed;
if (pos_x_shield >= 475) {
start_fw = false;
start_bw = true;
}
}

if (start_bw == true) {
move -=speed;
pos_x_shield -=speed;
if (pos_x_shield <= 125) { start_fw = true; start_bw = false; } } cl_star= color(random(0, 255), random(0, 255), random(0, 255)); fill(255); textSize(13); text("speed "+speed, 20, 20); } void draw_capt(float pos_x) { background(#0D0D0D); noStroke(); fill(255); textSize(550); text("A", 100, 500);// A font fill(255); //----- title -----// textSize(30); text("CAPTAIN AMERICA", 162, 570); //----- Shield -----// fill(#EE0000); ellipse(pos_x_shield, 300, size_draw, size_draw); fill(255); ellipse(pos_x+370, 300, size_draw*0.84, size_draw*0.84); fill(#EE0000); ellipse(pos_x+370, 300, size_draw*0.68, size_draw*0.68); fill(#000080); ellipse(pos_x+370, 300, size_draw*0.52, size_draw*0.52); //----- Star -----// beginShape(); fill(cl_star); vertex(pos_x+370, 243); vertex(pos_x+382.5, 280.5); vertex(pos_x+420, 280.5); vertex(pos_x+395, 305.5); vertex(pos_x+407.5, 343); vertex(pos_x+370, 318); vertex(pos_x+332.5, 343); vertex(pos_x+345, 305.5); vertex(pos_x+320, 280.5); vertex(pos_x+357.5, 280.5); endShape(CLOSE); } void keyPressed() { if (keyCode==UP)speed+=0.5; if (keyCode==DOWN)speed-=0.5; if (speed<=2)speed=2; if (speed>=30)speed=30;
}