📄 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 + -