struct & function
struct
Why struct?

想想看你是設計fall guys的人,那麼每場遊戲你要怎麼紀錄每個玩家的狀態?
Why struct?

每個玩家的狀態可能:
- 地圖上的x位置
- 地圖上的y位置
- x方向的速度
- y方向的速度
- 目前按住的按鍵
- 是否為撲倒狀態
- ...
double x[60];
double y[60];
double vx[60];
double vy[60];
bool key[60][4];
bool fall[60];
很難統整在一起。
(每個資料沒有直接關係,是散開的)
Why struct?
每個玩家的狀態可能:
- 地圖上的x位置
- 地圖上的y位置
- x方向的速度
- y方向的速度
- 目前按住的按鍵
- 是否為撲倒狀態
- ...
double x[60];
double y[60];
double vx[60];
double vy[60];
bool key[60][4];
bool fall[60];
struct fall_guys{
double x, y;
double vx, vy;
bool key[4];
bool fall;
};
struct fall_guys players[60];
Example Usage
#include <stdio.h>
struct fall_guys{
double x, y;
double vx, vy;
bool key[4];
bool fall;
};
struct fall_guys players[60];
int main(){
scanf("%lf%lf", &players[0].x, &players[0].y);
printf("x0: %lf, y0: %lf\n", players[0].x, players[0].y);
return 0;
}
typedef
type define - 定義型態名稱
把int換個名字?
typedef int I;
typedef double D;
struct fall_guys -> fall_guys
#include <stdio.h>
typedef struct fall_guys{
double x, y;
double vx, vy;
bool key[4];
bool fall;
}fall_guys;
fall_guys players[60];
int main(){
scanf("%lf%lf", &players[0].x, &players[0].y);
printf("x0: %lf, y0: %lf\n", players[0].x, players[0].y);
return 0;
}
Cursor
游標
POINT
typedef struct tagPOINT {
LONG x;
LONG y;
} POINT, *PPOINT, *NPPOINT, *LPPOINT;
在windows api裡面,有這樣的一份code...
Get Cursor
#include <windows.h>
POINT pt;
GetCursorPos(&pt);
// pt.x就會等於現在的滑鼠x座標
// pt.y就會等於現在的滑鼠y座標
Set Cursor
#include <windows.h>
SetCursorPos(x, y);
夠直觀吧?
Exercise
隨時輸出現在滑鼠位置。
Function
Function in math
f(x) = x^2 + x + 1
Define:
f(5) = 31
Usage:
f(x, y) = x^2 + y + 1
Define:
f(5, 2) = 28
Usage:
Function Def
[type] [function name] (params){
// Do something
return [val];
}
int f(int x){
return x * x + x + 1;
}
記不起來可以看看main是怎麼寫的。
f(x) = x^2 + x + 1
參數
函式名稱
回傳甚麼型態
回傳
Function Usage
int f(int x){
return x * x + x + 1;
}
跟數學的用法一樣。
printf("%d", f(5));
// -----
cout << f(5);
Function Tips
void Hi(){
printf("Hi");
return ;
}
1. 如果沒有要回傳東西,type可以用void。
要強制結束function可以用return ; (return後面直接接;)
2. 參數可多可少,也可以是空的。
3. 傳陣列也沒問題。
Exercise
假設一開始機器人的座標是0,請支援以下操作:
指令 "left" : x扣1。
指令 "right" : x加1。
指令 "print" : 輸出地圖。(空的表示_,牆表示|,機器人表示X)
機器人無法移動到0以下以及10以上(不包含)
如果機器人有移動到,自帶print。
Exercise
#include <stdio.h>
#include <string.h>
// TODO
int main(){
int pos = 0;
char S[100];
while(scanf("%s", S)!= EOF){
if(strcmp(S, "left")==0){
pos = left(pos);
}else if(strcmp(S, "right")==0){
pos = right(pos);
}else if(strcmp(S, "print")==0){
print(pos);
}
}
return 0;
}
Keyboard Control
鍵盤設定&監聽
GetKeyState
偵測現在按鍵狀態
偵測A
偵測左Shift
GetKeyState('A');
GetKeyState(VK_LSHIFT);
偵測左鍵
GetKeyState(VK_LEFT);
keybd_event
模擬按鍵輸入
按住A
keybd_event('A', 0, KEYEVENTF_EXTENDEDKEY|0, 0);
keybd_event('A', 0, KEYEVENTF_KEYUP|0, 0);
放開A
Exercise
每隔1秒按一次backspace (VK_BACK)
struct & function
By Arvin Liu
struct & function
- 447