Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Wave Plotter //Pascal Class

A wave plotter component that is able to draw sin, poly and squared lines, I used this in a osciloscope xD

I didn't liked this code, but the draw part (TWaveShape.paint) is looking cool, I used the same "X" coord to draw the 3 kinds of lines :)

I mean:

loop(x){
case waveType of
wtSin: y := lala;
wtPoly: y := lele;
wtSqr: y := lili;
end;
}

unit WavePlotter;

interface

uses
  forms, dialogs, SysUtils, Classes, Controls, Graphics;

const
  PI2 = PI * 2;

type
  TWaveType = ( wtSqr, wtPoly, wtSin );

  TWave = class( TPersistent )
  public
    waveType: TWaveType;
    color: TColor;
    offset: integer;
    frequency, amplitude, volts, interval, gain: extended;

    procedure AssignTo(Dest: TPersistent); override;
  end;

  TWaveShape = class( TGraphicControl )
  protected
    fWaves: TList;
    fBoxSize: integer;
    fLineColor: TColor;

    function getWave(const index: integer): TWave;
    procedure setBoxSize(const Value: integer);

    function getBackgroundColor: TColor;
    procedure setBackgroundColor(const Value: TColor);
    procedure setLineColor(const Value: TColor);

  public
    constructor create( AOwner: TComponent ); override;
    destructor destroy; override;

    procedure clear;
    procedure delete( const index: integer );

    function add: integer;

    property waves[ const index: integer]: TWave read GetWave;

  published
    procedure paint; override;
    property boxSize: integer read fBoxSize write setBoxSize;
    property backgroundColor: TColor read getBackgroundColor write setBackgroundColor;
    property lineColor: TColor read fLineColor write setLineColor;

    //inherited
    //property Canvas;
    property Align;
    property Anchors;
    property Constraints;
    property DragCursor;
    property DragKind;
    property DragMode;
    property Enabled;
    //property Font;
    property ParentColor;
    //property ParentFont;
    property ParentShowHint;
    property PopupMenu;
    property ShowHint;
    property Visible;
    property OnClick;
    property OnContextPopup;
    property OnDblClick;
    property OnDragDrop;
    property OnDragOver;
    property OnEndDock;
    property OnEndDrag;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnStartDock;
    property OnStartDrag;
  end;

implementation

function max( const a, b: integer ): integer;
begin
  if a > b then
    result := a
  else
    result := b;
end;

{ TWaveShape }

function TWaveShape.add: integer;
begin
  result := fWaves.add( TWave.Create );
end;

procedure TWaveShape.clear;
begin
  while fWaves.count > 0 do begin
    TWave( fWaves[0] ).free;
    fWaves.delete( 0 );
  end;
end;

constructor TWaveShape.create(AOwner: TComponent);
begin
  inherited;
  fWaves := TList.create;
  fLineColor := clGray;
  color := clBtnFace;
  fBoxSize := 50;
end;

procedure TWaveShape.delete(const index: integer);
begin
  if ( index > -1 ) and ( index < fWaves.count ) then begin
    TWave( fWaves[index] ).free;
    fWaves.delete( index );
  end;
end;

destructor TWaveShape.destroy;
begin
  fWaves.free;
  inherited;
end;

function TWaveShape.getBackgroundColor: TColor;
begin
  result := color;
end;

function TWaveShape.getWave(const index: integer): TWave;
begin
  result := nil;
  if ( index > -1 ) and ( index < fWaves.count ) then
    result := TWave( fWaves[ index ] );
end;

procedure TWaveShape.paint;
var
  k, x: integer;
  lastX, lastY: array of integer;
  y: extended;
begin
  if not enabled then
    exit;
  canvas.brush.color := color;
  canvas.fillRect( clientRect );

  setLength( lastY, fWaves.count );
  setLength( lastX, fWaves.count );
  for k := 0 to high( lastY ) do begin
    lastY[k] := clientHeight div 2 + waves[k].offset;
    lastX[k] := 0;
  end;

  for x := 0 to max( clientWidth, clientHeight ) do begin
    with canvas do begin
      pen.color := fLineColor;
      pen.width := 1;
      pen.style := psDot;

      if x mod fBoxSize = 0 then begin
        moveTo( 0, x + trunc( frac( clientHeight / 2 / fBoxSize ) * fBoxSize ) );
        lineTo( clientWidth, x + trunc( frac( clientHeight / 2 / fBoxSize ) * fBoxSize ) );

        moveTo( x, 0 );
        lineTo( x, clientHeight );
      end;

      for k := 0 to fWaves.count - 1 do begin
        with waves[k] do begin
          pen.color := color;
          pen.width := 1;
          pen.style := psSolid;

          y := pi*k + PI2 * x * interval / fBoxSize * frequency;

          case waveType of
            wtSin:
              y := sin( y );
            wtPoly: begin
              y := frac( y / PI2 );
              if y <= 0.25 then
                y := y / 0.25
              else if y <= 0.75 then
                y := ( -y + 0.5 ) / 0.25
              else
                y := ( y - 1 ) / 0.25;
            end;
            wtSqr: begin
              if frac( y / PI2 ) <= 0.5 then
                y := 1
              else
                y := -1;
            end;
          end;
          y := ( y * ( fBoxSize / volts ) * amplitude * gain ) + clientHeight / 2 + offset;
          moveTo( lastX[k], lastY[k] );
          lastX[k] := x;
          lastY[k] := trunc( y );
          lineTo( x, lastY[k] );
        end;
      end;
    end;
  end;
end;

procedure TWaveShape.setBackgroundColor(const Value: TColor);
begin
  color := Value;
  Invalidate;
end;

procedure TWaveShape.setBoxSize(const Value: integer);
begin
  fBoxSize := Value;
  invalidate;
end;


procedure TWaveShape.setLineColor(const Value: TColor);
begin
  fLineColor := Value;
  Invalidate;
end;

{ TWave }

procedure TWave.AssignTo(Dest: TPersistent);
begin
  if Dest.ClassType <> TWave then
    inherited;
  with TWave( Dest ) do begin
    waveType := self.waveType;
    color := self.color;
    offset := self.offset;
    frequency := self.frequency;
    amplitude := self.amplitude;
    volts := self.volts;
    interval := self.interval;
    gain := self.gain;
  end;
end;

end.

magic square demo

REBOL [
    Title:  "Magic Square program"
    Author: "Gregg Irwin"
    Comment: {
        Credit to Bob Kurosaka and Martin Gardener for inspiration.
    }
]

get-size: has [result] [
    print "Enter the size of the square's side."
    print ""
    result: to-integer ask "It must be an odd number larger than 1 : "
    if any [(result < 3) (even? result)] [get-size]
    result
]

edge-guard: does [
    if row < 1    [row: row + side]
    if col > side [col: col - side]
    if row > side [row: row - side]
    if col < 1    [col: col + side]
]

print-square: func [square side] [
    print ["Magic Square, Order " side]
    print ["Each row, col, and Diagonal add up to " side * (side ** 2 + 1) / 2]
    print ""
    repeat row side [
        repeat col side [
            prin [pick square/:row col tab]
        ]
        print ""
    ]
    print ""
]


magic-square: func [/size sz [integer!]] [
    side: either size [sz][get-size]
    row: 1
    col: (side + 1) / 2         ;Locate the starting cell
    square: array/initial reduce [side side] 0
    poke square/:row col 1      ;Initialize the first value

    for i 2 to-integer (side ** 2) 1 [
        row: row - 1
        col: col + 1                  ;Northeast move
        edge-guard
        if 0 <> pick square/:row col [
            row: row + 1              ;otherwise retreat
            col: col - 1
            row: row + 1              ;Break move
            edge-guard
        ]
        poke square/:row col i
    ]
    print-square square side
]


;-- 0 based version --

; print-square: func [square side] [
;     print ["Magic Square, Order " side]
;     print ["Each row, col, and Diagonal add up to " side * (side ** 2 + 1) / 2  - side]
;     print ""
;     repeat row side [
;         repeat col side [
;             prin [pick square/:row col tab]
;         ]
;         print ""
;     ]
;     print ""
; ]
; 
; magic-square: func [/size sz [integer!]] [
;     side: either size [sz][get-size]
;     row: 1
;     col: (side + 1) / 2         ;Locate the starting cell
;     square: array/initial reduce [side side] none
;     poke square/:row col 0      ;Initialize the first value
; 
;     repeat i to-integer (side ** 2) - 1 [
;         row: row - 1
;         col: col + 1                  ;Northeast move
;         edge-guard
;         if none <> pick square/:row col [
;             row: row + 1              ;otherwise retreat
;             col: col - 1
;             row: row + 1              ;Break move
;             edge-guard
;         ]
;         poke square/:row col i
;     ]
;     print-square square side
; ]

;-- End 0 based version --

magic-square
;magic-square/size 5

halt

Closest Square Point //JavaScript Function


Given a dot and a square, it returns the nearest dot over the square.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/closest-square-point [v1.0]

closestSquarePoint = function( px, py, x, y, w, h ){
	return { x: px < x ? x : px > x + w ? x + w : px, y: py < y ? y : py > y + h ? y + h : py };
};

15-square game

py_s60 1.1.3 was released a week ago.
I wonder why there's no more people playing with it.
So, I have created a simple game as an example.

I don't know what this game is called. It has 4x4 square box
with 15 pieces (1 piece missing). You need to move all the
pieces into sorting order.

Since the program is so simple, I decided to make the
moving of a piece smoother by moving it bit by bit.
Hope this doesn't make the code to hard to read.

from appuifw import *
from key_codes import *
import e32, random

# run and break-loop type of app
sleep = e32.ao_sleep
running = 1
def set_exit():
global running
running = 0
app.exit_key_handler= set_exit

# canvas and typical colors
c = Canvas()
app.body = c
red, green, blue, gray, white = 0xff0000, 0x00ff00, 0x0000ff, 0x777777, 0xffffff

# randomize number order for pieces
seq = range(1,17)
random.shuffle(seq)
b = [seq[0:4], seq[4:8], seq[8:12], seq[12:16]]

def piece(i, j, n):
if n < 10:
c.text( (12+20*i, 20+20*j), unicode(n))
else:
c.text( (7+20*i, 20+20*j), unicode(n))

def box(i, j, color, fill=None):
c.rectangle( [5+20*i, 5+20*j, 25+20*i, 25+20*j], color, fill)

# draw board pieces
for k in range(16):
j, i = divmod(k, 4)
piece(i, j, b[j][i])

y, x = divmod(seq.index(16), 4)
box(x, y, white, white)
moving = 0 # cursor to lock if animating

# move cursor in dx, dy direction
def move(dx, dy):
global x,y, moving
if moving:
return
moving = 1
if 0 <= x-dx < 4 and 0 <= y-dy < 4:
b[y][x] = b[y-dy][x-dx]
animate(x-dx, y-dy, dx, dy, b[y][x])
x -= dx # the hole move in opposite direction
y -= dy
moving = 0

# moving a piece for x,y to dx, dy direction
def animate(x, y, dx, dy, n):
if n < 10:
px = 12
else:
px = 7
for i in range(5):
c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n))
sleep(0.05)
c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n), white)
c.text( [px+20*(x+dx), 20+20*(y+dy)], unicode(n) )

# bind arrow keys
c.bind(EKeyRightArrow,lambda:move(1, 0))
c.bind(EKeyLeftArrow,lambda:move(-1, 0))
c.bind(EKeyUpArrow,lambda:move(0, -1))
c.bind(EKeyDownArrow,lambda:move(0, 1))

# main loop, just wait
while running:
sleep(0.1)
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS