2013-08-05 2 views
1

루아를 처음 사용하며 빙고 게임을 개발할 계획입니다. 나는 25 개의 격자를 만들었고 무작위로 숫자를 생성했다. 그러나 그리드의 숫자는 반복됩니다. 검색했지만 친절하게 친구를 찾지 못했습니다.루아에서 반복되는 임의의 숫자

--enter code here 
local widget = require "widget" 
local storyboard = require("storyboard") 
local scene = storyboard.newScene() 
local xaxis = {40,80,120,160,200,40,80,120,160,200,40,80,120,160,200,40,80,120,160,200,40,80,120,160,200} 
local yaxis = {40,40,40,40,40,80,80,80,80,80,120,120,120,120,120,160,160,160,160,160,200,200,200,200,200} 
local img = {} 
local i 
local k 
local u={} 
    for i = 1, 25 do 
     img[i] = display.newImageRect("t.png", 39, 39) 
     img[i].x=xaxis[i] 
     img[i].y=yaxis[i] 
     math.randomseed(os.time()) 
     j = math.random(1,75) 
     u[i], u[j] = u[j], u[i] 
     img[i] = display.newText(j,0,0,native.systemFont,20) 
     img[i].x=xaxis[i] 
     img[i].y=yaxis[i] 
    end 

번호는 무작위로 생성되지만 수는 이것은 거의 모든 프로그래밍 언어에서 일반적인 실수이다

답변

3

을 반복한다. 루프에서 무작위를 사용할 때는 항상 루프 외부에서 시간 시드를 지정해야합니다. 반복은 정말 빠르며 항상 매번 숫자 생성과 같은 결과를내는 현재 시간을 다시 할당합니다.

그래서 당신이 할 일은 루프에서 math.randomseed(os.time())을하는 것입니다

math.randomseed(os.time()) 

for i = 1, 25 do 
    img[i] = display.newImageRect("t.png", 39, 39) 
    img[i].x=xaxis[i] 
    img[i].y=yaxis[i] 
    j = math.random(1,75) 
    u[i], u[j] = u[j], u[i] 
    img[i] = display.newText(j,0,0,native.systemFont,20) 
    img[i].x=xaxis[i] 
    img[i].y=yaxis[i] 
end 

Proof.

+0

친절하게 반복되는 숫자가 친구에게 도움이 되더라도 –

+1

@MaheshJayachandran Numbers는 반복 할 것입니다. shuffle 알고리즘을 찾고 있다면 [Fisher-Yates shuffle algorithm] (http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modern_method)의 최신 버전을 살펴보십시오. – Leri