2015年2月19日 星期四

[Java] resize image + imagebutton

  1.  // resize image + make imagebutton

  2.  JPanel panel = new JPanel();
  3.              panel.setLayout(null); // set 了layout是null後必需調用setBounds
  4.              panel.setBounds(0, 0, 200 , 200); // 參數1: x座標; 2:y座標; 3:width; 4:height

  5.              
  6.      ImageIcon img = new ImageIcon(getClass().getResource("/lam/images/1.jpg"));
  7.  
  8.               // resize img width and height to 100,100

  9.               Image image = img.getImage();
  10.               Image newimg = image.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
  11.               img = new ImageIcon(newimg);
  12.  
  13.                // add image to button
  14.                              
  15.               JButton btn = new JButton();
  16.               btn.setBorder(LineBorder.createGrayLineBorder());
  17.               btn.setIcon(img);  
  18.               btn.setBounds(0, 0, 150, 120);

  19.       panel.add(btn);



2015年2月9日 星期一

[java] 字母貪食蛇小遊戲 - Object、GUI、keylistener的應用






字母貪食蛇小遊戲 - Object、GUI、KeyListener的應用。




































  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */

  6. package snakegui;

  7. /**
  8.  *
  9.  * @author kongyinlam
  10.  */
  11. import java.awt.*;
  12. import javax.swing.*;
  13. import java.awt.event.*;
  14. import java.util.*;
  15. public class SnakeGUI {

  16.     /**
  17.      * @param args the command line arguments
  18.      */
  19.     public static void main(String[] args) {
  20.            SnakeGame sg = new SnakeGame(20,30);
  21.                      sg.play('w');
  22.     }
  23.    
  24. }
  25. class SnakeGame implements KeyListener{
  26.       Board b;
  27.       ArrayList<Token> tokens;
  28.       int py, px;
  29.       boolean isEaten=false;
  30.       public SnakeGame(int h, int w){
  31.              b = new Board(h, w, this);
  32.                          
  33.              tokens = new ArrayList<>();
  34.              for(int i=0; i<4; i++){
  35.                  Token token = new Token(this, b, tokens.size());
  36.                  token.setInitPos();
  37.                  tokens.add(token);
  38.              }
  39.             
  40.                            
  41.       }
  42.       public void play(char key){
  43.                  
  44.                   b.clearBoard();
  45.                  
  46.                   if(isEaten) eaten();
  47.                  
  48.                   for(Token tokenss: tokens)
  49.                      tokenss.MoveToken(key);
  50.                  
  51.                   b.paintBoard();
  52.       }
  53.        public void eaten(){
  54.              isEaten = false;
  55.              Token token = new Token(this, b, tokens.size());
  56.              token.y = tokens.get(tokens.size()-1).y;
  57.              token.x = tokens.get(tokens.size()-1).x;
  58.              token.c = tokens.get(0).c;
  59.              tokens.add(token);
  60.              tokens.get(0).y = new Random().nextInt(b.h-3)+1;
  61.              tokens.get(0).x = new Random().nextInt(b.w-3)+1;
  62.              tokens.get(0).c = (char)(new Random().nextInt(26)+97);
  63.             
  64.       }

  65.     @Override
  66.     public void keyTyped(KeyEvent e) {
  67.            try{
  68.            char key = (""+e.getKeyChar()).toLowerCase().charAt(0);
  69.            if(key=='w'||key=='s'||key=='a'||key=='d')
  70.                    play(key);
  71.            }
  72.            catch(Exception ee){}
  73.      }

  74.     @Override
  75.     public void keyPressed(KeyEvent e) {
  76.                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

  77.     }

  78.     @Override
  79.     public void keyReleased(KeyEvent e) {
  80.         throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  81.     }

  82. }
  83. class Token{
  84.       SnakeGame sg;
  85.       Board b;
  86.       int id;
  87.       int y,x;
  88.       char c;
  89.       public Token(SnakeGame sg, Board b, int id){
  90.              this.sg = sg;
  91.              this.b = b;
  92.              this.id = id;
  93.              c = (char)(new Random().nextInt(26)+97);
  94.             
  95.       }
  96.       public void setInitPos(){
  97.              if(id==0){
  98.                     y = 10;
  99.                     x = 10;
  100.              }
  101.              else {
  102.                     y = b.h-4+id;
  103.                     x = b.w-4;
  104.              }
  105.             
  106.       }
  107.       public void MoveToken(char k){
  108.              if(id!=0){
  109.                 if(id==1){
  110.                     sg.py = y;
  111.                     sg.px = x;
  112.                     switch(k){
  113.                         case 'w' : y-=1; break;
  114.                         case 's' : y+=1; break;
  115.                         case 'd' : x+=1; break;
  116.                         case 'a' : x-=1; break;
  117.                     }
  118.                     if(b.layout[y][x]=='*') JOptionPane.showMessageDialog(null, "GameOver", "Result", JOptionPane.INFORMATION_MESSAGE);
  119.                     else if(y==sg.tokens.get(0).y&&x==sg.tokens.get(0).x){
  120.                             sg.isEaten=true;
  121.                     }
  122.                 }
  123.                 else{
  124.                     int ty = y;
  125.                     int tx = x;
  126.                     y = sg.py;
  127.                     x = sg.px;
  128.                     sg.py = ty;
  129.                     sg.px = tx;
  130.                 }
  131.              }
  132.              b.layout[y][x] = c;
  133.       }
  134.     
  135. }
  136. class Board{
  137.       JFrame f;
  138.       int h,w;
  139.       char[][] layout;
  140.       public Board(int h, int w, SnakeGame sg){
  141.              this.h = h;
  142.              this.w = w;
  143.             
  144.              f = new JFrame();            
  145.              f.setSize(w*20, h*30);
  146.              Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
  147.              f.setLocation(dim.width/2-f.size().width/2, dim.height/2-f.size().height/2);            
  148.              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  149.             
  150.              f.setLayout(new GridBagLayout());
  151.              f.addKeyListener(sg);
  152.             
  153.              layout = new char [h][w];

  154.           
  155.             
  156.       }
  157.       public void clearBoard(){
  158.              f.getContentPane().removeAll();

  159.              for(int i=0; i<h; i++){
  160.              for(int j=0; j<w; j++){
  161.                  if(i==0||i==h-1||j==0||j==w-1) layout[i][j]='*';
  162.                  else layout[i][j]=' ';
  163.              }                
  164.              }
  165.       }
  166.       public void paintBoard(){
  167.             
  168.              for(int i=0; i<h; i++){
  169.              for(int j=0; j<w; j++){
  170.                  GridBagConstraints gbc = new GridBagConstraints();
  171.                  JLabel lb = new JLabel(""+layout[i][j]);
  172.                  gbc.gridx = j;
  173.                  gbc.gridy = i;
  174.                  gbc.ipadx = 10;
  175.                  gbc.ipady = 2;
  176.                  gbc.anchor = GridBagConstraints.CENTER;
  177.                  f.add(lb, gbc);
  178.              }
  179.              }
  180.              f.getContentPane().repaint();
  181.              f.setVisible(true);
  182.       }
  183.      
  184. }









2015年1月31日 星期六

[C++] string 轉 char array



==========================================


  1.  #include <iostream>

  2. using namespace std;


  3. int main(){

  4.      string s;

  5.      cin >> s; // input

  6.      char c [s.length()];
  7.     
  8.      for(int i=0; i<s.length(); i++){
  9.           c[i] = s[i];
  10.       }
  11.    
  12.    return 0;
  13. }

===========================================


[C++] size_t 介紹


size_t 类型在C++上是定义在cstddef头文件中,而在C上是定義在头文件stddef.h 中。
它是一个与机器相关的unsigned类型,其大小足以保证存储内存中对象的大小。

中文名:size_t
外文名:unsigned int

在C++中,设计 size_t 就是为了适应多个平台的 。size_t的引入增强了程序在不同平台上的可移植性。size_t是针对系统定制的一种数据类型,一般是整型,因为C/C++标准只定义一最低的位数,而不是必需的固定位数。而且在内存里,对数的高位对齐存储还是低位对齐存储各系统都不一样。为了提高代码的可移植性,就有必要定义这样的数据类型。一般这种类型都会定义到它具体占几位内存等。当然,有些是编译器或系统已经给定义好的。经测试发现,在32位系统中size_t是4字节的,而在64位系统中,size_t是8字节的,这样利用该类型可以增强程序的可移植性。




文章出處:size_t 百度 http://baike.baidu.com/view/3236587.htm

2015年1月29日 星期四

C++ 字串函數 (String method)






C++ 內置了一個String類別,內裡有很多函數給予我們處理字串的運算。


最常用有以下:


方 法 說 明
assign(string, start, num) 從string的第start個字元取出num個字元來指定給另一字串物件。
append(string, start, num) 從string的第start個字元取出num個字元來附加至另一字串物件之後。
find(string, 0) 從引發find的字串物件第0個字元尋找是否有符合string的子字串。
insert(start, string) 將string插入引發insert的字串物件第start個字元之後。
length() 傳回字串的長度。




===================================

// assign 的使用

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;


int main(){

    string str1;
    str1 = str1.assign("c++isfunny", 5, 6);
    cout << "str1: " << str1 << endl;
  
    return 0;
  
}

====================================

- output : funny
- 注意的是,就算第3個參數-->6 可能已經超出字串範圍,但都不會造成error的。


*有學習JAVA的朋友可能會覺得assign method和java裡的substring method 相當相似,但其實並不
一樣的,substring函數是 String substring(int beginIndex, int endIndex),第二個參數是endindex,即字串只會copy到endindex前一個字符就會停,與assign函數是不同的。




C++ 亂數函數 rand() 和 srand()




所謂的亂數,即是指電腦自動產生的一個數字,好似一個六合彩號碼般,
無永遠沒法知道下一個出現的號碼。而C/C++的亂碼其實是由一個亂數產
生器產生的,函數名稱是rand,放在stdlib.h / cstdlib 表頭檔裡面,在使用
時直接呼叫 rand() 便可。


註:若果你不明白表頭檔 <stdlib.h> 是什麼 ,可以到這篇文章看看-->> stdlib.h介紹





Rand() 和 Srand()



先來個rand()使用的示範:
==================================

  1. #include <iostream>
  2. #include <stdlib.h>    // 引入表頭檔

  3. using namespace std;  

  4. int main(){

  5.     for(int i=0; i<5; i++){
  6.         cout<< rand() << endl;    // 印出5個亂數
  7.     }
  8.  
  9.     return 0;
  10.    


===================================



你可能會好奇,那究竟這些亂數的範圍到底是多少呢?

目前可以確定的是,最大值(RAND_MAX) 至少會是 0x7fff (轉換10進制後是32767),
最大會是多少不一定。以 Visual C++ 2010 環境而言,這個值是 32767。實際上
VC6.0 , VC2002 / 2003 , VC2008, VC2010 , gcc, Dev-C++ , Code::Blocks (with mingw) ,
這個值也都剛好是 32767,只是他們實作的亂數細節不同而已。但新版的版本的
RAND_MAX 會更大,例如在mac上用xcode開發的C/C++,最大值便是2147483647(231-1)
主要是看軟體( compiler )的實作方式,若想查下最大值是多少,不坊用以下程式測試一下:



========================
  1. #include <iostream>
  2. #include <stdlib.h>
  3. using namespace std;
  4. int main(){
  5.  
  6.     cout<< RAND_MAX;
  7.  
  8.     return 0;
  9.    
  10. }
========================


另外,當你不停用rand() run最初的程式時,會發現產生出來的亂數都是一樣的,因為rand()產生
的是偽隨機數字,每次執行時都是相同的,給果想要不同,就要使用srand()函數初始化它。

在預設的情況下,rand()的隨機種子(seed :指起始點,即最小值) 是1,而相同的隨機種子
產生的結果都是一樣的。那初始值該給多少?初始值給固定的值都沒用,要會隨著環境變動
的值才有意義,像是 記憶體使用量、process id 、CPU 使用率 等,這些都是會隨環境變動,
但有些變動性可能不大,而最常用來給初始值的,是時間,所以程式可以修改如下:


===========================================

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. int main()
  5. {
  6.     int i;
  7.     unsigned seed;
  8.     seed = (unsigned)time(NULL); // 取得時間序列
  9.     srand(seed); // 以時間序列當亂數種子
  10.     for(i=0; i<5; i++)
  11.          cout << rand() << endl; 
  12.     return 0;
  13. }

===========================================


註:

- 7-9 行可以縮短為 srand( (unsigned) time(NULL) );

- time(NULL),傳入值為NULL可以獲取當前時間的總秒數(從 00:00 hours, Jan 1, 1970 UTC 起),
  實際語法如下, time_t time (time_t* timer) 。

- 如果不明白什麼是 unsigned ,請先看這篇文章--> Unsigned keyword







Rand() 指定範圍



-需要使用%運算子,如果不明什麼是%,就GOOGLE一下吧。

程式如下:

================================

  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <time.h>

  4. using namespace std;


  5. int main(){

  6.     srand( (int)time(NULL));
  7.  
  8.     for(int i=0; i<5; i++)
  9.     cout<< rand()%6+2 <<endl;
  10.  
  11.     return 0;
  12.    
  13. }

================================


以上程序運行後,將會輸出5個號碼,範圍由 2~7 。

-rand()%6 :即指定範圍需要由起始數開始取6個數值,包括起始數
-rand()%6+2 :+2 的意思是指定起始數是2,然後由2開始取六個數作為range(包括2),
                           若沒有+2,起始數預設是0。










C++ stdlib.h 介紹

 
stdlib 意思即 standard library 標準庫頭文件
 
stdlib 包含了C、C++语言的最常用的系统函数
 
常用的函数如malloc()、calloc()、realloc()、free()、system()、atoi()、atol()、rand()、srand()、exit()等等。
 
具體內容可以自己打開編譯器的include目錄裡的 stdlib.h 頭文件看看。