P. 1
32977162-Ghidul-Incepatorului-Programare

32977162-Ghidul-Incepatorului-Programare

|Views: 4,469|Likes:
Published by Chiches Ciprian

More info:

Published by: Chiches Ciprian on Mar 14, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

10/19/2015

pdf

text

original

Sections

Oferim în continuare cîteva exemple de programe, unele în Pascal, altele în C, pentru
a permite celor pasionaţi să-şi însuşească cunoştinţele minimale de programare a PC-urilor:
lucrul cu tastatura, accesul direct la memorie, lucrul în modul grafic, etc. Pentru cei ce doresc
să aprofundeze acest subiect sau doresc cît mai multe detalii le recomandăm, pe lîngă citirea
atentă a help-ului Turbo Pascal-ului sau a Turbo C-ului, folosirea utilitarului TechHelp
specializat în descrierea programării PC-urilor.
Ideea care ar defini cel mai bine acest tip de cunoştinţe de programare este conţinută
în cunoscuta expresie : "Secrete mici, efecte mari !".

// Un simplu program muzical

#include
#include
#include
main(){ /* Do do# Re re# Mi Fa fa# sOl sol# La la# Si */
int octava[]={65 , 69 , 73 , 78 , 82 , 87 , 92 , 98 , 104 , 110 , 116 , 123};
int i,j,nr_octava,i_nota,timp=500;
float masura,durata,durata_masura;
char *linia="42$2R2R4M4F2O2L1R2R2S2S4L4O2O2"; //$4D2D4$3S4L2";

do{
masura=(float)(linia[0]-'0')/(linia[1]-'0');durata_masura=0;
for(i=2;linia[i]!='\0';i++){
if (i%2==0){
switch(linia[i]){
case '$' : {nr_octava=1;for(j=linia[++i]-'0';j>0;j--)nr_octava*=2;}
break;
case 'D' : i_nota=0;break;
case 'd' : i_nota=1;break;
case 'R' : i_nota=2;break;
case 'r' : i_nota=3;break;

120

case 'M' : i_nota=4;break;
case 'F' : i_nota=5;break;
case 'f' : i_nota=6;break;
case 'O' : i_nota=7;break;
case 'o' : i_nota=8;break;
case 'L' : i_nota=9;break;
case 'l' : i_nota=10;break;
case 'S' : i_nota=11;break;

}
} else {

if (linia[i]=='6') durata=1/16; else durata=1/(float)(linia[i]-'0');
durata_masura+=durata;
if (durata_masura>masura) { nosound();durata_masura=0;}
sound(nr_octava*octava[i_nota]);
delay(durata*timp);

}

/* else */

}

/* for */

}

/* do */
while (!kbhit());
nosound();
}

Program Citite_Taste;

uses crt;
var c:char;

shift:byte absolute $40:$17; { adresa octetului de stare a tastaturii }

begin
repeat

c:=readkey;
if (shift and $3>0) then
write(' shift ',c,':',Ord(c))
else write(' ',c,':',Ord(c));
until c=#27;
end.

121

// Program C pt. afisarea Tabelului codurilor ASCII;

#include
void main(){
unsigned short c;
for(c=0;c<=255;c++)
switch(c){
case 7 : printf("b%3uł",c);break; // beep
case 8 : printf("B%3uł",c);break; // back space
case 9 : printf("T%3uł",c);break; // tab
case 10 : printf("L%3uł",c);break; // line feed
case 13 : printf("R%3uł",c);break; // return
case 27 : printf("E%3uł",c);break; // escape
default : printf("%c%3uł",c,c); // caractere afisabile
};

}

Program Tenis;

{ Joc demonstrativ al posibilitatilor de folosire a accesului direct
la memoria ecran. Paletele sint actionate de tastele 'A' si 'W', respectiv
'sageata sus' si 'sageata jos'. }
Uses Crt;
Const viteza=1500;
Type Ecran=Record
car:char;
atrib:byte;

End;

Var

scr:array[1..25,1..80] of Ecran absolute $b800:$0; { Adresa de memoriei ecran in mod text }
x,y,x0,y0:byte;
i,d,s:integer;
u:real;
ok:boolean;
tasta:char;

122

yP1:array[1..5]of byte;
yP2:array[1..5]of byte;
uP:array[1..5]of real;

Procedure Paleta1(tip:char);
Begin {generare paleta 1}
for i:=1 to 5 do
scr[yP1[i],76].car:=tip;

end;
Procedure Paleta2(tip:char);
Begin {generare paleta 2}
for i:=1 to 5 do
scr[yP2[i],5].car:=tip;

End;
Procedure Mutapaleta1;
Begin

Paleta1(' ');
if (tasta=#80) and (yP1[i]<24) then {miscarea paletei 1}
for i:=1 to 5 do Inc(yP1[i]);
if (tasta=#72) and (yP1[i]>6) then
for i:=1 to 5 do Dec(yP1[i]);

End;
Procedure Mutapaleta2;
Begin

Paleta2(' '); {miscarea paletei 2}
if (tasta=#122) and (yP2[i]<24) then
for i:=1 to 5 do Inc(yP2[i]);
if (tasta=#119) and (yP2[i]>6) then
for i:=1 to 5 do Dec(yP2[i]);

End;
procedure cantec; {genereaza cantecul final}
begin sound(400);delay(800);
sound(500);delay(800);
sound(600);delay(800);

123

sound(650);delay(800);
sound(600);delay(800);
sound(700);delay(800);
sound(650);delay(1000);

end;
Begin {program principal-generare cadru}

Clrscr;
d:=0;s:=0;
{ writeln('________ ________ _______ ______ ________ ');
write(char(179),' ',char(179),' ',char(179),' ');
writeln(char(179),' ',char(179));
readln;}
clrscr;
For x:=1 to 80 do begin
scr[1,x].car :=#219;
scr[25,x].car:=#219;

end;
For y:=2 to 9 do begin {poarta}
scr[y,1].car :=#219;
scr[y,80].car:=#219;

end;
For y:=17 to 24 do begin
scr[y,1].car :=#219;
scr[y,80].car:=#219;

end;
x0:=40;
y0:=13;
u:=20*PI/180; {initializare miscare minge}
x:=x0;
y:=y0;
for i:=1 to 5 do begin
yP1[i]:=10+i;
yP2[i]:=10+i;
uP[i]:=(i/3*PI-PI)/15; {unghiul de dispersie a paletei}

124

end;
tasta:=' ';
repeat {miscare minge}
if ((u>=0) and (u 3*PI/2) and (u<2*PI)) then inc(x)
else dec(x);
y:=y0+Trunc(Abs(x-x0) * Sin(u)/Cos(u));
if scr[y,x].car<>' ' then begin
if (y=1)or(y=25) then begin {ciocniri}
u:=2*PI-u;x0:=x;
if y=1 then y0:=2 else y0:=24;
end; {-de pereti}
if (x=1)or(x=80) then begin
u:=PI+u;if u>2*Pi then u:=u-2*PI;
y0:=y;
if x=1 then x0:=2 else x0:=79;

end;
if x=76 then begin {-de palete}
for i:=1 to 5 do
if y=yP1[i] then begin
sound(1000);
u:=PI+u+uP[i];
if u>2*Pi then u:=u-2*PI;
x0:=x;y0:=y;

end;
nosound;

end;
if x=5 then begin {-de palete}
for i:=1 to 5 do
if y=yP2[i] then begin
sound(600);
u:=PI+u+uP[i];
if u>2*Pi then u:=u-2*PI;
x0:=x;y0:=y;

end;

125

nosound;

end;

end
else if not (((x=1)or(x=80)) and((y<17)and(y>8))) then
begin {gol}
scr[y,x].car:='0';
i:=1;
ok:=false;
repeat

ok:=keypressed;
inc(i);
until (i=viteza)or ok;
if ok then begin
tasta:=readkey;
if tasta = #0 then tasta:=readkey;
mutapaleta1;
mutapaleta2;

end;
Paleta1(#219);
Paleta2(#219);
scr[y,x].car:=' ';
scr[y,x].car:=' ';

end
else begin

sound(800);
if (x>=80)and(y>9)and(y<17) then d:=d+1;
if (x<=1)and(y>9)and(y<17) then s:=s+1;
textcolor(2);
textbackground(7);
gotoxy(39,2);
write('SCOR');
gotoxy(38,3);
write(' ',d,' : ',s);
if (d=5)or(s=5) then begin

126

gotoxy(35,10);
write(' G A M E O V E R ');
cantec; nosound;
halt;
end;

delay(1500);
paleta1(' ');
paleta2(' ');
x0:=40;
y0:=13;
u:=20*PI/180; {reinitializare miscare minge}
x:=x0;
y:=y0;
for i:=1 to 5 do begin
yP1[i]:=10+i;
yP2[i]:=10+i;
uP[i]:=(i/3*PI-PI)/5;
end;
tasta:=' ';
nosound;

end;
until tasta=#27;

End.

Program Biliard; { demonstrativ pentru folosirea modului grafic }

uses Graph,Crt;
Const nr_obiecte=10;
raza=25;
pasx=3;pasy=2;
viteza=10; { de la 0 la 10 }

var
grDriver,grMode,ErrCode: Integer;
i,xMax,yMax,xtmp,ytmp:word;
x,y:Array[1..nr_obiecte] of word;

127

sensx,sensy:Array[1..nr_obiecte] of shortint;

Procedure Deseneaza(x,y,color:word);
Const bucati=12;
Var x1,y1,unghi,Xasp,Yasp:word;
Begin

SetWriteMode(XORPut);SetColor(color);
GetAspectRatio(Xasp, Yasp);
unghi:=0;
x1:=x+Trunc(raza*cos(unghi*2*PI/bucati));
y1:=y+Trunc(raza*sin(unghi*2*PI/bucati)*Xasp/Yasp);
For unghi:=1 to bucati do begin
xtmp:=x+Trunc(raza*cos(unghi*2*PI/bucati));
ytmp:=y+Trunc(raza*sin(unghi*2*PI/bucati)*Xasp/Yasp);
Line(x1,y1,xtmp,ytmp);Line(x,y,x1,y1);
x1:=xtmp;y1:=ytmp;

end;
End;

begin
grDriver := Detect;
InitGraph(grDriver, grMode,'');
ErrCode := GraphResult;
if ErrCode = grOk then
begin { Do graphics }
xMax:=GetMaxX;yMax:=GetMaxY;
Rectangle(0,0,xMax,yMax);
Randomize;
For i:=1 to nr_obiecte do begin
x[i]:=raza+Random(xMax-2*raza);y[i]:=raza+Random(yMax-2*raza);
sensx[i]:=-1+(i mod 2)*2;sensy[i]:=-sensx[i];
Deseneaza(x[i],y[i],i);

end;
Repeat

128

For i:=1 to nr_obiecte do begin
Deseneaza(x[i],y[i],i);
xtmp:=x[i]+pasx*sensx[i];ytmp:=y[i]+pasy*sensy[i];
If (xtmp>raza) and (xtmp else sensx[i]:=-sensx[i];
If (ytmp>raza) and (ytmp else sensy[i]:=-sensy[i];
Deseneaza(x[i],y[i],i);
Delay(100-10*viteza);

end;
Until KeyPressed;
Readln;
CloseGraph;

end
else

Writeln('Graphics error:', GraphErrorMsg(ErrCode));

end.

// Program C de umplere a ecranului text prin acces direct la memoria ecran

#include
#include
struct scrcar{
unsigned char car,atrib;
} far *ecran;
int lin,col;
int culoare=BLUE,fundal=LIGHTGRAY;
void main(void){
ecran=(struct scrcar far *)MK_FP(0xb800,0);
for(lin=0;lin<25;lin++)
for(col=0;col<80;col++) {
ecran[lin*80+col].car='*';
ecran[lin*80+col].atrib=fundal*16+culoare;

}
getch();
}

129

Program Acces_direct_ecran_grafic320_200;

{ Fiecare jumatate de ecran se genereaza din cealalta jumatate
pe baza proprietatilor automatelor celulare – asemanator ca in jocul Life }
Uses crt;
Const maxl=200-1;
maxc=320-1;
mijl=maxc div 2;
Type Matrice=array[0..maxl,0..maxc] of byte;
var

scr:Matrice absolute $A000:0; { adresa memoriei ecran in modul grafic 320x200 }
i,j,k,l,c,x:integer;
ok:char;
BEGIN
asm {initializeaza in mod grafic 320x200x250 NU in 640x400x256}

mov ah,0
mov al,13h
int 10h;

end;
randomize;x:=random(maxc);
for k:=1 to 2 do
for i:=0 to maxl do
for j:=0 to mijl do
scr[i,j+k*mijl]:=random(maxc) ;

k:=0;
repeat
repeat

for i:=0 to maxl do
for j:=0 to mijl do begin
l:=i;c:=j+k*mijl;
if (scr[(l-1)mod maxl,c] (scr[l,(c-1)mod mijl] scr[i,j+((k+1)mod 2)*mijl]:=(scr[(l-1)mod maxl,c]+scr[l,(c-1)mod mijl]+ x)div 3-1
else if (scr[l,(c+1)mod mijl]>scr[l,c])and
(scr[(l+1)mod maxl,c]>scr[l,c]) then

130

scr[i,j+((k+1)mod 2)*mijl]:=(scr[(l+1)mod maxl,c]+scr[l,(c+1)mod mijl]+ x) div 3+1
else scr[i,j+((k+1)mod 2)*mijl]:=scr[l,c]+1;

end;
k:=(k+1) mod 2;
until keypressed;
ok:=readkey;x:=random(maxc);
if ok<>#27 then ok:=readkey;
until ok=#27;
{readln;}
asm {inchide modul grafic}
mov ax,0
int 10h

end;
END.

Program Mouse; { Gestionarea mouse-ului prin apelul intreruperii de sistem $33 }

uses Crt,Graph,Dos;
var

grDriver,grMode,ErrCode : Integer;
mfunc,buton,mx,my,xf,yf,x,y:word;
xi,yi:integer;
s1,s2,s3:string[5];
P : pointer;
Size : Word;

{ Intr $33, nr.fctiei dorite in AX:
00 mouse reset
01 cuplare cursor mouse (vizibil)
02 decuplare cursor mouse(ascuns)
03 determ.unei apasari pe tasta si semnalare pozitie
04 pozitionarea cursorului de mouse
05 inform.suplim.despre apasarea tastelor
06 inreg.tastelor de mouse eliberate
07 stabilire domeniu orizontal(minim si maxim)

131

08 - || - - || -vertical - || - - || -
09 selectare cursor grafic
10 selectare cursor text
13/14 emulare creion optic conectat/deconectat
15 stabilire sensibilitate mouse
29 fixarea paginii ecran in care mouse-ul e vizibil
30 afisarea - || - - || - - || - - || -

procedure MouseReg;
var reg:registers;
begin

reg.ax:=mfunc;reg.bx:=buton;reg.cx:=mx;reg.dx:=my;
intr($33,reg);
mfunc:=reg.ax;buton:=reg.bx;mx:=reg.cx;my:=reg.dx;

end;
}
procedure MouseAsm;ASSEMBLER;
ASM
MOV AX,mfunc
MOV BX,buton
MOV CX,mx
MOV DX,my
INT $33
MOV mfunc,AX
MOV buton,BX
MOV mx,CX
MOV my,DX

end;

Begin

grDriver := Detect;
InitGraph(grDriver,grMode,'');
ErrCode := GraphResult;
if ErrCode = grOk then

132

begin

if mem[memW[0:$cc+2]:memW[0:$cc]]=$cf then
begin

outtext('Mouse-ul nu este instalat!');
readln;closegraph;halt;

end;
mfunc:=0;mouseasm; {initializare}
mfunc:=1;mouseasm; {vizibil}
mfunc:=3;
mouseasm;xi:=mx;yi:=my;
setactivepage(1);
rectangle(xi,yi,mx,my);
Size := ImageSize(xi,yi,mx,my);
GetMem(P, Size); { Get memory from heap }
GetImage(xi,yi,mx,my,P^);
putimage(xi,yi,P^,XORput);
setactivepage(0);
PutImage(100, 100, P^, ORPut);
repeat

mouseasm;
xi:=mx;yi:=my;
while buton=1 do
begin

PutImage(100, 100, P^,XORPut);
mouseasm;
setactivepage(1);
rectangle(xi,yi,mx,my);
Size := ImageSize(xi,yi,mx,my);
GetMem(P, Size); { Get memory from heap }
GetImage(xi,yi,mx,my,P^);
putimage(xi,yi,P^,XORput);
setactivepage(0);
PutImage(100, 100, P^, ORPut);

end;

133

until keypressed;
mfunc:=2;mouseasm; { decuplare mouse }
CloseGraph;

end
else

WriteLn('Graphics error:',GraphErrorMsg(ErrCode));

end.

// Program C de generare a efectului grafic-plasma-prin utilizarea unor functii ale
modului grafic

#include
#include
#include
#include
#include
#include
int MX,MY;
int p1,p2,p3,p4,r1,r2,r3,r4;
void plasma(int x1,int x2,int y1,int y2){
if(x2-x1<2) return;
p1=getpixel(x1,y1);
p2=getpixel(x2,y1);
p3=getpixel(x2,y2);
p4=getpixel(x1,y2);
r1=random(4);
r2=random(4);
r3=random(4);
r4=random(4);
if (getpixel(x1+(x2-x1)/2,y1)==0) putpixel(x1+(x2-x1)/2,y1,(p1+p2)/2+r1);
if (getpixel(x2,y1+(y2-y1)/2)==0) putpixel(x2,y1+(y2-y1)/2,(p2+p3)/2+r2);
if (getpixel(x1+(x2-x1)/2,y2)==0) putpixel(x1+(x2-x1)/2,y2,(p3+p4)/2+r3);
if (getpixel(x1,y1+(y2-y1)/2)==0) putpixel(x1,y1+(y2-y1)/2,(p4+p1)/2+r4);
putpixel(x1+(x2-x1)/2,y1+(y2-y1)/2,(p1+p2+p3+p4)/4+random(2));
plasma(x1,x1+(x2-x1)/2,y1,y1+(y2-y1)/2);

134

plasma(x1+(x2-x1)/2,x2,y1,y1+(y2-y1)/2);
plasma(x1,x1+(x2-x1)/2,y1+(y2-y1)/2,y2);
plasma(x1+(x2-x1)/2,x2,y1+(y2-y1)/2,y2);

}
int gdriver = VGA, gmode = VGAHI, errorcode,i;
double red=20,green=30,blue=40;
struct palettetype pal;
void main(void){
/* select a driver and mode that supports the use */
/* of the setrgbpalette function. */
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */

}
/* grab a copy of the palette */
getpalette(&pal);

for (i=0; i

setrgbpalette(pal.colors[i], red+i, green+i, blue+i);

randomize();
MX=getmaxx();MY=getmaxy();
putpixel(0,0,MAXCOLORS/2);
putpixel(0,MY,MAXCOLORS/2);
putpixel(MX,0,MAXCOLORS/2);
putpixel(MX,MY,MAXCOLORS/2);
plasma(0,MX,0,MY);
// rotate palette

135

while(!kbhit()){
for(i=0;i

setrgbpalette(pal.colors[i],(int) red+i, (int) green+i, (int) blue+i);
red+=0.5; green+=1; blue+=1.5;

}
closegraph();
}

Program Sarpe;

{ Program de joc demonstrativ: "Sarpele" culegator de numere. El este dirijat
cu ajutorul sagetilor, viteza sa de miscare poate fi modificata corespunzator
in orice moment folosind tastele de la 1 la 9. }
Uses Crt;
Const

sc=#219;
lungmax=95;
maxnext=10;
xlimit=[1,80];
ylimit=[1,25];

Var

sx,sy:array[1..95] of byte;
c:char;
i,primul,ultimul,next,tdelay,idelay:integer;
xnext,ynext:byte;

Begin
clrscr;
randomize;
for i:=1 to 79 do begin gotoxy(i,1);write(sc);gotoxy(i,25);write(sc);end;
for i:=1 to 24 do begin gotoxy(1,i);write(sc);gotoxy(80,i);write(sc);end;
primul:=2;ultimul:=1;
for i:=primul downto ultimul do begin sx[i]:=40;sy[i]:=13;end;
next:=0;idelay:=100;
for i:=primul downto ultimul do begin
gotoxy(sx[i],sy[i]);write(sc);

136

end;
c:=readkey;
while next begin

xnext:=2+random(78);ynext:=2+random(23);
inc(next);gotoxy(xnext,ynext);write(next);
repeat

if keypressed then begin
c:=readkey;tdelay:=idelay;
if c=#0 then c:=readkey;

end
else tdelay:=tdelay*97 div 100;
case c of
'1'..'9':

idelay:=100+100 div (ord(c)-ord('1')+1);

#75: { stinga }
begin

gotoxy(sx[ultimul],sy[ultimul]);write(' ');
if primul=lungmax then begin
sx[1]:=sx[primul]-1;sy[1]:=sy[primul];
primul:=1

end
else begin
inc(primul);
sx[primul]:=sx[primul-1]-1;sy[primul]:=sy[primul-1];

end;
if ultimul=lungmax then ultimul:=1
else inc(ultimul);

end;
#77: { dreapta }
begin

gotoxy(sx[ultimul],sy[ultimul]);write(' ');
if primul=lungmax then begin
sx[1]:=sx[primul]+1;sy[1]:=sy[primul];

137

primul:=1

end
else begin
inc(primul);
sx[primul]:=sx[primul-1]+1;sy[primul]:=sy[primul-1];

end;
if ultimul=lungmax then ultimul:=1
else inc(ultimul);

end;
#72: { sus }
begin

gotoxy(sx[ultimul],sy[ultimul]);write(' ');
if primul=lungmax then begin
sx[1]:=sx[primul];sy[1]:=sy[primul]-1;
primul:=1

end
else begin
inc(primul);
sx[primul]:=sx[primul-1];sy[primul]:=sy[primul-1]-1;

end;
if ultimul=lungmax then ultimul:=1
else inc(ultimul);

end;
#80: { jos }
begin

gotoxy(sx[ultimul],sy[ultimul]);write(' ');
if primul=lungmax then begin
sx[1]:=sx[primul];sy[1]:=sy[primul]+1;
primul:=1

end
else begin
inc(primul);
sx[primul]:=sx[primul-1];sy[primul]:=sy[primul-1]+1;

end;

138

if ultimul=lungmax then ultimul:=1
else inc(ultimul);

end;
end;
if primul > ultimul then
for i:=primul downto ultimul do begin
gotoxy(sx[i],sy[i]);write(sc);
if (sx[primul]=sx[i]) and (sy[primul]=sy[i]) and (i<>primul) then

c:=#27;

end

else
begin

for i:=ultimul to lungmax do begin
gotoxy(sx[i],sy[i]);write(sc);
if (sx[primul]=sx[i]) and (sy[primul]=sy[i]) and (i<>primul) then

c:=#27;

end;
for i:=1 to primul do begin
gotoxy(sx[i],sy[i]);write(sc);
if (sx[primul]=sx[i]) and (sy[primul]=sy[i]) and (i<>primul) then

c:=#27;

end;

end;
if (sx[primul] in xlimit)or(sy[primul] in ylimit) then c:=#27;
delay(tdelay);
until (c=#27) or ((sx[primul]=xnext)and(sy[primul]=ynext));
sound(next*30);
if c=#27 then next:=maxnext
else
if ultimul-next <= 0 then begin
for i:=lungmax+ultimul-next to lungmax do begin
sx[i]:=sx[ultimul];sy[i]:=sy[ultimul];

end;
for i:=1 to ultimul do begin

139

sx[i]:=sx[ultimul];sy[i]:=sy[ultimul];

end;
ultimul:=lungmax+ultimul-next;

end
else begin

for i:=ultimul-next to ultimul do begin
sx[i]:=sx[ultimul];sy[i]:=sy[ultimul];

end;
ultimul:=ultimul-next;

end;
delay(tdelay);
nosound;
end; { next < maxnext}
End.

Program Scan_Taste;

{ Program ce demonstreaza posibilitatea de acces la codurile de scanare
ale tastaturii. Este indicat sa fie lansat in mod DOS si nu de sub Windows. }
Uses Crt,Dos;
Var

tasta:byte;
KbdIntVec:procedure;

{$F+}
Procedure KeyClick; interrupt;
begin

Port[$20]:=$20; { resetarea portului de acces al tastaturii }

end;
Begin

GetIntVec($9,@KbdIntVec); { modificarea intreruperii de tastatura }
SetIntVec($9,Addr(KeyClick)); { cu o procedura proprie "inofensiva" }
tasta:=0;
repeat

repeat until tasta<>Port[$60];
tasta:=Port[$60];

140

gotoxy(20,2);write(tasta:3);
until tasta=129;
SetIntVec($9,@KbdIntVec);

End.

Program Taste_muzicale_V2;

{ Program demonstrativ de folosire muzicala a tastaturii pe post de "orga".
Pentru o mai buna intelegere este utila consultarea programului scantast.pas }
Uses Crt,Dos;
Const

Nota_Do:array[1..4] of integer=(33,66,132,264);
Raport:array[1..10]of real=(24/24,27/24,30/24,32/24,36/24,40/24,45/24,
48/24,51/24,54/24);
Nota:array[1..10]of string[3]=('Do','Re','Mi','Fa','Sol','La','Si',
'Do','Re','Mi');
CodT:array[1..4]of byte=(44,30,16,2);
Type Pixel=Record
atrib:byte;
car:char;

end;

Var

tasta:byte;i:integer;
KbdIntVec:procedure;
ecran:array[1..25,1..80]of Pixel absolute $b800:0000;

{$F+}
Procedure KeyClick; interrupt;
begin

Port[$20]:=$20;

end;
Begin
ClrScr;
GetIntVec($9,@KbdIntVec);
SetIntVec($9,Addr(KeyClick));
tasta:=0;

141

repeat

repeat until tasta<>Port[$60];
tasta:=Port[$60];
if (tasta>=CodT[1])and(tasta begin

gotoxy(5*(tasta+1-CodT[1]),24);write(Nota[tasta+1-CodT[1]]);
sound( Trunc( Raport[ tasta+1-CodT[1] ] * Nota_Do[1] ) )

end
else

if (tasta>=CodT[2])and(tasta begin
gotoxy(5*(tasta+1-CodT[2]),22);write(Nota[tasta+1-CodT[2]]);
sound( Trunc( Raport[ tasta+1-CodT[2] ] * Nota_Do[2] ) )
end
else

if (tasta>=CodT[3])and(tasta begin
gotoxy(5*(tasta+1-CodT[3]),20);write(Nota[tasta+1-CodT[3]]);
sound( Trunc( Raport[ tasta+1-CodT[3] ] * Nota_Do[3] ) )
end
else

if (tasta>=CodT[4])and(tasta begin

gotoxy(5*(tasta+1-CodT[4]),18);write(Nota[tasta+1-CodT[4]]);
sound( Trunc( Raport[ tasta+1-CodT[4] ] * Nota_Do[4] ) )

end
else nosound;
until tasta=129;
SetIntVec($9,@KbdIntVec);

End.

142

Program Testare_VESA;

{ Program de testare a posibilitatilor de lucru a placii grafice in
standardul VESA. }
uses dos;
type tmoduri=array[1..256] of word;
var imod,vseg,x,y:word; cbank,c:longint; rg:registers;
ntbanks:longint; opt:char;
vesabuf:record sign:longint; vers:word; oem:pchar;
capab:longint; list:^tmoduri;
reserv:array[1..512] of byte end;
vesamod:record attr:word; wina,winb:byte;
gran,winsiz,sega,segb:word; pagfun:pointer;
bytes,width,height:word;
charw,charh,planes,bits,nbanks,model,sbank,
nrimpg,reservb,rms,rfp,gms,gfs,bms,bfs:byte;
reserv:array[1..512] of byte end;

function hexa(v:word):string;
const s:string[16]='0123456789abcdef';
function hexb(b:byte):string;
begin

hexb:=s[b div 16+1]+s[b mod 16+1];

end;
begin

hexa:=hexb(hi(v))+hexb(lo(v));

end;
procedure setbank(b:longint);
begin

vseg:=$a000;
if b<>cbank then with rg,vesamod do begin
cbank:=b; ax:=$4f05; bx:=0;
dx:=b*64 div gran; intr(16,rg);
end;

end;

143

procedure putpixel(x,y:word; cul:longint);
var l:longint; m,z:word;
begin

with rg,vesamod do case bits of
4: begin

l:=longint(bytes)*y+x div 8;
port[$3ce]:=3; port[$3cf]:=0;
port[$3ce]:=5; port[$3cf]:=2;
port[$3ce]:=8; port[$3cf]:=128 shr (x and 7);
setbank(l shr 16);
z:=mem[vseg:word(l)]; mem[vseg:word(l)]:=cul;
end;
8: begin

l:=longint(bytes)*y+x; setbank(l shr 16);
mem[vseg:word(l)]:=cul;
end;
15,16: begin

l:=longint(bytes)*y+x*2; setbank(l shr 16);
memw[vseg:word(l)]:=cul;
end;
24: begin

l:=longint(bytes)*y+x*3;
z:=word(l); m:=l shr 16; setbank(m);
if z<$fffe then move(cul,mem[vseg:z],3)
else begin

mem[vseg:z]:=lo(cul);
if z=$ffff then setbank(m+1);
mem[vseg:z+1]:=lo(cul shr 8);
if z=$fffe then setbank(m+1);
mem[vseg:z+2]:=cul shr 16;
end;

end;

end;

144

end;

begin

with rg, vesabuf, vesamod do begin
ax:=$4f00; es:=seg(vesabuf); di:=ofs(vesabuf);
sign:=$41534556; intr(16,rg);
if al<>$4f then begin
writeln('Standardul VESA nu e implementat');
exit end;
imod:=1;
while list^[imod]<>$ffff do begin
ax:=3; intr(16,rg); ax:=$4f01; cx:=list^[imod];
es:=seg(vesamod); di:=ofs(vesamod);
intr(16,rg);
if attr and 16<>0 then begin
writeln(oem,' VESA Versiune ',hi(vers),'.',lo(vers));
writeln(hexa(list^[imod]),
' Rezolutie: ',width,' x ',height,
' Culori: ',longint(1) shl bits);
write('Doriti testare (D/N)? '); readln(opt);
end else opt:='N';
if upcase(opt)='D' then begin
ax:=$4f02; bx:=list^[imod];
intr(16,rg); cbank:=-1;
ntbanks:=longint(bytes)*height div gran div 1024;
for x:=0 to ntbanks do begin
setbank(x); mem[$a000:$ffff]:=0;
fillchar(mem[$a000:0],$ffff,0);
end;
case bits of
4,8: c:=15;
15: c:=32767;
16: c:=65535;
24: c:=longint(1) shl 24-1;

145

end;
for x:=0 to width-1 do begin
putpixel(x,0,c); putpixel(x,height-1,c);
end;
for y:=0 to height-1 do begin
putpixel(0,y,c); putpixel(width-1,y,c);
end;
for x:=0 to 191 do for y:=0 to 191 do begin
case bits of

4: c:=(y div 48)*4+x div 48;
8: c:=(y div 12)*4+x div 12;
15,16: c:=(y div 6)*(1 shl rfp)+x div 6;
24: c:=longint(x)*65536+y;
end;
putpixel(x+4,y+4,c);
end;
readln;
end;
inc(imod);
end;
ax:=3; intr(16,rg);
end;

end.

146

Curiozităţi şi trucuri de programare

Pentru o cît mai completă prezentare a programării în C nu puteam evita prezentarea
unor curiozităţi şi ale unor trucuri de programare C. Acelaşi lucru este valabil şi pentru
limbajul Pascal dar este acesta este oarecum "ieşit din modă". Numărul foarte mare de astfel
de "invenţii" a condus la organizarea încă din 1984 a unui concurs internaţional de
programare numit foarte sugestiv The International Obfuscated C Code Contest – IOCCC
adică Concursul internaţional de programare ofuscată C (încîlcită şi confuză). Participanţii la
acest concurs oferă în fiecare an adevărate perle de programare C ce dovedesc, pe lîngă
serioase cunoştinţe de C, aptitudinile extraordinare şi fiabilitatea compilatorului C. Multe din
capodoperele acestui concurs au fost apoi înscripţionate pe tricouri sau pungi, spre deliciul
fanilor programării C.

Această pasiune are totuşi şi o latură serioasă ce poate fi sesizată în programarea sub
platformele (sistemele de operare) gen Unix. În aceste sisteme toate programele circulă nu
numai sub forma de cod executabil ci şi în sursa originală C. Ascunderea unor informaţii
despre programarea sistem de ochii celor "periculos" de curioşi este astfel dificilă. Dar iată că
acest tip de programare "ofuscată" face acest lucru posibil ! Numai cei foarte pasionaţi îşi
"prind urechile" în descifrarea unor astfel de programe intenţionat încîlcite. Altfel spus,
secretul unor astfel de programe se ascunde chiar în rebusul din faţa ochilor cititorului.
Recomandăm acest capitol în special fanilor programării C şi celor foarte pasionaţi.

// Un simplu "Hello world!" dar care arata o surprinzatoare interpretare a
compilatorului C

#include
char a[]="Hello world!";
int i;
void main(void){
for(i=0;a[i]!='\0';i++)
putchar(i[a]);

// !! a[i] <=> *(a+i) <=> *(i+a) <=> i[a] !!

}

147

// Iata unde conduce folosirea tipului de date float:
// c este foarte diferit de w ?!
// Putem spune ca acesta este un bug al C-ului ?

#include
float a=12345679.,b=12345678.,
c=a*a-b*b,
u=a*a,v=b*b,w=u-v;

void main(){
printf("a=%f,b=%f\nc=%f,w=%f\n",a,b,c,w);
}

// Iata si varianta "corecta" in care nu se produce nici o trunchiere:

#include
long double a=12345679.,b=12345678.,
c=a*a-b*b,
u=a*a,v=b*b,w=u-v;

void main(){
printf("a=%Lf,b=%Lf\nc=%Lf,w=%Lf\n",a,b,c,w);
}

// Acest program este capabil sa-si duplice identic la "iesire" codul sursa C fara a
efectua nici o
// citire de nicaieri. Are deci caracteristica unui virus, se auto-replica !

#include
char *s[]={
"#include ",
"char *s[]={",
"void main(void){",
"int i;char *ps;",
"puts(s[0]);puts(s[1]);",
"for(i=0;i<10;i++)",

148

" {putchar(34);for(ps=s[i];*ps;ps++)putchar(*ps);",
" putchar(34);putchar(',');putchar(10);}",
"putchar(34);for(ps=s[10];*ps;ps++)putchar(*ps);putchar(34);putchar(10);",
"putchar('}');putchar(';');putchar(10);",
"for(i=2;i<11;i++)puts(s[i]);putchar('}');"
};
void main(void){
int i;char *ps;
puts(s[0]);puts(s[1]);
for(i=0;i<10;i++)
{putchar(34);for(ps=s[i];*ps;ps++)putchar(*ps);
putchar(34);putchar(',');putchar(10);}
putchar(34);for(ps=s[10];*ps;ps++)putchar(*ps);putchar(34);putchar(10);
putchar('}');putchar(';');putchar(10);
for(i=2;i<11;i++)puts(s[i]);putchar('}');
}

// Program C surpriza (ales dintre cele de la IOCCC)
// Ce face acest program intr-o singura linie ?

int i;main(){for(;i["] {write(j/p+p,i---j,i/i);}

// Alt program C surpriza (ales dintre cele de la IOCCC)
// Ce face acest program intr-o singura linie ?

main(v,c)char**c;{for(v[c++]="Hello, world!\n)";(!!c)[*c]&&(v--||--c&&execlp(*c,*c,c[!!c]
+!!c,!c));**c=!c)write(!!*c,*c,!!**c);}

// Puteti "decripta" acest program C de trei linii ? Executia lui arata clar ce face,
intrebarea este // insa cum face ?!

#define P(X)j=write(1,X,1)
#define C 39

149

int M[5000]={2},*u=M,N[5000],R=22,a[4],l[]={0,-1,C-1,-1},m[]={1,-C,-1,C},*b=N,
*d=N,c,e,f,g,i,j,k,s;main(){for(M[i=C*R-1]=24;f|d>=b;){c=M[g=i];i=e;for(s=f=0;
s<4;s++)if((k=m[s]+g)>=0&&k=16!
=M[k]>=16))a[f++
]=s;if(f){f=M[e=m[s=a[rand()/(1+2147483647/f)]]+g];j=j c|1<b++?b[-1]:e;}P(" ");for(s=C;--s;P("_")
)P(" ");for(;P("\n"),R--;P("|"))for(e=C;e--;P("_ "+(*u++/8)%2))P("| "+(*u/4)%2
);}

150

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->