Jump to content

Module:Sandbox/Bawolff/Quiz/game

From Wikipedia, the free encyclopedia

local p = {}
local quiz = require( 'Module:Sandbox/Bawolff/Quiz' )
local people = mw.ext.data.get( 'EN Wikipedia vital articles birthdays.tab' ).data


function p.makeQuiz(frame)
	-- This randomizes the random number generator. It also decreases cache time of pages.
	math.randomseed( tonumber( mw.getLanguage( "en" ):formatDate( "U" ) ) * 100000 + os.clock() * 100000 )

	local numbQuestions = frame.args.number or frame:getParent().args.number or 10
	local numbChoices = frame.args.choices or frame:getParent().args.choices or 4

	local quizData = { questions = {} }

	for i = 1, numbQuestions do
		local q = { type = "radio", answers = {} }

		local person = people[math.random(#people)]
		local qid = person[3]:gsub( 'http://www.wikidata.org/entity/', '' )

		local entity = mw.wikibase.getEntity( qid )
		if entity and entity.claims and entity.claims.P18 and entity.claims.P18[1] and entity.claims.P18[1].mainsnak.datatype == 'commonsMedia' and entity.claims.P18[1].mainsnak.datavalue.value then
			q.question = 'Who is:<br>[[File:' .. entity.claims.P18[1].mainsnak.datavalue.value .. '|150x150px]]'
			local ans = math.random( 4 )

			--There is a gender bias in the vital article list. Try to bias the wrong choices to the same gender to make it less obvious.
			local isWoman = entity and entity.claims and entity.claims.P21 and entity.claims.P21[1].mainsnak and entity.claims.P21[1].mainsnak.datavalue and entity.claims.P21[1].mainsnak.datavalue.value.id == 'Q6581072' and true or false
			for j = 1, numbChoices do
				if j == ans then
					local name = (entity.sitelinks and entity.sitelinks.enwiki) and entity.sitelinks.enwiki.title or person[1]
					q.answers[#q.answers+1] = { text = '[[' .. name .. ']]', correct = "correct", score = 1 }
				else
					local ansPerson = people[math.random(#people)]
					if isWoman then
						for k = 1,5 do
							local possibleEntity = mw.wikibase.getEntity( ansPerson[3]:gsub( 'http://www.wikidata.org/entity/', '' ) )
							if not ( possibleEntity and possibleEntity.claims and possibleEntity.claims.P21 and possibleEntity.claims.P21[1].mainsnak and possibleEntity.claims.P21[1].mainsnak.datavalue and possibleEntity.claims.P21[1].mainsnak.datavalue.value.id == 'Q6581072' ) then
								mw.log( "redrawing choice due to gender mismatch on " .. person[1] .. ' and ' .. ansPerson[1] )
								ansPerson = people[math.random(#people)]
							else
								break
							end
						end
					end
					if person[1] == ansPerson[1] then
						ansPerson = people[math.random(#people)]
					end
					q.answers[#q.answers+1] = { text = '[[' .. (ansPerson[1]) .. ']]', correct = "incorrect", score = 0 }
				end
			end
			quizData.questions[#quizData.questions+1] = q
		else
			mw.log( "Skiping " .. person[1] .. " due to lack of images in wikidata" )
			i = i - 1
		end

	end

	return frame:preprocess( quiz.outputQuiz( quizData ) )
end

return p