原谅我可怜的英语。 我写了一个代码来呈现河内算法。我想展示一个简单的动画。 像这样https://www.youtube.com/watch?v=o2YSdRJg0s8 但我真的不知道何时应该调用绘图功能。
#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
#include <sstream>
#include <math.h>
#define X1 150
#define X2 300
#define X3 450
#define witdh 10
void hanoi(int, char, char, char);
void printWin(int n);
void printBar(char ch,int n);
int mouse();
int time = 0;
int A=0,B=0,C=0;
int main(void)
{
int n;
printWin(3);
mouse();
system("pause");
}
void hanoi(int n, char A, char B, char C)
{
int i;
if (n == 1)
{
//I want to draw a animation instead this text describe.
printf("%d: move %d from %c to %c\n", ++time, n, A, C);
}
else
{
hanoi(n - 1, A, C, B);
printBar('A',n); //I dont know how to use printBar property
delay(200);
//I want to draw a animation instead this text describe.
printf("%d: move %d from %c to %c\n", ++time, n, A, C);
//So I use printBar.But its incorrect
printBar('C',n);
hanoi(n - 1, B, A, C);
delay(200);
printBar('B',n);
}
}
void printWin(int n) //initial the button and draw the window
{
int Y1=250,Y2=200,Y3=300;
initwindow(800, 600);
char msg[10];
int i=0;
sprintf(msg,"%d",n);
rectangle(X1-50,300,X1+50,350); //button GO
rectangle(X2-50,300,X2+50,350); //button ADD
rectangle(X3-50,300,X3+50,350); //button SUB
outtextxy(140,315,"GO");
outtextxy(290,315,"ADD");
outtextxy(440,315,"SUB");
outtextxy(360,320," ");
outtextxy(360,315,msg);
rectangle(X1,Y1,X1+5,Y1-100);
rectangle(X2,Y1,X2+5,Y1-100);
rectangle(X3,Y1,X3+5,Y1-100);
rectangle(X1-50,Y1,X1+50,Y1+5);
rectangle(X2-50,Y1,X2+50,Y1+5);
rectangle(X3-50,Y1,X3+50,Y1+5);
outtextxy(X1,Y1+15,"A");
outtextxy(X2,Y1+15,"B");
outtextxy(X3,Y1+15,"C");
for(i=n;i>0;i--) printBar('A',i); //draw the initial statement(with 5 sticks
}
void printBar(char ch,int n) //drawing bar in hanoi
{
int x=0,y=0;
int Y1=250,Y2=200,Y3=300;
setfillstyle(SOLID_FILL,WHITE);
if(ch=='A')
{
x=X1;
A++;
y=Y1-A*witdh;
}
if(ch=='B')
{
x=X2;
B++;
y=Y1-B*witdh;
}
if(ch=='C')
{
x=X3;
C++;
y=Y1-C*witdh;
}
//rectangle(X1,Y1,X1+5,Y1-100);
bar(x-n*witdh,y,x+n*witdh,y-5);
}
int mouse() //get the button click
{
int x,y;
while(!ismouseclick(WM_RBUTTONDOWN))
{
if(ismouseclick(WM_LBUTTONDOWN))
getmouseclick(WM_LBUTTONDOWN,x,y);
//printf("%d%d",x,y);
if(x>(X1-50)&&x<X1+50)
{
hanoi(3, 'A', 'B', 'C');
return 0;
}
}
}