Pull to refresh

Facemash своими руками

О Facemash.com Вы наверняка могли слышать из фильма «Социальная сеть»: это именно тот проект, который принес славу Марку Цукербергу и сподвиг его начать работу над Facebook. Сейчас мы попытаемся создать свой Facemash. Тег Рекомендую использовать программу Notepad++, лично мне в ней работать очень удобно и приятно.

Итак, создаем «Rate.php»

<?php
 
include('mysql.php');
include('functions.php');
 
if ($_GET['winner'] && $_GET['loser']) {
 
 $result = mysql_query("SELECT * FROM images WHERE image_id = ".$_GET['winner']." ");
 $winner = mysql_fetch_object($result);
 
 $result = mysql_query("SELECT * FROM images WHERE image_id = ".$_GET['loser']." ");
 $loser = mysql_fetch_object($result);
 
 $winner_expected = expected($loser->score, $winner->score);
 $winner_new_score = win($winner->score, $winner_expected);
  //test print "Winner: ".$winner->score." - ".$winner_new_score." - ".$winner_expected."<br>";
 mysql_query("UPDATE images SET score = ".$winner_new_score.", wins = wins+1 WHERE image_id = ".$_GET['winner']);
 
 $loser_expected = expected($winner->score, $loser->score);
 $loser_new_score = loss($loser->score, $loser_expected);
  //test print "Loser: ".$loser->score." - ".$loser_new_score." - ".$loser_expected."<br>";
 mysql_query("UPDATE images SET score = ".$loser_new_score.", losses = losses+1  WHERE image_id = ".$_GET['loser']);
 
 mysql_query("INSERT INTO battles SET winner = ".$_GET['winner'].", loser = ".$_GET['loser']." ");
 
 header('location: /');
 
}
 
?>


Затем прописываем «MySQL.php»

<?php

// Настройки MySQL
$user   = "";
$password = "";
$database = "";
$host   = "";
mysql_connect($host,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
?> 


Теперь «install_images.php»
<?php

include('mysql.php');
if ($handle = opendir('images')) {
 /* This is the correct way to loop over the directory. */
 while (false !== ($file = readdir($handle))) {
  if($file!='.' && $file!='..') {
   $images[] = "('".$file."')";
  }
 }
 closedir($handle);
}
$query = "INSERT INTO images (filename) VALUES ".implode(',', $images)." ";
if (!mysql_query($query)) {
 print mysql_error();
}
else {
 print "finished installing your images!";
}
 
?>


Теперь можно сделать и «index.php»

<?php

include('mysql.php');
include('functions.php');
 
// Get random 2
$query="SELECT * FROM images ORDER BY RAND() LIMIT 0,2";
$result = @mysql_query($query);
while($row = mysql_fetch_object($result)) {
 $images[] = (object) $row;
}
 
// Get the top10
$result = mysql_query("SELECT *, ROUND(score/(1+(losses/wins))) AS performance FROM images ORDER BY ROUND(score/(1+(losses/wins))) DESC LIMIT 0,10");
while($row = mysql_fetch_object($result)) $top_ratings[] = (object) $row;
 
// Close the connection
mysql_close();
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Facemash</title>
<style type="text/css">
body, html {font-family:Arial, Helvetica, sans-serif;width:100%;margin:0;padding:0;text-align:center;}
h1 {background-color:#600;color:#fff;padding:20px 0;margin:0;}
a img {border:0;}
td {font-size:11px;}
.image {background-color:#eee;border:1px solid #ddd;border-bottom:1px solid #bbb;padding:5px;}
</style>
</head>
<body>
 
<h1>FaceMash</h1>
<h2>Кто горячее? Выбирай.</h2>
<center>
<table>
 <tr>
  <td valign="top" class="image"><a href="rate.php?winner=<?=$images[0]->image_id?>&loser=<?=$images[1]->image_id?>"><img src="http://www.xboxmb.com/images/<?=$images[0]->filename?>" /></a></td>
  <td valign="top" class="image"><a href="rate.php?winner=<?=$images[1]->image_id?>&loser=<?=$images[0]->image_id?>"><img src="http://www.xboxmb.com/images/<?=$images[1]->filename?>" /></a></td>
 </tr>
 <tr>
  <td>Won: <?=$images[0]->wins?>, Lost: <?=$images[0]->losses?></td>
  <td>Won: <?=$images[1]->wins?>, Lost: <?=$images[1]->losses?></td>
 </tr>
 <tr>
  <td>Score: <?=$images[0]->score?></td>
  <td>Score: <?=$images[1]->score?></td>
 </tr>
 <tr>
  <td>Expected: <?=round(expected($images[1]->score, $images[0]->score), 4)?></td>
  <td>Expected: <?=round(expected($images[0]->score, $images[1]->score), 4)?></td>
 </tr>
</table>
</center>
<h2>Top Rated</h2>
<center>
<table>
 <tr>
  <? foreach($top_ratings as $key => $image) : ?>
  <td valign="top"><img src="http://www.xboxmb.com/images/<?=$image->filename?>" width="70" /></td>
  <? endforeach ?>
 </tr>
 <? /* Remove this to see the scoring
 <tr>
  <? foreach($top_ratings as $key => $image) : ?>
  <td valign="top">Score: <?=$image->score?></td>
  <? endforeach ?>
 </tr>
 <tr>
  <? foreach($top_ratings as $key => $image) : ?>
  <td valign="top">Performance: <?=$image->performance?></td>
  <? endforeach ?>
 </tr>
 <tr>
  <? foreach($top_ratings as $key => $image) : ?>
  <td valign="top">Won: <?=$image->wins?></td>
  <? endforeach ?>
 </tr>
 <tr>
  <? foreach($top_ratings as $key => $image) : ?>
  <td valign="top">Lost: <?=$image->losses?></td>
  <? endforeach ?>
 </tr>
 */ ?>
</table>
</center>
</body>
</html>


И напоследок пропишем функции: «functions.php»
<? PHP
/ / Вычислить ожидаемый результат%
Ожидается функцию ($ Rb, Ra $) {
 возвращает 1 / (1 + ПР (10, ($ $ Rb-Ra) / 400));
}
/ / Вычислить новую оценку winnner
Функция выигрыша ($ оценка, $ ожидалось, $ K = 24) {
 вернуть $ оценка + $ K * (1 - $ ожидалось);
}
/ / Вычислить новую счетом проиграл
функция потерь ($ оценка, $ ожидалось, $ K = 24) {
 вернуть $ оценка + $ K * (0 - $ ожидалось);
}
>


Заливаем все файлы на хостинг сайта. После этого создаем папку «images», но пока не загружаем в нее фотографии. Залезаем в phpMyAdmin и создаем таблицу:

CREATE TABLE IF NOT EXISTS `battles` (
`battle_id` bigint(20) unsigned NOT NULL auto_increment,
`winner` bigint(20) unsigned NOT NULL,
`loser` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`battle_id`),
KEY `winner` (`winner`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `images` (
`image_id` bigint(20) unsigned NOT NULL auto_increment,
`filename` varchar(255) NOT NULL,
`score` int(10) unsigned NOT NULL default '1500',
`wins` int(10) unsigned NOT NULL default '0',
`losses` int(10) unsigned NOT NULL default '0',
PRIMARY KEY (`image_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;;


Отлично, теперь залезаем в MySQL.php и заполняем поля:

$user = "";
$password = "";
$database = "";
$host = ""


Теперь заливаем фотографии в папку images, и «устанавливаем их». Вот и все. Наш собственный Facemash готов к использованию. Если у вас возникнут вопросы — пишите, постараюсь вам помочь. Спасибо за внимание :)
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.