?? spell.cpp
字號:
#include "stdafx.h"
#include "spell.h"
#include <stdlib.h>
#include <time.h>
CSpell::CSpell(int w, int h, int bx, int by){
// 構造函數,傳入長和寬
width = w;
height = h;
bx = (bx>=w)?(w-1):(bx<0 ? 0 : bx);
by = (by>=h)?(h-1):(by<0 ? 0 : by);
blank = by * w + bx;
map = new int[w*h];
for(int i = 0; i < w*h; i++){
map[i] = i;
}
// 初始化
Init();
}
CSpell::~CSpell(){
delete [] map;
}
void CSpell::ReCreate(int w, int h, int bx, int by){
// 重新構建大小
delete [] map;
width = w;
height = h;
bx = (bx>=w)?(w-1):(bx<0 ? 0 : bx);
by = (by>=h)?(h-1):(by<0 ? 0 : by);
blank = by * w + bx;
map = new int[w*h];
for(int i = 0; i < w*h; i++){
map[i] = i;
}
// 初始化
Init();
}
int CSpell::GetPic(int w, int h){
// 獲取個某個位置的圖片
if(w < 0 || w >= width || h < 0 || h >= height){
return -1;
}
return map[h*width + w];
}
int CSpell::Move(int w, int h){
// 移動某個位置的圖片
if(w < 0 || w >= width || h < 0 || h >= height){
return -10;
}
if(blank == map[h*width+w]){
return -1;
}
if(blank == GetPic(w-1, h)){
int t = map[h*width+w];
map[h*width+w] = map[h*width+w-1];
map[h*width+w-1] = t;
}
else if(blank == GetPic(w+1, h)){
int t = map[h*width+w];
map[h*width+w] = map[h*width+w+1];
map[h*width+w+1] = t;
}
else if(blank == GetPic(w, h-1)){
int t = map[h*width+w];
map[h*width+w] = map[(h-1)*width+w];
map[(h-1)*width+w] = t;
}
else if(blank == GetPic(w, h+1)){
int t = map[h*width+w];
map[h*width+w] = map[(h+1)*width+w];
map[(h+1)*width+w] = t;
}
else{
return -1;
}
for(int i = 0; i < LENGTH; i++){
if(i != map[i]){
return 0;
}
}
return 1;
}
void CSpell::Init(){
// 初始化(生成隨機位置)
srand(time(NULL));
int a, b, t;
int i = 0, d = 1;
while(i++ < LENGTH || d == 0){// 交換至少單位數量次
do{
a = rand()%(LENGTH);
b = rand()%(LENGTH);
}
while(a == b);
t = map[a];
map[a] = map[b];
map[b] = t;
// 計算距離,必須要模為1有解
if(blank == map[a] || blank == map[b]){
int w = a%width - b%width + 1;
int h = a/width - b/width;
w = w<0?-w:w;
h = h<0?-h:h;
d = (d+w+h)%2;
}
else{
d = !d;
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -