Lot ot code including non-satisfying implementation of chess960 start position

pull/1/merge
Thibault Duplessis 2012-05-15 21:59:38 +02:00
parent 141c29dc17
commit ba38cee499
16 changed files with 288 additions and 200 deletions

View File

@ -1,8 +1,7 @@
package lila
import game._
import user._
import game.GameRepo
import game.{ GameRepo, DbGame }
import chess.{ Color, White, Black }
import round.{ IsConnectedOnGame, GetGameVersion, RoomRepo, Progress, Event }
import analyse.GameInfo

View File

@ -52,7 +52,8 @@ object LangList {
"fj" -> "vosa Vakaviti",
"fi" -> "suomi, suomen kieli",
"fr" -> "français",
"frp" -> "arpitan",
"fp" -> "arpitan",
//"frp" -> "arpitan",
"ff" -> "Fulfulde, Pulaar, Pular",
"gl" -> "Galego",
"ka" -> "ქართულ",

View File

@ -7,7 +7,8 @@ import play.api.data._
import play.api.data.Forms._
import scalaz.effects._
final class FormFactory(userConfigRepo: UserConfigRepo) {
final class FormFactory(
configRepo: UserConfigRepo) {
def aiFilled(implicit ctx: Context): IO[Form[AiConfig]] =
aiConfig map ai.fill
@ -21,7 +22,7 @@ final class FormFactory(userConfigRepo: UserConfigRepo) {
)
def aiConfig(implicit ctx: Context): IO[AiConfig] = ctx.me.fold(
user userConfigRepo.config(user) map (_.ai),
user configRepo.config(user) map (_.ai),
io(AiConfig.default)
)
}

View File

@ -6,11 +6,11 @@ import http.Context
import scalaz.effects._
final class Processor(
userConfigRepo: UserConfigRepo) {
configRepo: UserConfigRepo) {
def ai(config: AiConfig)(implicit ctx: Context): IO[Unit] = for {
_ ctx.me.fold(
user userConfigRepo.update(user, ((c: UserConfig) c withAi config)),
user configRepo.update(user, ((c: UserConfig) c withAi config)),
io()
)
color = config.color.resolve

View File

@ -13,5 +13,9 @@ final class SetupEnv(
lazy val configRepo = new UserConfigRepo(mongodb(MongoCollectionConfig))
lazy val formFactory = new FormFactory(configRepo)
lazy val formFactory = new FormFactory(
configRepo = configRepo)
lazy val processor = new Processor(
configRepo = configRepo)
}

View File

@ -1,12 +1,14 @@
@(form: Form[lila.setup.AiConfig])(implicit ctx: Context)
@(form: Form[lila.setup.AiConfig])(implicit ctx: Context)
@fields = {
<div class="variants buttons">
@helper.inputRadioGroup(form("variant"), lila.setup.AiConfig.variantChoices)
@setup.radios(form("variant"), lila.setup.AiConfig.variantChoices)
</div>
@trans.level()
<div class="level buttons">
@helper.inputRadioGroup(form("level"), lila.setup.AiConfig.levelChoices)
<div id="config_level">
@setup.radios(form("level"), lila.setup.AiConfig.levelChoices)
</div>
</div>
}

View File

@ -0,0 +1,6 @@
@(field: play.api.data.Field, options: Seq[(String,String)])
@options.map { v =>
<input type="radio" id="@(field.id)_@v._1" name="@field.name" value="@v._1" @(if(field.value == Some(v._1)) "checked" else "")>
<label class="required" for="@(field.id)_@v._1">@v._2</label>
}

View File

@ -1,4 +1,4 @@
<div id="connection_lost" class="lichess_overboard">
Reconnecting
<img width="220" height="33" src="@routes.Assets.at("images/hloader.gif")" />
<img width="220" height="33" alt="Loading" src="@routes.Assets.at("images/hloader.gif")" />
</div>

View File

@ -54,7 +54,7 @@ fr_file = lichess_trans_dir + '/messages.fr.yml'
lines = File.open(fr_file).readlines.map { |l|
parts = l.split('":').each { |p| p.strip.gsub('"', '') }
key = keyify(parts[0])
val = format(parts[1])
val = format(parts[0])
key + '=' + val
}
text = lines.join("\n")

View File

@ -137,25 +137,7 @@ object Board {
def apply(pieces: (Pos, Piece)*): Board = Board(pieces toMap, History())
def apply(): Board = standard
lazy val standard: Board = {
val lineUp = IndexedSeq(Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook)
val pairs = for (y Seq(1, 2, 7, 8); x 1 to 8) yield {
posAt(x, y) map { pos
(pos, y match {
case 1 White - lineUp(x - 1)
case 2 White.pawn
case 7 Black.pawn
case 8 Black - lineUp(x - 1)
})
}
}
Board(pairs.flatten toMap, History())
}
def apply(): Board = Board(pieces = Variant.Standard.pieces)
def empty = new Board(Map.empty, History())
}

View File

@ -0,0 +1,10 @@
package lila.chess
import Variant._
object Setup {
def apply(variant: Variant): Game = Game(
board = Board(pieces = variant.pieces)
)
}

View File

@ -1,5 +1,10 @@
package lila.chess
import scala.util.Random
import scalaz.{ States }
import Pos.posAt
sealed abstract class Variant(val id: Int) {
lazy val name = toString.toLowerCase
@ -7,12 +12,62 @@ sealed abstract class Variant(val id: Int) {
def standard = this == Variant.Standard
def exotic = !standard
def pieces: Map[Pos, Piece]
}
object Variant {
case object Standard extends Variant(1)
case object Chess960 extends Variant(2)
private def symmetricRank(rank: IndexedSeq[Role]): Map[Pos, Piece] =
(for (y Seq(1, 2, 7, 8); x 1 to 8) yield {
posAt(x, y) map { pos
(pos, y match {
case 1 White - rank(x - 1)
case 2 White.pawn
case 7 Black.pawn
case 8 Black - rank(x - 1)
})
}
}).flatten.toMap
case object Standard extends Variant(1) {
val pieces = symmetricRank(
IndexedSeq(Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook)
)
}
case object Chess960 extends Variant(2) with States {
def pieces = symmetricRank {
val size = 8
type Rank = IndexedSeq[Option[Role]]
def ?(max: Int) = Random nextInt max
def empty(rank: Rank, skip: Int): Option[Int] = {
1 to size find (x (rank take x count (_.isEmpty)) == skip + 1)
} map (_ - 1)
def update(rank: Rank, role: Role)(x: Int): Rank =
rank.updated(x, role.some)
def place(rank: Rank, role: Role, x: Int): Option[Rank] =
empty(rank, x) map update(rank, role)
val bishops: Rank =
IndexedSeq.fill(8)(none[Role])
.updated(2 * ?(4), Bishop.some) // place first bishop
.updated(2 * ?(4) + 1, Bishop.some) // place second bishop
val rank = for {
a1 bishops.some
a2 place(a1, Queen, ?(6))
a3 place(a2, Knight, ?(5))
a4 place(a3, Knight, ?(4))
a5 place(a4, Rook, 0)
a6 place(a5, King, 0)
a7 place(a6, Rook, 0)
} yield a7
rank.err("WTF").flatten
}
}
val all = List(Standard, Chess960)

View File

@ -0,0 +1,23 @@
package lila.chess
import Pos._
import Variant._
class VariantTest extends ChessTest {
val board = Board()
"standard" should {
"position pieces correctly" in {
Standard.pieces must havePairs(A1 -> (White - Rook), B1 -> (White - Knight), C1 -> (White - Bishop), D1 -> (White - Queen), E1 -> (White - King), F1 -> (White - Bishop), G1 -> (White - Knight), H1 -> (White - Rook), A2 -> (White - Pawn), B2 -> (White - Pawn), C2 -> (White - Pawn), D2 -> (White - Pawn), E2 -> (White - Pawn), F2 -> (White - Pawn), G2 -> (White - Pawn), H2 -> (White - Pawn), A7 -> (Black - Pawn), B7 -> (Black - Pawn), C7 -> (Black - Pawn), D7 -> (Black - Pawn), E7 -> (Black - Pawn), F7 -> (Black - Pawn), G7 -> (Black - Pawn), H7 -> (Black - Pawn), A8 -> (Black - Rook), B8 -> (Black - Knight), C8 -> (Black - Bishop), D8 -> (Black - Queen), E8 -> (Black - King), F8 -> (Black - Bishop), G8 -> (Black - Knight), H8 -> (Black - Rook))
}
}
"chess960" should {
"position pieces correctly" in {
Chess960.pieces must havePair(A2 -> (White - Pawn))
}
}
}

View File

@ -1,139 +1,139 @@
playWithAFriend=Jouer avec un ami
inviteAFriendToPlayWithYou=Inviter un ami à jouer avec vous
playWithTheMachine=Jouer avec l'ordinateur
challengeTheArtificialIntelligence=Défier l'intelligence artificielle
toInviteSomeoneToPlayGiveThisUrl=Pour inviter quelqu'un à jouer, donnez-lui cette url
gameOver=Partie terminée
waitingForOpponent=En attente de l'adversaire
waiting=En attente
yourTurn=A votre tour
aiNameLevelAiLevel=%s niveau %s
level=Niveau
toggleTheChat=Activer/Désactiver la discussion
toggleSound=Activer/Désactiver le son
chat=Discussion
giveUp=Admettre la défaite
resign=Abandonner
checkmate=Echec et mat
stalemate=Pat
white=Blanc
black=Noir
createAGame=Créer une partie
random=Aléatoire
noGameAvailableRightNowCreateOne=Aucune partie disponible, créez-en une!
whiteIsVictorious=Blanc est victorieux
blackIsVictorious=Noir est victorieux
playANewGame=Jouer une nouvelle partie
rematch=Revanche
playWithTheSameOpponentAgain=Jouer à nouveau avec le même adversaire
newOpponent=Nouvel adversaire
playWithAnotherOpponent=Jouer avec un autre adversaire
yourOpponentWantsToPlayANewGameWithYou=Votre adversaire souhaite jouer une nouvelle partie avec vous
joinTheGame=Rejoindre la partie
youAreViewingThisGameAsASpectator=Vous voyez cette partie en tant que spectateur
whitePlays=Blanc joue
blackPlays=Noir joue
theOtherPlayerHasLeftTheGameYouCanForceResignationOrWaitForHim=L'autre joueur a quitté la partie. Vous pouvez forcer l'abandon, ou attendre qu'il revienne.
makeYourOpponentResign=Forcer l'abandon de l'adversaire déconnecté
forceResignation=Forcer l'abandon
talkInChat=Parler à l'autre joueur
theFirstPersonToComeOnThisUrlWillPlayWithYou=La première personne à ouvrir cette page jouera avec vous.
whiteCreatesTheGame=Blanc crée la partie
blackCreatesTheGame=Noir crée la partie
whiteJoinsTheGame=Blanc rejoint la partie
blackJoinsTheGame=Noir rejoint la partie
whiteResigned=Blanc abandonne
blackResigned=Noir abandonne
whiteLeftTheGame=Blanc quitte la partie
blackLeftTheGame=Noir quitte la partie
playWithAFriend=Play with a friend
inviteAFriendToPlayWithYou=Invite a friend to play with you
playWithTheMachine=Play with the machine
challengeTheArtificialIntelligence=Challenge the artificial intelligence
toInviteSomeoneToPlayGiveThisUrl=To invite someone to play, give this url
gameOver=Game Over
waitingForOpponent=Waiting for opponent
waiting=Waiting
yourTurn=Your turn
aiNameLevelAiLevel=%s level %s
level=Level
toggleTheChat=Toggle the chat
toggleSound=Toggle sound
chat=Chat
giveUp=Give up
resign=Resign
checkmate=Checkmate
stalemate=Stalemate
white=White
black=Black
createAGame=Create a game
random=Random
noGameAvailableRightNowCreateOne=No game available right now, create one!
whiteIsVictorious=White is victorious
blackIsVictorious=Black is victorious
playANewGame=Play a new game
rematch=Rematch
playWithTheSameOpponentAgain=Play with the same opponent again
newOpponent=New opponent
playWithAnotherOpponent=Play with another opponent
yourOpponentWantsToPlayANewGameWithYou=Your opponent wants to play a new game with you
joinTheGame=Join the game
youAreViewingThisGameAsASpectator=You are viewing this game as a spectator
whitePlays=White plays
blackPlays=Black plays
theOtherPlayerHasLeftTheGameYouCanForceResignationOrWaitForHim=The other player has left the game. You can force resignation, or wait for him.
makeYourOpponentResign=Make your opponent resign
forceResignation=Force resignation
talkInChat=Talk in chat
theFirstPersonToComeOnThisUrlWillPlayWithYou=The first person to come on this url will play with you.
whiteCreatesTheGame=White creates the game
blackCreatesTheGame=Black creates the game
whiteJoinsTheGame=White joins the game
blackJoinsTheGame=Black joins the game
whiteResigned=White resigned
blackResigned=Black resigned
whiteLeftTheGame=White left the game
blackLeftTheGame=Black left the game
contact=Contact
thereIsNothingToSeeHereIfYouThinkItsABugYouCouldSendAnEmailToEmail=Il n'y a rien à voir ici. Si vous pensez qu'il s'agit d'un bug, vous pouvez envoyer un courriel à %s
shareThisUrlToLetSpectatorsSeeTheGame=Partagez cette url pour laisser des spectateurs voir la partie
replayAndAnalyse=Revoir et analyser
viewGameStats=Voir les statistiques de la partie
flipBoard=Retourner l'échiquier
threefoldRepetition=Triple répétition
claimADraw=Déclarer la partie nulle
offerDraw=Proposer le nul
draw=Partie nulle
nbConnectedPlayers=%s joueurs connectés
talkAboutChessAndDiscussLichessFeaturesInTheForum=Parler d'échecs et discuter les fonctionalités de lichess dans le forum
seeTheGamesBeingPlayedInRealTime=Voir les parties jouées en temps réel
gamesBeingPlayedRightNow=Parties jouées en ce moment
viewAllNbGames=Voir les %s parties
viewNbCheckmates=Voir les %s mats
viewInFullSize=Agrandir
logOut=Déconnexion
signIn=Connexion
signUp=Inscription
people=Membres
games=Parties
thereIsNothingToSeeHereIfYouThinkItsABugYouCouldSendAnEmailToEmail=There is nothing to see here. If you think it's a bug, you could send an email to %s
shareThisUrlToLetSpectatorsSeeTheGame=Share this url to let spectators see the game
replayAndAnalyse=Replay and analyse
viewGameStats=View game stats
flipBoard=Flip board
threefoldRepetition=Threefold repetition
claimADraw=Claim a draw
offerDraw=Offer draw
draw=Draw
nbConnectedPlayers=%s connected players
talkAboutChessAndDiscussLichessFeaturesInTheForum=Talk about chess and discuss lichess features in the forum
seeTheGamesBeingPlayedInRealTime=See the games being played in real time
gamesBeingPlayedRightNow=Games being played right now
viewAllNbGames=View all %s games
viewNbCheckmates=View %s checkmates
viewInFullSize=View in full size
logOut=Log out
signIn=Sign in
signUp=Sign up
people=People
games=Games
forum=Forum
chessPlayers=Joueurs d'échecs
first=Premier
previous=Précédent
next=Suivant
last=Dernier
minutesPerSide=Minutes par joueur
variant=Variante
timeControl=Contrôle du temps
start=Démarrer
username=Pseudo
password=Mot de passe
haveAnAccount=Déjà inscrit ?
allYouNeedIsAUsernameAndAPassword=Vous n'avez besoin que d'un pseudo et d'un mot de passe
learnMoreAboutLichess=En savoir plus sur Lichess
rank=Classement
gamesPlayed=Parties jouées
declineInvitation=Décliner l'invitation
cancel=Annuler
timeOut=Temps écoulé
drawOfferSent=Proposition de nul envoyée
drawOfferDeclined=Proposition de nul refusée
drawOfferAccepted=Proposition de nul acceptée
drawOfferCanceled=Proposition de nul annulée
yourOpponentOffersADraw=Votre adversaire propose le nul
accept=Accepter
decline=Refuser
playingRightNow=Partie en cours
abortGame=Annuler la partie
gameAborted=Partie annulée
chessPlayers=Chess players
first=First
previous=Previous
next=Next
last=Last
minutesPerSide=Minutes per side
variant=Variant
timeControl=Time control
start=Start
username=Username
password=Password
haveAnAccount=Have an account?
allYouNeedIsAUsernameAndAPassword=All you need is a username and a password.
learnMoreAboutLichess=Learn more about Lichess
rank=Rank
gamesPlayed=Games played
declineInvitation=Decline invitation
cancel=Cancel
timeOut=Time out
drawOfferSent=Draw offer sent
drawOfferDeclined=Draw offer declined
drawOfferAccepted=Draw offer accepted
drawOfferCanceled=Draw offer canceled
yourOpponentOffersADraw=Your opponent offers a draw
accept=Accept
decline=Decline
playingRightNow=Playing right now
abortGame=Abort game
gameAborted=Game aborted
standard=Standard
unlimited=Illimité
unlimited=Unlimited
mode=Mode
casual=Amicale
rated=Classée
thisGameIsRated=Cette partie est classée
rematchOfferSent=Proposition de revanche envoyée
rematchOfferAccepted=Proposition de revanche acceptée
cancelRematchOffer=Annuler la proposition de revanche
play=Jouer
inbox=Boite de réception
chatRoom=Salon de discussion
composeMessage=Écrire un message
sentMessages=Messages envoyés
incrementInSeconds=Incrément en secondes
freeOnlineChess=Jeu d'échecs gratuit en ligne
spectators=Spectateurs :
nbWins=%s victoires
nbLosses=%s défaites
nbDraws=%s nuls
exportGames=Exporter les parties
color=Couleur
eloRange=Fourchette de classement
giveNbSeconds=Donner %s secondes
searchAPlayer=Rechercher un joueur
whoIsOnline=Qui est en ligne
allPlayers=Tous les joueurs
namedPlayers=Joueurs nommés
premoveEnabledClickAnywhereToCancel=Premove activé - Cliquer ailleurs pour annuler
thisPlayerUsesChessComputerAssistance=Ce joueur utilise un programme d'échecs
opening=Ouverture
takeback=Annuler le coup
proposeATakeback=Proposer l'annulation du coup
takebackPropositionSent=Annulation du coup proposée
takebackPropositionDeclined=Annulation du coup refusée
takebackPropositionAccepted=Annulation du coup acceptée
takebackPropositionCanceled=Annulation du coup annulée
yourOpponentProposesATakeback=Votre adversaire propose l'annulation du coup
freeOnlineChessGamePlayChessNowInACleanInterfaceNoRegistrationNoAdsNoPluginRequiredPlayChessWithComputerFriendsOrRandomOpponents=Jeu d'échecs gratuit en ligne. Jouez aux échecs maintenant avec une interface simple. Pas d'inscription, pas de pub, aucun plugin requis. Jouez aux échecs avec l'ordinateur, des amis ou des adversaires aléatoires
casual=Casual
rated=Rated
thisGameIsRated=This game is rated
rematchOfferSent=Rematch offer sent
rematchOfferAccepted=Rematch offer accepted
cancelRematchOffer=Cancel rematch offer
play=Play
inbox=Inbox
chatRoom=Chat room
composeMessage=Compose message
sentMessages=Sent messages
incrementInSeconds=Increment in seconds
freeOnlineChess=Free Online Chess
spectators=Spectators:
nbWins=%s wins
nbLosses=%s losses
nbDraws=%s draws
exportGames=Export games
color=Color
eloRange=Elo range
giveNbSeconds=Give %s seconds
searchAPlayer=Search a player
whoIsOnline=Who is online
allPlayers=All players
namedPlayers=Named players
premoveEnabledClickAnywhereToCancel=Premove enabled - Click anywhere to cancel
thisPlayerUsesChessComputerAssistance=This player uses chess computer assistance
opening=Opening
takeback=Takeback
proposeATakeback=Propose a takeback
takebackPropositionSent=Takeback proposition sent
takebackPropositionDeclined=Takeback proposition declined
takebackPropositionAccepted=Takeback proposition accepted
takebackPropositionCanceled=Takeback proposition canceled
yourOpponentProposesATakeback=Your opponent proposes a takeback
freeOnlineChessGamePlayChessNowInACleanInterfaceNoRegistrationNoAdsNoPluginRequiredPlayChessWithComputerFriendsOrRandomOpponents=Free online Chess game. Play Chess now in a clean interface. No registration, no ads, no plugin required. Play Chess with computer, friends or random opponents.

View File

@ -1,65 +1,68 @@
div.game_config h2, div.game_config button {
font-size: 1.4em;
padding: 0 2em;
font-size: 1.4em;
padding: 0 2em;
}
div.game_config button {
letter-spacing: 1px;
letter-spacing: 1px;
}
div.game_config h2 {
margin-bottom: 1em;
margin-bottom: 1em;
}
div.game_config div.ui-buttonset {
margin-bottom: 1em;
margin-bottom: 1em;
}
div.game_config .ui-button-text {
text-transform: capitalize;
}
div.game_config div.ui-slider {
font-size: 1.3em;
margin: 0 15px;
font-size: 1.3em;
margin: 0 15px;
}
div.game_config .optional_config {
background: #f4f4f4;
margin-bottom: 1em;
padding: 3px 0;
border-top: solid 1px #e4e4e4;
border-bottom: solid 1px #e4e4e4;
background: #f4f4f4;
margin-bottom: 1em;
padding: 3px 0;
border-top: solid 1px #e4e4e4;
border-bottom: solid 1px #e4e4e4;
}
div.game_config .time_choice,
div.game_config .increment_choice,
div.game_config .elo_range_config {
padding-bottom: 1em;
text-align: left;
text-indent: 15px;
padding-bottom: 1em;
text-align: left;
text-indent: 15px;
}
div.game_config .time_choice span {
font-weight: bold;
}
div.game_config .clock_config label {
cursor: pointer;
cursor: pointer;
}
div.game_config button.submit {
margin-top: 0.5em;
margin-top: 0.5em;
}
div.game_config div.color_submits {
margin-top: 1em;
margin-left: 18px;
height: 65px;
margin-top: 1em;
margin-left: 18px;
height: 65px;
}
div.game_config div.color_submits button.submit {
float: left;
width: 80px;
height: 65px;
padding: 5px 14px;
margin: 0 5px;
float: left;
width: 80px;
height: 65px;
padding: 5px 14px;
margin: 0 5px;
}
div.game_config div.color_submits button.submit span {
background: url(../images/sprite_color.png) no-repeat;
width: 50px;
height: 51px;
padding: 0;
background: url(../images/sprite_color.png) no-repeat;
width: 50px;
height: 51px;
padding: 0;
}
div.game_config div.color_submits button.black span {
background-position: 0 -51px;
background-position: 0 -51px;
}
div.game_config div.color_submits button.random span {
background-position: 0 -102px;
background-position: 0 -102px;
}

2
todo
View File

@ -8,3 +8,5 @@ hide logout button
create play2 session module
forms that validate while constructing the object
player timeout depending on game duration
chess captcha is broken sometimes curl localhost:9000/api/captcha/solve/36yabr3t
do not count games vs engine as win/loss