[A83] Re: shuffle code help please


[Prev][Next][Index][Thread]

[A83] Re: shuffle code help please




I read some stuff on this a while ago, and found that one of the most
elegant methods of shuffling a deck of cards was this:
You start with a variable equal to 52, and get a random number from it
(0-51).  You take the card with this number, move the cards on top of it
back one, move it to the top of the deck, decrement the variable to 51, and
do it over.  So the next time you get a random number from 0-50, take that
card out, move the cards on top of it back one spot, move it to the top of
the deck and repeat.  You quit when you decrement your variable and it is
zero =)
This algorithm is guaranteed to be random.
- - Joe
joe@joepnet.com


>
> this isnt the worlds most elegant code but it works, somewhat. I am trying
to
> shuffle 52 cards ranging from 0..51. the method i am trying is takeing 2
> random slots and swapping them, then repeating the process 255 times.
after i
> run this code and check it i am getting repeates in the sequence.
>
> shuffle:
>     ;new idea take two random slots and swap them
>     ld b,255
> again:
>     push bc                   ;save the main loop var
>     ld b,52
>     call irandom             ;get random number 0-51
>     ld (slot1),a
>     ld b,52
>     call irandom             ;another random number 0-51
>     ld (slot2),a
>     ld hl,carddeck      ;start to put slot1 into slot2
>     ld a,(slot2)
>     ld b,0
>     ld c,a
>     add hl,bc                  ;get address of deck+slot number
>     ld a,(slot1)
>     ld (hl),a
>     ld hl,carddeck      ;start to put slot2 into slot1
>     ld a,(slot1)
>     ld b,0
>     ld c,a
>     add hl,bc
>     ld a,(slot2)
>     ld (hl),a
>     pop bc
>     djnz again
>     ret
>
> carddeck:
>     .db 0,1,2,3,4,5,6,7,8,9,10
>     .db 11,12,13,14,15,16,17,18,19,20
>     .db 21,22,23,24,25,26,27,28,29,30
>     .db 31,32,33,34,35,36,37,38,39,40
>     .db 41,42,43,44,45,46,47,48,49,50
>     .db 51
>
> slot1:
>        .db 0
> slot2:
>        .db 0
>
>




Follow-Ups: References: