"depot M315"

This commit is contained in:
JunkJumper
2020-05-01 22:28:41 +02:00
parent 91f5bce946
commit 16368c9c8b
125 changed files with 4506 additions and 0 deletions

View File

@@ -0,0 +1,147 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.2.3" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
associations="true" dependencies="false" nesting-relationships="true" router="FAN">
<class id="1" language="java" name="forum.Canal" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/Canal.java" binary="false" corner="BOTTOM_RIGHT">
<position height="135" width="120" x="116" y="78"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="forum.CanalDeBreve" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/CanalDeBreve.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="1038" y="140"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="3" language="java" name="forum.Controleur" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/Controleur.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="619" y="346"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="4" language="java" name="forum.Forum" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/Forum.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="785" y="562"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="5" language="java" name="forum.GestionnaireCanal" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/GestionnaireCanal.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="667" y="153"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="6" language="java" name="forum.GestionnaireForum" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/GestionnaireForum.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="479" y="565"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="7" language="java" name="forum.Memoire" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/Memoire.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="1243" y="160"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="8" language="java" name="forum.Message" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/Message.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="148" y="560"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="9" language="java" name="forum.UserConsole" project="Forum_TD1&amp;2"
file="/Forum_TD1&amp;2/src/forum/UserConsole.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="1167" y="485"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<association id="10">
<end type="SOURCE" refId="1" navigable="false">
<attribute id="11" name="message"/>
<multiplicity id="12" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="8" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="13">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="14" name="registreF"/>
<multiplicity id="15" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="6" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="16">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="17" name="ui"/>
<multiplicity id="18" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="9" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="19">
<end type="SOURCE" refId="5" navigable="false">
<attribute id="20" name="canalDeBreve"/>
<multiplicity id="21" minimum="0" maximum="2147483647"/>
</end>
<end type="TARGET" refId="2" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="22">
<end type="SOURCE" refId="5" navigable="false">
<attribute id="23" name="canal"/>
<multiplicity id="24" minimum="0" maximum="2147483647"/>
</end>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="25">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="26" name="registreC"/>
<multiplicity id="27" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="5" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="28">
<end type="SOURCE" refId="6" navigable="false">
<attribute id="29" name="forum"/>
<multiplicity id="30" minimum="0" maximum="2147483647"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@@ -0,0 +1,5 @@
package designPattern.facebookGhost;
public interface Event {
}

View File

@@ -0,0 +1,125 @@
package designPattern.facebookGhost;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
/**
*
* Inspired by
* //https://github.com/roundrop/facebook4j/blob/master/facebook4j-core/src/main/java/facebook4j/api/FriendMethods.java
* pour imaginer une esquisse de rseau tr<74>s tr<74>s simplifi<66>
* @author blay
*
*/
@SuppressWarnings("deprecation")
public class FacebookGhostNetwork extends Observable {
public static final String DEFAULT_LOCATION = "unspecified";
HashMap<String,User> users = new HashMap<> ();
public FacebookGhostNetwork() {
}
public User addUser(String nom, String profile){
return addUser(nom, profile,DEFAULT_LOCATION);
}
public User addUser(String nom, String profile, String location){
User user = new UserImpl(nom, profile,location);
users.put(nom, user);
Event e = new UserEvent(user);
setChanged();
notifyObservers(e);
return user;
}
/**
* Returns a user's friends.
* @param userId the ID of a user
* @return users
* @see <a href="https://developers.facebook.com/docs/reference/api/user/#friends">User#friends - Facebook Developers</a>
*/
ArrayList<User> getFriends(String userId){
return getUser(userId).getFriends();
}
/**
* Returns a user's family members.
* @param userId the ID of a user
* @return users
* @see <a href="https://developers.facebook.com/docs/reference/api/user/#friends">User#friends - Facebook Developers</a>
*/
ArrayList<User> getFamily(String userId){
return getUser(userId).getFamily();
}
/**
* Returns a given user, specified by ID.
* @param userId the ID of the user
* @return user
* remove but not the use of dedicated exception !! @throws FacebookException when Facebook service or network is unavailable
* @see <a href="https://developers.facebook.com/docs/reference/api/user/">User - Facebook Developers</a>
*/
public User getUser(String userId) {
return users.get(userId);
}
/**
* Create a relation between 2 given members of a same family
* @param id1 the ID of the user
* @param id2 the ID of the user
*/
public void addFamilyRelation(String id1, String id2) {
User u1 = users.get(id1);
User u2 = users.get(id2);
addFamilyRelation(u1, u2);
}
public void addFamilyRelation(User u1, User u2) {
u1.addFamily(u2);
u2.addFamily(u1);
Event e = new RelationEvent("family",u1,u2);
setChanged();
notifyObservers(e);
}
/**
* Create a relation between 2 given friends
* @param id1 the ID of the user
* @param id2 the ID of the user
*/
public void addFriendRelation(String id1, String id2) {
User u1 = users.get(id1);
User u2 = users.get(id2);
addFriendRelation(u1, u2);
}
public void addFriendRelation(User u1, User u2) {
u1.addFriend(u2);
u2.addFriend(u1);
Event e = new RelationEvent("Friend",u1,u2);
setChanged();
notifyObservers(e);
}
@Override
public String toString() {
return "FacebookGhostNetwork [ " + users + "]";
}
}

View File

@@ -0,0 +1,6 @@
package designPattern.facebookGhost;
public interface IdNameEntity {
String getId();
String getName();
}

View File

@@ -0,0 +1,25 @@
package designPattern.facebookGhost;
public class IdNameEntityImpl implements IdNameEntity {
private String id;
private String name;
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
public IdNameEntityImpl(String id, String name) {
super();
this.id = id;
this.name = name;
}
}

View File

@@ -0,0 +1,32 @@
package designPattern.facebookGhost;
public class RelationEvent implements Event {
public String getNature() {
return nature;
}
public User getU1() {
return u1;
}
public User getU2() {
return u2;
}
String nature;
User u1;
User u2;
public RelationEvent(String nature, User u1, User u2) {
this.nature = nature;
this.u1 = u1;
this.u2=u2;
}
@Override
public String toString() {
return "RelationEvent [nature=" + nature + ", u1=" + u1 + ", u2=" + u2
+ "]";
}
}

View File

@@ -0,0 +1,104 @@
package designPattern.facebookGhost;
/*import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;*/
import java.util.ArrayList;
/**
* Emprunt<6E> <20> https://github.com/roundrop/facebook4j
* @author Ryuji Yamashita - roundrop at gmail.com
*/
public interface User {
String myProfil();
String getId();
String getName();
/* String getFirstName();
String getMiddleName();
String getLastName();
String getGender();
Locale getLocale();
List<IdNameEntity> getLanguages();
URL getLink();
String getUsername();
String getThirdPartyId();
Boolean isInstalled();
Double getTimezone();
Date getUpdatedTime();
Boolean isVerified();
String getBio();
String getBirthday();
// Cover getCover();
List<User.Education> getEducation();
String getEmail();
*/
IdNameEntity getHometown();
/*
List<String> getInterestedIn();
IdNameEntity getLocation();
String getPolitical();
List<IdNameEntity> getFavoriteAthletes();
List<IdNameEntity> getFavoriteTeams();
// Picture getPicture();
String getQuotes();
String getRelationshipStatus();
String getReligion();
IdNameEntity getSignificantOther();
User.VideoUploadLimits getVideoUploadLimits();
URL getWebsite();
List<User.Work> getWork();
;
interface Education {
IdNameEntity getYear();
String getType();
IdNameEntity getSchool();
IdNameEntity getDegree();
List<IdNameEntity> getConcentration();
List<User.EducationClass> getClasses();
List<IdNameEntity> getWith();
}
interface EducationClass {
List<IdNameEntity> getWith();
String getDescription();
}
interface VideoUploadLimits {
long getLength();
long getSize();
}
interface Work {
IdNameEntity getEmployer();
IdNameEntity getLocation();
IdNameEntity getPosition();
String getStartDate();
String getEndDate();
}*/
User.AgeRange getAgeRange();
interface AgeRange {
// one value could be null (13-17 / 18-20 / 21 - null)
Integer getMin();
Integer getMax();
int getAge();
}
ArrayList<User> getFriends();
void addFriend(User friend);
void addFamily(User familyMember);
ArrayList <User>getFamily();
void setLocation(String name);
//String BIRTHDAY_DATE_FORMAT = "MM/dd/yyyy";
}

View File

@@ -0,0 +1,11 @@
package designPattern.facebookGhost;
public class UserEvent implements Event {
User user;
public UserEvent(User user) {
this.user = user;
}
}

View File

@@ -0,0 +1,105 @@
package designPattern.facebookGhost;
import java.util.ArrayList;
public class UserImpl implements User {
private String id;
private String myProfile;
private User.AgeRange range;
private IdNameEntity homeTown;
class AgeRangeImpl implements User.AgeRange{
int age = 20;
public Integer getMin() {
return 0;
}
public Integer getMax() {
return 120;
}
public int getAge() {
return age;
}
}
public UserImpl(String id, String profile, String phomeTown) {
this.id = id;
myProfile = profile;
range = new AgeRangeImpl();
homeTown = new IdNameEntityImpl(phomeTown,phomeTown);
}
public UserImpl(String id, String profile) {
this.id = id;
myProfile = profile;
range = new AgeRangeImpl();
}
public String myProfil() {
return myProfile;
}
public String getId() {
return id;
}
public String getName() {
return id;
}
public AgeRange getAgeRange() {
return range;
}
private ArrayList friends = new ArrayList ();
public void addFriend(User friend) {
friends.add(friend);
}
public ArrayList getFriends() {
return friends;
}
private ArrayList family = new ArrayList ();
public void addFamily(User familyMember) {
family.add(familyMember);
}
public ArrayList getFamily(){
return family;
}
@Override
public String toString() {
return "UserImpl [id=" + id + ", myProfile=" + myProfile + ", range="
+ range +
//",friends=" + friends + ", family=" + family +
"]";
}
@Override
public IdNameEntity getHometown() {
return homeTown;
}
@Override
public void setLocation(String name) {
homeTown = new IdNameEntityImpl(name,name) ;
}
}

View File

@@ -0,0 +1,192 @@
package designPattern.grapheSimple;
import designPattern.grapheX.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* La classe Chemin définit un chemin comme un ensemble d'arcs et maintient pour
* chaque chemin la somme des valeurs des arcs
*
* @author blay
* @param <S>
*
*/
public class Chemin<S extends Identifiable> implements Comparable<Chemin<S>> {
// On pourrait éviter cet attribut en calculant la distance à la demande.
int distance = 0;
List<Arc<S>> paths = new ArrayList<>();
public Chemin() {
paths = new ArrayList<>();
}
public Chemin(List<Arc<S>> arcs) {
paths = arcs;
}
/**
* @return le Sommet terminant le chemin si le chemin est vide il vaut null
*/
public S arrivee() {
if (paths.isEmpty())
return null;
Arc<S> arc = paths.get(paths.size() - 1);
return arc.destination();
}
/**
* @return la somme des valeurs des arcs
*/
public int distance() {
return distance;
}
/**
* @return la liste des arcs qui composent le chemin Attention dangereux une
* copie serait préférable
*/
public List<Arc<S>> getArcs() {
return paths;
}
/**
* Ajoute un arc <20> la fin du chemin
*
* @TODO : verifier que le dernier noeud est bien le premier noeud de l'arc
* ajoute
*/
public boolean add(Arc<S> e) {
distance += e.valeur();
return paths.add(e);
}
public void add(int x, Arc<S> e) {
distance += e.valeur();
paths.add(x, e);
}
public boolean addAll(Collection<Arc<S>> c) {
for (Arc<S> a : c)
distance += a.valeur();
return paths.addAll(c);
}
public void clear() {
distance = 0;
paths.clear();
}
/**
* verifie l'appartenance d'un arc au chemin
*
* @param arc
* @return vrai si l'arc appartient au chemin
*/
public boolean contains(Arc<S> arc) {
return paths.contains(arc);
}
public boolean isEmpty() {
return paths.isEmpty();
}
public boolean remove(Arc<S> o) {
return paths.remove(o);
}
public boolean removeAll(Collection<Arc<S>> c) {
return paths.removeAll(c);
}
public int size() {
return paths.size();
}
@Override
public String toString() {
return "Chemin [dist.=" + distance + ", paths=" + paths + "]";
}
/**
* d<>termine si le sommet appartient au chemin
*
* @param sommet
* @return vrai si le sommet appartient au chemin
*/
public boolean atteint(S sommet) {
for (Arc<S> a : paths)
if (a.destination().equals(sommet))
return true;
return false;
}
/**
* @param depart
* @param arrivee
* @return le sous-chemin reliant depart et arrivee si les deux noeuds
* appartiennent au chemin.
*
*/
public Chemin<S> extraireChemin(S depart, S arrivee) {
boolean debutee = false;
Chemin<S> c = new Chemin<>();
for (Arc<S> a : paths) {
if (debutee) {
c.add(a);
}
if (a.origine().equals(depart)) {
c.add(a);
debutee = true;
}
if (debutee && a.destination().equals(arrivee))
return c;
}
return c;
}
public int compareTo(Chemin<S> c) {
if (this.distance() < c.distance())
return -1;
else if (this.distance() == c.distance())
return 0;
else
return 1;
}
public boolean equals(Object o) {
if (!(o instanceof Chemin))
return false;
Chemin<S> o2 = (Chemin<S>) o;
Chemin<S> c = o2;
if ((distance == c.distance) && (c.paths.size() == this.paths.size())) {
for (Arc<S> a : c.paths) {
if (!paths.contains(a)) {
return false;
}
}
return true;
} else
return false;
}
public List<S> sommets() {
List<S> sommets = new ArrayList<>();
if (! paths.isEmpty()) {
for (Arc<S> arc : paths)
sommets.add(arc.origine());
sommets.add(paths.get(paths.size() - 1).destination());
}
return sommets;
}
}

View File

@@ -0,0 +1,260 @@
package designPattern.grapheSimple;
import designPattern.grapheX.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Cette classe a ete necessaire pour gérer les graphes ayant plusieurs arétes entre deux sommets données
* et ayant des arcs dans les deux sens entre deux sommets.
* Ces fonctionnalités n'étaient pas prises en charge par les classes initiales.
* Elle permet egalement de simplifier la comprehension des codes données.
* @author blay
*
*/
public class GrapheSimple<T extends Sommet> extends Graphe<T> {
HashMap<String,T> mesSommets = new HashMap<>();
HashMap<T,HashMap<T,ArrayList<Arc<T>>>> aretes;
public GrapheSimple() {
aretes = new HashMap<>();
}
public T getSommet(String ident){
return mesSommets.get(ident);
}
@Override
public int taille() {
return mesSommets.size();
}
@Override
public Graphe<T> copie() {
//@TODO
return null;
}
//n'ajoute le sommet que s'il n'est pas deja dans le graphe.
@Override
public void ajouterSommet(T s) {
if (existeSommet(s))
return;
mesSommets.put(s.identifiant(), s);
aretes.put(s,new HashMap<T,ArrayList<Arc<T>>>());
}
@Override
public boolean existeArc(Sommet s, Sommet t) {
return aretes.get(s).containsKey(t);
}
//A revoir avec la nouvelle version
//@todo
private boolean existeSommet(T s) {
return aretes.containsKey(s);
}
public List<Arc<T>> arcs(T s, T t) {
return aretes.get(s).get(t);
}
@Override
public void ajouterArc(T s, T t) {
this.ajouterArc(s,t,0);
}
@Override
public void ajouterArc(Arc<T> arc) {
HashMap<T, ArrayList<Arc<T>>> s = aretes.get(arc.origine());
if (s == null){
ajouterSommet(arc.origine());
s=aretes.get(arc.origine());
}
if (aretes.get(arc.destination()) == null)
ajouterSommet(arc.destination());
if (s.get(arc.destination()) == null)
s.put(arc.destination(), new ArrayList<>());
s.get(arc.destination()).add(arc);
}
@Override
public void ajouterArc(T s, T t, int val) {
Arc<T> a = new Arc<>(s,t,val);
this.ajouterArc(a);
}
//Remarque : gestion horrible des exceptions mais on s'adapte à cause de l'héritage qui nous interdit de lever une exception.
@Override
public int valeurArc(T s, T t) {
if (!existeArc(s,t)) throw new Error("Arc inexistant");
return aretes.get(s).get(t).get(0).valeur();
}
//RETIRE TOUS LES ARCS VERS T
@Override
public void enleverArc(Sommet s, Sommet t) {
if (!existeArc(s,t)) return ;
aretes.get(s).remove(t);
}
@Override
public Collection<T> sommets() {
return mesSommets.values();
}
@Override
public Collection<Arc<T>> voisins(Sommet s) {
ArrayList<Arc<T>> voisins = new ArrayList<>();
HashMap<T, ArrayList<Arc<T>>> arcs = aretes.get(s);
if ( arcs != null )
for (ArrayList<Arc<T>> av : arcs.values())
voisins.addAll(av);
return voisins ;
}
@Override
public String toString() {
return "Sommets=" + mesSommets + ";\n arcs="
+ toStringArretes(aretes) + "]";
}
private String toStringArretes(
HashMap<T, HashMap<T, ArrayList<Arc<T>>>> aretes2) {
StringBuilder bld = new StringBuilder();
for ( HashMap<T, ArrayList<Arc<T>>> x : aretes2.values()){
for ( ArrayList<Arc<T>> edges : x.values())
for (Arc<T> a : edges)
bld.append( "\t").append(a).append("\n" );
}
return bld.toString();
}
/**
* @param origine
* @return une liste de chemin
* Cette m<>thode renvoie les chemins les plus longs possibles <20> partir du point d'orgine
*/
public List<Chemin<T>> chemins(T origine){
HashMap<T,ArrayList<Arc<T>>> dejaVu = new HashMap<>();
return chemins(origine,dejaVu);
}
/**
* @param origine
* @param destination
* @return une liste de chemins entre deux Ts
* Cette m<>thode renvoie tous les chemins entre deux Sommets donnes
*/
//Pbme avec la comparaison des chemins... qui considere comme <20>gal deux objets diff<66>rents... cela doit venir de l'h<>ritage...
public List<Chemin<T>> chemins(T origine, T destination){
List<Chemin<T>> chemins = chemins(origine);
List<Chemin<T>> cheminsEntreDeuxSommets = new ArrayList<> ();
for(Chemin<T> c : chemins) {
if (c.atteint(destination)){
Chemin<T> raccourcis = c.extraireChemin(origine, destination);
if (! cheminsEntreDeuxSommets.contains(raccourcis)) {
cheminsEntreDeuxSommets.add(raccourcis);
}
}
}
return cheminsEntreDeuxSommets;
}
private List<Chemin<T>> chemins(T origine, HashMap<T,ArrayList<Arc<T>>> dejaVu){
List<Chemin<T>> chemins = new ArrayList<>();
if (dejaVu.containsKey(origine)){
chemins.add(new Chemin<>(dejaVu.get(origine)));
return chemins;
}
dejaVu.put(origine, new ArrayList<Arc<T>>());
Collection<Arc<T>> voisins = voisins(origine);
HashMap<T,ArrayList<Arc<T>>> dejavVuLocal ;
for (Arc<T> a : voisins) {
T destination = a.destination();
dejavVuLocal= new HashMap<>(dejaVu);
if (nouvelleDestinationOuNouvelArcSansRetour(origine,dejavVuLocal,destination,a)) {
dejavVuLocal.get(origine).add(a);
List<Chemin<T>> cheminsLocaux = chemins(destination,dejavVuLocal);
if (cheminsLocaux.isEmpty()) {
Chemin<T> chemin = new Chemin<>();
chemin.add(a);
chemins.add(chemin);
}
else {
for (Chemin<T> c : cheminsLocaux) {
c.add(0,a);
chemins.add(c);
}
}
}
}
return chemins;
}
//todo : tenir compte de Origine
private boolean nouvelleDestinationOuNouvelArcSansRetour(
T origine, HashMap<T, ArrayList<Arc<T>>> dejaVu, T destination,
Arc<T> a) {
if (! dejaVu.containsKey(destination) )
return true;
return ( (! dejaVu.get(destination).contains(a)) && (! dejaVu.containsKey(a.destination()) ) );
}
public Chemin<T> cheminLePlusCourt(T origine, T destination){
List<Chemin<T>> chemins = this.chemins(origine, destination);
Chemin<T> cheminLePlusCourt = null;
int distanceLaPlusCourte = Integer.MAX_VALUE;
for(Chemin<T> c : chemins) {
if (distanceLaPlusCourte > c.distance()) {
distanceLaPlusCourte = c.distance();
cheminLePlusCourt = c;
}
}
return cheminLePlusCourt;
}
public Set<T> voisinsAuRang(T origine, int rang){
List<Chemin<T>> chemins = chemins(origine);
Set<T> TsVoisinsDejaVu = new TreeSet<>();
Set<T> TsDeBonRang = new TreeSet<>();
for (Chemin<T> c : chemins) {
List<T> sommets = c.sommets();
int i = 0;
for (i = 0; (i <sommets.size() && i < rang); i++)
TsVoisinsDejaVu.add(sommets.get(i));
if ( (i == rang) && (i < sommets.size()) )
TsDeBonRang.add(sommets.get(i));
}
TsDeBonRang.removeAll(TsVoisinsDejaVu);
return TsDeBonRang;
}
}

View File

@@ -0,0 +1,83 @@
package designPattern.grapheX;
/**
* Classe d'arcs
*
* @author FMorain (morain@lix.polytechnique.fr)
* @author PChassignet (chassign@lix.polytechnique.fr)
* @author JCervelle (julien.cervelle@univ-mlv.fr)
* @version 2007.03.21
*/
// L'arc o -> d avec valeur val
public class Arc<S extends Identifiable> implements Comparable<Arc<S>> {
private S o, d;
private int val;
public Arc(S o0, S d0, int val0) {
this.o = o0;
this.d = d0;
this.val = val0;
}
public Arc(S o0, S d0) {
this.o = o0;
this.d = d0;
this.val = 0;
}
public Arc(Arc<S> a) {
this.o = a.o;
this.d = a.d;
this.val = a.val;
}
public S destination() {
return d;
}
public S origine() {
return o;
}
public int valeur() {
return val;
}
public void modifierValeur(int vv) {
this.val = vv;
}
@Override
public String toString() {
return "(" + val + ":" + this.o + ", " + this.d + ")";
}
@Override
public int hashCode() {
int codeOri = (o == null ? 0 : o.hashCode());
int codeDst = (d == null ? 0 : d.hashCode());
return codeDst ^ (codeOri * 31);
}
@Override
public boolean equals(Object aa) {
if (!(aa instanceof Arc))
return false;
Arc<?> arc = (Arc<?>) aa;
boolean equalsO = o == null && arc.o == null || o != null
&& o.equals(arc.o);
boolean equalsD = d == null && arc.d == null || d != null
&& d.equals(arc.d);
return equalsO && equalsD && (val == arc.val);
}
public int compareTo(Arc<S> a) {
int comp = Identifiable.compare(this.o, a.o);
if (comp == 0)
comp = Identifiable.compare(d, a.d);
return comp;
}
}

View File

@@ -0,0 +1,871 @@
package designPattern.grapheX;
import java.util.*;
/**
Classe abstraite de graphes
@author FMorain (morain@lix.polytechnique.fr)
@version 2008.03.01
@author MBF revisée pour la rendre générique
*/
public abstract class Graphe<T extends Sommet> extends GrapheGenerique<T>{
@Override
public abstract int taille();
public abstract Graphe<T> copie();
@Override
public abstract void ajouterSommet(T s);
@Override
public abstract boolean existeArc(T s, T t);
@Override
public abstract void ajouterArc(T s, T t, int val);
public abstract void ajouterArc(Arc<T> arc);
@Override
public abstract int valeurArc(T s, T t);
@Override
public abstract void enleverArc(T s, T t);
@Override
public abstract Collection<T> sommets();
@Override
public abstract Collection<Arc<T>> voisins(T s);
public boolean oriente;
public static String version(){
return "grapheX -- version 1.3d, 2008/02/27";
}
public void ajouterArc(T s, T t){
ajouterArc(s, t, 0);
}
public boolean existeArc(Arc<T> alpha){
return existeArc(alpha.origine(), alpha.destination());
}
public String toString(){
String str = "";
for(T s : sommets()){
str += s + ":";
for(T t : sommets()){
if(existeArc(s, t))
str += " " + valeurArc(s, t);
else
str += " -";
}
str += "\n";
}
return str;
}
/* public void faireComplet(){
int n = taille();
for(int i = 0; i < n; i++)
ajouterSommet(new Sommet(i+""));
for(Sommet s : sommets())
for(Sommet t : sommets())
if(!s.equals(t))
ajouterArc(s, t, 1);
}
public static void afficherParcours(HashMap<Sommet,Integer> L){
System.err.println("PARCOURS");
for(Sommet s : L.keySet())
System.err.print(" ["+s+", "+L.get(s)+"]");
System.err.println();
}
public static Graphe RoyWarshall(Graphe G){
Graphe F = G.copie();
for(Sommet s : G.sommets())
F.ajouterArc(s, s, 1);
System.err.println("FT_ini = \n"+F);
for(Sommet r : G.sommets()){
for(Sommet s : G.sommets())
for(Sommet t : G.sommets())
if(!F.existeArc(s, t)
&& (F.existeArc(s, r) && F.existeArc(r, t)))
F.ajouterArc(s, t, 1);
System.err.println("\nA_"+r);
System.err.println(F);
}
return F;
}*/
//////////////////// Dijkstra ////////////////////
public HashMap<T,Integer> Dijkstra(T s){
int INFINITY = 1000000;
HashMap<T,Integer> L = new HashMap<T,Integer>();
// 1. initialisation
for(T t : sommets())
if(! t.equals(s))
if(existeArc(s, t))
L.put(t, valeurArc(s, t));
else
L.put(t, INFINITY);
// 2.
HashSet<T> U = new HashSet<>(sommets()); // copie
L.put(s, 0);
U.remove(s);
// 3.
while(! U.isEmpty()){
//afficherParcours(L);
// 4.
T v = null;
int Lv = INFINITY;
for(T t : U)
if(L.get(t) < Lv){
v = t;
Lv = L.get(t);
}
System.err.println("-->v="+v);
// 5.
U.remove(v);
// 6.
// for(Sommet t : U)
// if(existeArc(v, t)){
for(Arc<T> a : voisins(v)){
T t = a.destination();
int tmp = Lv + a.valeur();
if(tmp < L.get(t))
L.put(t, tmp);
}
}
return L;
}
/*
TreeSet<SommetValue> Dijkstra2Init(HashMap<T,Integer> L, T s){
int INFINITY = 1000000;
TreeSet<SommetValue> fp =
new TreeSet<SommetValue>(
new Comparator<SommetValue>() {
public int compare(SommetValue s1, SommetValue s2) {
if(s1.valeur < s2.valeur)
return -1;
else if(s1.valeur > s2.valeur)
return 1;
if(s1.s.equals(s2.s))
return 0;
return -1;
}
}
);
for(Sommet u : sommets()){
if(u.equals(s))
L.put(u, 0);
else if(existeArc(s, u)){
int val = valeurArc(s, u);
fp.add(new SommetValue(u, val));
L.put(u, val);
}
else{
fp.add(new SommetValue(u, INFINITY));
L.put(u, INFINITY);
}
}
return fp;
}
public HashMap<T,Integer> Dijkstra2(T s){
HashMap<T,Integer> L = new HashMap<T,Integer>();
// 1. initialisation
TreeSet<SommetValue> U = Dijkstra2Init(L, s);
// 3.
while(! U.isEmpty()){
//afficherParcours(L);
// 4.
SommetValue v = U.first();
U.remove(v);
int Lv = v.valeur;
//System.err.println("v="+v.s+" Lv="+Lv);
// 5.
// 6.
for(Arc<T> a : voisins(v.s)){
Sommet t = a.destination();
int tmp = Lv + a.valeur();
if(tmp < L.get(t)){
// System.err.println("-"+t+" "+L.get(t));
U.remove(new SommetValue(t, L.get(t)));
// System.err.println("+"+t+" "+tmp);
U.add(new SommetValue(t, tmp));
L.put(t, tmp);
}
}
}
return L;
}
public void Prim(){
HashSet<Sommet> HS = new HashSet<Sommet>();
for(Sommet u : sommets()){
if(! HS.contains(u)){
//System.err.println("Je pars de "+u);
HS.add(u);
TreeSet<Arc<Sommet>> fp =
new TreeSet<Arc<Sommet>>(
new Comparator<Arc<Sommet>>(){
public int compare(Arc<Sommet> a1, Arc<Sommet> a2){
if(a1.valeur() < a2.valeur())
return -1;
else if(a1.valeur() > a2.valeur())
return 1;
else if(a1.equals(a2))
return 0;
else if(! a1.origine().equals(a2.origine()))
return a1.origine().compareTo(a2.origine());
else if(! a1.destination().equals(a2.destination()))
return a1.destination().compareTo(a2.destination());
else
return 0;
}
}
);
for(Arc<Sommet> a : voisins(u)){
//System.err.println("fp += "+a+" ["+a.valeur()+"]");
fp.add(a);
}
while(! fp.isEmpty()){
System.err.println("FP_BEGIN");
for(Arc<Sommet> z : fp){
System.err.println(z+" "+z.valeur());
}
System.err.println("FP_END");
Arc<Sommet> a = fp.first();
fp.remove(a);
Sommet t = a.destination();
System.err.print("Je regarde "+a+"["+a.valeur()+"] : ");
if(HS.contains(t))
System.err.println("il forme un cycle");
else{
System.err.println("je l'ajoute dans T");
HS.add(t);
for(Arc<Sommet> b : voisins(t)){
System.err.println("fp += "+b+" ["+b.valeur()+"]");
fp.add(b);
}
}
}
}
}
}
//////////////////// BFS ////////////////////
final static int inexplore = 0, encours = 1, explore = 2;
public void bfs(HashMap<Sommet,Integer> etat, Sommet s){
LinkedList<Sommet> f = new LinkedList<Sommet>();
etat.put(s, encours);
f.addLast(s);
while(! f.isEmpty()){
Sommet t = f.removeFirst();
System.err.println("J'explore "+t);
for(Arc<Sommet> a : voisins(t)){
Sommet u = a.destination();
if(etat.get(u) == inexplore){
etat.put(u, encours);
f.addLast(u);
}
}
etat.put(t, explore);
}
}
public HashMap<Sommet,Integer> bfsDistance(Sommet s){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
LinkedList<Sommet> f = new LinkedList<Sommet>();
HashMap<Sommet,Integer> distance =
new HashMap<Sommet,Integer>();
HashMap<Sommet,Integer> numero =
new HashMap<Sommet,Integer>();
int num = 0;
for(Sommet t : sommets()){
etat.put(t, inexplore);
distance.put(t, 0);
numero.put(t, 0);
}
etat.put(s, encours);
f.addLast(s);
numero.put(s, num++);
while(! f.isEmpty()){
Sommet t = f.removeFirst();
System.err.println("J'explore "+t);
for(Arc<Sommet> a : voisins(t)){
Sommet u = a.destination();
if(etat.get(u) == inexplore){
etat.put(u, encours);
f.addLast(u);
numero.put(u, num++);
System.err.println("num["+u+"]="+numero.get(u));
distance.put(u, distance.get(t) + 1);
}
}
etat.put(t, explore);
}
return distance;
}
public void composantesConnexesBFS(){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
for(Sommet s : sommets())
etat.put(s, inexplore);
int ncc = 0;
for(Sommet s : sommets())
if(etat.get(s) == inexplore){
ncc++;
System.err.println("Composante "+ncc);
bfs(etat, s);
}
}
public boolean bfsBiparti(HashMap<Sommet,Integer> etat, HashMap<Sommet,Integer> couleur, Sommet s){
LinkedList<Sommet> f = new LinkedList<Sommet>();
int c = 0; // la couleur
etat.put(s, encours);
couleur.put(s, c);
f.addLast(s);
while(! f.isEmpty()){
Sommet t = f.removeFirst();
System.err.println("J'explore "+t+" de couleur "+couleur.get(t));
// c <- couleur des voisins de t
c = 1 - couleur.get(t);
for(Arc<Sommet> a : voisins(t)){
Sommet u = a.destination();
if(etat.get(u) == inexplore){
etat.put(u, encours);
couleur.put(u, c);
f.addLast(u);
}
else if(couleur.get(u) != c){
System.err.println(u+" est de'ja` colorie' avec la mauvaise couleur");
return false;
}
}
etat.put(t, explore);
}
return true;
}
// n'a vraiment un sens que sur les graphes non oriente's connexes
public HashMap<Sommet,Integer> estBiparti(){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
HashMap<Sommet,Integer> couleur = new HashMap<Sommet,Integer>();
for(Sommet s : sommets())
etat.put(s, inexplore);
int ncc = 0;
for(Sommet s : sommets())
if(etat.get(s) == inexplore){
ncc++;
System.err.println("Composante "+ncc);
if(!bfsBiparti(etat, couleur, s))
// le graphe n'est pas biparti
return null;
}
return couleur;
}
////////////DFS
public void dfs(HashMap<Sommet,Integer> etat, Sommet s){
LinkedList<Sommet> F = new LinkedList<Sommet>();
int rg = -1;
F.addFirst(s);
while(! F.isEmpty()){
Sommet t = F.removeFirst();
if(etat.get(t) != explore){
System.err.println("J'explore "+t);
etat.put(t, encours);
++rg;
System.err.println("rang["+t+"]="+rg);
for(Arc<Sommet> a : voisins(t)){
Sommet u = a.destination();
F.addFirst(u);
}
}
etat.put(t, explore);
}
}
public void dfs(){
Sommet r = null;
for(Sommet s : sommets()){
r = s;
break;
}
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
for(Sommet s : sommets())
etat.put(s, inexplore);
//dfsFausse(etat, r); // pour avoir un exemple qui foire Data/pchassignet.in
dfs(etat, r);
}
public int dfsRec(HashMap<Sommet,Integer> etat,
HashMap<Arc<Sommet>,String> etat_a,
HashMap<Sommet,Integer> rang, int rg,
Sommet racine, Sommet s){
etat.put(s, encours);
rang.put(s, rg++);
System.err.println("J'explore "+s);
for(Arc<Sommet> a : voisins(s)){
Sommet t = a.destination();
if(etat.get(t) == inexplore){
System.err.println("("+s+", "+t+") liaison");
etat_a.put(a, "arcliaison");
rg = dfsRec(etat, etat_a, rang, rg, racine, t);
}
else{
if(etat.get(t) == encours){
// t est ascendant de s
System.err.println("("+s+", "+t+") arrie`re");
etat_a.put(a, "arcarriere");
}
else{
// t a de'ja` e'te' explore'
if(rang.get(t) < rang.get(racine)){
System.err.println("("+s+", "+t+") transverse car racine("+t+") <> racine("+s+")");
etat_a.put(a, "arcinter");
}
else{ // t est dans la me^me arborescence que s
if(rang.get(s) < rang.get(t)){
System.err.println("("+s+", "+t+") avant");
etat_a.put(a, "arcavant");
}
else{
System.err.println("("+s+", "+t+") transverse");
etat_a.put(a, "arcintra");
}
}
}
}
}
etat.put(s, explore);
return rg;
}
public void dfsRang(){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
HashMap<Arc<Sommet>,String> etat_a = new HashMap<Arc<Sommet>,String>();
HashMap<Sommet,Integer> rang = new HashMap<Sommet,Integer>();
for(Sommet s : sommets()){
etat.put(s, inexplore);
for(Arc<Sommet> alpha : voisins(s))
etat_a.put(alpha, "arclibre");
}
int rg = 0;
for(Sommet s : sommets())
if(etat.get(s) == inexplore)
rg = dfsRec(etat, etat_a, rang, rg, s, s);
System.err.print(" ");
for(Sommet t : sommets())
System.err.print(t);
System.err.print("\nrang ");
for(Sommet t : sommets())
System.err.print(rang.get(t));
System.err.println();
}
// on retourne un arbre couvrant de racine s
public Arbre dfsRec(HashMap<Sommet,Integer> etat, Sommet s){
etat.put(s, encours);
Arbre A = new Arbre(s);
System.err.println("J'explore "+s);
for(Arc<Sommet> a : voisins(s)){
Sommet t = a.destination();
if(etat.get(t) == inexplore)
A.ajouterFils(dfsRec(etat, t));
}
etat.put(s, explore);
return A;
}
public void dfsCouvrant(){
Sommet ALPHA = new Sommet("ALPHA");
Arbre F = new Arbre(ALPHA);
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
for(Sommet s : sommets())
etat.put(s, inexplore);
for(Sommet s : sommets())
if(etat.get(s) == inexplore)
F.ajouterFils(dfsRec(etat, s));
System.err.println("F=\n"+F);
}
//// Tri topologique
boolean dfsTopo(HashMap<Sommet,Integer> etat,
LinkedList<Sommet> L, Sommet s){
etat.put(s, encours);
System.err.println("J'explore "+s);
for(Arc<Sommet> a : voisins(s)){
Sommet t = a.destination();
if(etat.get(t) == inexplore){
if(! dfsTopo(etat, L, t))
return false;
}
else if(etat.get(t) == encours){
// t est ascendant de s
System.err.println("("+s+", "+t+") arrie`re -> erreur");
return false;
}
}
etat.put(s, explore);
L.addFirst(s);
return true;
}
public void triTopologique(){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
for(Sommet s : sommets())
etat.put(s, inexplore);
for(Sommet s : sommets()){
if(etat.get(s) == inexplore){
LinkedList<Sommet> L = new LinkedList<Sommet>();
if(! dfsTopo(etat, L, s)){
System.err.println("Graphe avec circuit");
return;
}
for(Sommet t : L)
System.err.print(t+" -> ");
System.err.println();
}
}
}
//// Points d'attache
int dfsAttache(HashMap<Sommet,Integer> etat,
HashMap<Sommet,Integer> rang, int rg,
HashMap<Sommet,Integer> rat, Sommet racine, Sommet s){
etat.put(s, encours);
System.err.println("J'explore "+s);
rang.put(s, rg++);
int rats = rang.get(s), ratt;
for(Arc<Sommet> a : voisins(s)){
Sommet t = a.destination();
if(etat.get(t) == inexplore){
rg = dfsAttache(etat, rang, rg, rat, racine, t);
ratt = rat.get(t);
}
else if(etat.get(t) == encours)
// (s, t) est un arc arrie`re
ratt = rang.get(t);
else if(rang.get(t) < rang.get(racine))
// (s, t) transverse inter
continue;
else // (s, t) avant ou transverse intra
ratt = rang.get(t);
// HERE: vrai? Cf. exemple bbc1 pour l semble faux...!
rats = Math.min(rats, ratt);
}
rat.put(s, rats);
etat.put(s, explore);
return rg;
}
public void pointsDAttache(){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
HashMap<Sommet,Integer> rang = new HashMap<Sommet,Integer>();
HashMap<Sommet,Integer> rat = new HashMap<Sommet,Integer>();
for(Sommet s : sommets())
etat.put(s, inexplore);
int rg = 0;
for(Sommet s : sommets())
if(etat.get(s) == inexplore)
rg = dfsAttache(etat, rang, rg, rat, s, s);
System.err.println("Rangs");
for(Sommet s : sommets())
System.err.println(s+" "+rang.get(s));
System.err.println("Rangs d'attache");
for(Sommet s : sommets())
System.err.println(s+" "+rat.get(s));
}
//// Composantes fortement connexes
final static int libre = 0, empile = 1, exclus = 2, pointdentree = 3, dansCFC = 4;
int dfsCfc(HashMap<Sommet,Integer> etat,
HashMap<Sommet,Integer> etat_cfc,
HashMap<Arc<Sommet>,String> etat_a,
LinkedList<Sommet> pile,
HashMap<Sommet,Integer> rang, int rg,
HashMap<Sommet,Integer> rat,
Sommet racine, Sommet s){
etat.put(s, encours);
System.err.println("J'explore "+s);
rang.put(s, rg++);
rat.put(s, rang.get(s));
pile.addFirst(s);
etat_cfc.put(s, empile);
for(Arc<Sommet> a : voisins(s)){
Sommet t = a.destination();
if(etat_cfc.get(t) == inexplore){
System.err.println("("+s+", "+t+") liaison");
etat_a.put(a, "arcliaison");
rg = dfsCfc(etat, etat_cfc, etat_a, pile, rang, rg, rat, racine, t);
if(rat.get(t) < rat.get(s)){
rat.put(s, rat.get(t));
}
}
else{
if(etat_cfc.get(t) == empile){
if(rang.get(t) > rang.get(s))
// (s, t) est avant
etat_a.put(a, "arcavant");
else{
// (s, t) est arriere ou intra-arbre
// t est dans C(s) car t descendant de s et s -> t
if(etat.get(t) == encours){
System.err.println("("+s+", "+t+") arrie`re");
etat_a.put(a, "arcarriere");
}
else{
System.err.println("("+s+", "+t+") intra-arbre");
etat_a.put(a, "arcintra");
}
System.err.println(t+" est dans C("+s+")");
if(rang.get(t) < rat.get(s))
rat.put(s, rang.get(t));
}
}
else{
// t est exclus
System.err.println(t+" exclus");
if(rang.get(t) < rang.get(racine))
// (s, t) est inter-arbre
etat_a.put(a, "arcinter");
else
etat_a.put(a, "arcintra");
}
}
}
etat.put(s, explore);
System.err.print("rang["+s+"]="+rang.get(s));
System.err.println(" rat["+s+"]="+rat.get(s));
if(rat.get(s) == rang.get(s)){
// s est un point d'entre'e
etat_cfc.put(s, pointdentree);
for(Sommet u : pile){
if(u.equals(s))
break;
etat_cfc.put(u, dansCFC);
}
Sommet t;
System.err.print("CFC={");
do{
t = pile.removeFirst();
etat_cfc.put(t, exclus);
System.err.print(" "+t);
} while(! t.equals(s));
System.err.println(" }");
}
return rg;
}
public void cfc(){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
HashMap<Sommet,Integer> etat_cfc = new HashMap<Sommet,Integer>();
HashMap<Arc<Sommet>,String> etat_a = new HashMap<Arc<Sommet>, String>();
HashMap<Sommet,Integer> rang = new HashMap<Sommet,Integer>();
HashMap<Sommet,Integer> rat = new HashMap<Sommet,Integer>();
LinkedList<Sommet> pile = new LinkedList<Sommet>();
for(Sommet s : sommets()){
etat.put(s, inexplore);
etat_cfc.put(s, libre);
for(Arc<Sommet> alpha : voisins(s))
etat_a.put(alpha, "arclibre");
}
int rg = 0;
for(Sommet s : sommets())
if(etat.get(s) == inexplore)
rg = dfsCfc(etat, etat_cfc, etat_a, pile, rang, rg, rat, s, s);
System.err.println("Rangs");
for(Sommet s : sommets())
System.err.println(s+" "+rang.get(s));
}
//// Points d'articulation et blocs
void depiler(LinkedList<Arc<Sommet>> pile, Sommet s, Sommet t){
Sommet x, y;
System.err.print("Bloc = {");
do{
Arc<Sommet> a = pile.removeFirst();
x = a.origine();
y = a.destination();
System.err.print("("+x+", "+y+")");
} while(!x.equals(s) && !y.equals(t));
System.err.println("}");
}
void depiler(LinkedList<Arc<Sommet>> pile){
System.err.print("Bloc_racine = {");
while(! pile.isEmpty()){
Arc<Sommet> a = pile.removeFirst();
System.err.print("("+a.origine()+", "+a.destination()+")");
}
System.err.println("}");
}
// pere -> s
int dfsPda(LinkedList<Sommet> lpda,
HashMap<Sommet,Integer> etat,
LinkedList<Arc<Sommet>> pile,
HashMap<Sommet,Integer> rang, int rg,
HashMap<Sommet,Integer> rat,
Sommet pere, Sommet s){
etat.put(s, encours);
System.err.println("J'explore "+s);
rang.put(s, rg++);
int rats = rang.get(s);
for(Arc<Sommet> a : voisins(s)){
Sommet t = a.destination();
if(etat.get(t) == inexplore){
System.err.println("("+s+", "+t+") liaison");
pile.addFirst(a);
rg = dfsPda(lpda, etat, pile, rang, rg, rat, s, t);
rats = Math.min(rats, rat.get(t));
if(rat.get(t) >= rang.get(s)){
System.err.println(s+" est point d'articulation");
depiler(pile, s, t);
lpda.addFirst(s);
}
}
else if((rang.get(t) < rang.get(s)) && !t.equals(pere)){
System.err.println("("+s+", "+t+") arrie`re ou transverse");
pile.addFirst(a);
rats = Math.min(rats, rang.get(t));
}
}
rat.put(s, rats);
System.err.print("rang["+s+"]="+rang.get(s));
System.err.println(" rat["+s+"]="+rat.get(s));
etat.put(s, explore);
return rg;
}
// s est la racine de l'arborescence
int dfsPda(LinkedList<Sommet> lpda,
HashMap<Sommet,Integer> etat,
LinkedList<Arc<Sommet>> pile,
HashMap<Sommet,Integer> rang, int rg,
HashMap<Sommet,Integer> rat, Sommet s){
etat.put(s, encours);
System.err.println("J'explore "+s);
rang.put(s, rg++);
int rats = rang.get(s);
int nfils = 0;
for(Arc<Sommet> a : voisins(s)){
Sommet t = a.destination();
if(etat.get(t) == inexplore){
System.err.println("("+s+", "+t+") liaison");
pile.addFirst(a);
rg = dfsPda(lpda, etat, pile, rang, rg, rat, s, t);
nfils++;
}
}
if(nfils > 1){
lpda.addFirst(s);
System.err.println(s+" est racine ET point d'articulation");
depiler(pile);
}
rat.put(s, rats);
System.err.print("rang["+s+"]="+rang.get(s));
System.err.println(" rat["+s+"]="+rat.get(s));
etat.put(s, explore);
return rg;
}
public void pointsDArticulation(LinkedList<Sommet> lpda,
HashMap<Sommet,Integer> rat){
HashMap<Sommet,Integer> etat = new HashMap<Sommet,Integer>();
HashMap<Sommet,Integer> rang = new HashMap<Sommet,Integer>();
for(Sommet s : sommets())
etat.put(s, inexplore);
int rg = 0;
LinkedList<Arc<Sommet>> pile = new LinkedList<Arc<Sommet>>();
for(Sommet s : sommets())
if(etat.get(s) == inexplore)
// nouvelle composante connexe
rg = dfsPda(lpda, etat, pile, rang, rg, rat, s);
System.err.println("Rangs");
for(Sommet s : sommets())
System.err.println(s+" "+rang.get(s));
}
public static String XMLHeader(){
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
str += "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n";
str += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
str += "xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n";
str += "http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n";
str += " <key id=\"Pigale/version\" for=\"graph\" attr.name=\"Pigale version\" attr.type=\"string\">\n";
str += " <default>1.3.9</default>\n";
str += " </key>\n";
str += " <key id=\"Pigale/V/16\" for=\"node\" attr.name=\"Coordinates\" attr.type=\"string\"/>\n";
str += " <key id=\"Pigale/V/1\" for=\"node\" attr.name=\"Color\" attr.type=\"string\"/>\n";
str += " <key id=\"Pigale/V/0\" for=\"node\" attr.name=\"Label\" attr.type=\"string\"/>\n";
str += " <key id=\"Pigale/E/1\" for=\"edge\" attr.name=\"Color\" attr.type=\"string\"/>\n";
str += " <key id=\"Pigale/E/16\" for=\"edge\" attr.name=\"Width\" attr.type=\"string\"/>\n";
return str;
}
public static String XMLTrailer(){
return "</graphml>\n";
}
// pos[s] est la position de s dans le plan, color[s] le contenu de s, par exemple une couleur.
// pos[s] doit etre de la forme x,y
public String toGraphml(String nom, HashMap<Sommet,String> pos, HashMap<Sommet,Integer> color){
String str = XMLHeader();
str += " <graph id=\"" + nom + "\"";
if(oriente)
str += " edgedefault=\"directed\">\n";
else
str += " edgedefault=\"undirected\">\n";
// les sommets
for(Sommet s : sommets()){
str += " <node id=\"" + s + "\">\n";
if(pos != null)
str += " <data key=\"Pigale/V/16\">"+pos.get(s)+"</data>\n";
if(color != null)
str += " <data key=\"Pigale/V/1\">" + color.get(s) + "</data>\n";
str += " <data key=\"Pigale/V/0\">" + s + "</data>\n";
str += " </node>\n";
}
// les aretes
for(Sommet s : sommets()){
for(Arc<Sommet> arc : voisins(s)){
// TODO: permettre des couleurs et labels sur les arcs
Sommet t = arc.destination();
str += " <edge source=\""+s+"\" target=\""+t+"\">\n";
str += " <data key=\"Pigale/E/1\">1</data>\n";
str += " <data key=\"Pigale/E/16\">1</data>\n";
str += " </edge>\n";
}
}
str += " </graph>\n";
str += XMLTrailer();
return str;
}*/
}

View File

@@ -0,0 +1,81 @@
package designPattern.grapheX;
import java.util.Collection;
/**
* Super-classe abstraite des graphes, les sommets doivent <20>tre identifiables.
*
* @author FMorain (morain@lix.polytechnique.fr)
* @author PChassignet (chassign@lix.polytechnique.fr)
* @version 2007.03.21
*/
public abstract class GrapheGenerique<S extends Identifiable> {
/**
* @return le nombre de sommets de ce graphe.
*/
public abstract int taille();
/**
* @param s
* le sommet <20> ajouter <20> ce graphe.
*/
public abstract void ajouterSommet(S s);
/**
* @return une <tt>Collection</tt> de tous les sommets de ce graphe.
*/
public abstract Collection<S> sommets();
/**
* Teste l'existence de l'arc de <tt>s</tt> <20> <tt>t</tt> dans ce graphe.
*
* @param s
* l'origine de l'arc,
* @param t
* l'extr<74>mit<69> de l'arc.
*/
public abstract boolean existeArc(S s, S t);
/**
* @param s
* l'origine de l'arc,
* @param t
* l'extr<74>mit<69> de l'arc,
* @param val
* une valeur enti<74>re attach<63>e <20> l'arc de <tt>s</tt> <20> <tt>t</tt>
* dans ce graphe.
*/
public abstract void ajouterArc(S s, S t, int val);
/**
* @param s
* l'origine de l'arc,
* @param t
* l'extr<74>mit<69> de l'arc.
* @return la valeur enti<74>re attach<63>e <20> l'arc de <tt>s</tt> <20> <tt>t</tt>
* dans ce graphe.
*/
public abstract int valeurArc(S s, S t);
/**
* Supprime l'arc de <tt>s</tt> <20> <tt>t</tt> dans ce graphe.
*
* @param s
* l'origine de l'arc,
* @param t
* l'extr<74>mit<69> de l'arc.
*/
public abstract void enleverArc(S s, S t);
/**
* @param s
* l'origine des arcs.
* @return une <tt>Collection</tt> de tous les arcs de ce graphe ayant
* <tt>s</tt> pour origine. Ces arcs sont de type
* <tt>Arc&lt;S&gt;</tt>.
*/
public abstract Collection<Arc<S>> voisins(S s);
}

View File

@@ -0,0 +1,100 @@
package designPattern.grapheX;
/**
* D<>finit des objets identifi<66>s par une <tt>String</tt>. Deux objets
* <tt>Identifiable</tt> qui sont construit avec le m<>me identifiant seront
* consid<69>r<EFBFBD>s comme identiques pour les m<>thodes <tt>hashCode</tt>,
* <tt>equals</tt> et <tt>compareTo</tt>. Cette classe sert notamment de
* super-classe pour les sommets d'un graphe.
*
* @author PChassignet (chassign@lix.polytechnique.fr)
* @version 2007.03.21
*/
public class Identifiable implements Comparable<Identifiable> {
private final String ident;
/**
* @param identifiant
* l'identifiant pour cet objet.
*/
public Identifiable(String identifiant) {
ident = identifiant;
}
/**
* @return l'identifiant pour cet objet.
*/
public final String identifiant() {
return ident;
}
/**
* @return le <tt>hashCode</tt> de l'identifiant de cet objet.
*/
@Override
public final int hashCode() {
if (ident == null)
return 0;
else
return ident.hashCode();
}
/**
* @return le r<>sultat de <tt>equals</tt> sur les identifiants.
*/
@Override
public final boolean equals(Object o) {
if (!(o instanceof Identifiable)) {
return false;
}
String oid = ((Identifiable) o).ident;
if (ident == null)
return oid == null;
else
return ident.equals(oid);
}
/**
* @return le r<>sultat de <tt>compareTo</tt> sur les identifiants.
*/
public final int compareTo(Identifiable id) {
if (ident == null)
if (id.ident == null)
return 0;
else
return -1;
else if (id.ident == null)
return 1;
else
return ident.compareTo(id.ident);
}
/**
* @param id1
* premier objet <20> comparer,
* @param id2
* second objet <20> comparer,
* @return le r<>sultat de <tt>id1.compareTo(id2)</tt>.
*/
public static final int compare(Identifiable id1, Identifiable id2) {
if (id1 == null)
if (id2 == null)
return 0;
else
return -1;
else if (id2 == null)
return 1;
else
return id1.compareTo(id2);
}
@Override
public String toString() {
if (ident == null)
return "[null]";
else
return "[\"" + ident + "\"]";
}
}

View File

@@ -0,0 +1,23 @@
package designPattern.grapheX;
/**
* Classe de sommets, toutes les propri<72>t<EFBFBD>s sont h<>rit<69>es de Identifiable.
*
* @author FMorain (morain@lix.polytechnique.fr)
* @author PChassignet (chassign@lix.polytechnique.fr)
* @version 2007.03.21
*/
public class Sommet extends Identifiable {
public Sommet(String nn) {
super(nn);
}
@Override
public String toString() {
return identifiant();
}
}

View File

@@ -0,0 +1,11 @@
package designPattern.grapheX;
public class SommetValue {
Sommet s;
int valeur;
SommetValue(Sommet ss, int vv){
s = ss;
valeur = vv;
}
}

View File

@@ -0,0 +1,44 @@
package designPattern.reseauSocial.core;
import designPattern.grapheX.Sommet;
public class Member extends Sommet implements MemberInterface {
private String localisation;
private Enum<Strength> force;
public Member(String nn) {
super(nn);
// TODO Auto-generated constructor stub
}
@Override
public String getLocation() {
return this.localisation;
}
@Override
public void setLocation(String s) {
this.localisation = s;
}
@Override
public String getName() {
return super.toString();
}
public Enum<Strength> getForce() {
return force;
}
public void setForce(Enum<Strength> force) {
this.force = force;
}
public void addMember(String nom, String location, SocialNetworkInterface<Member> reseau) {
Member m = new Member(nom);
m.setLocation(location);
reseau.addMember(m);
}
}

View File

@@ -0,0 +1,10 @@
package designPattern.reseauSocial.core;
public interface MemberInterface {
public String getLocation();
public void setLocation(String s);
public String getName();
}

View File

@@ -0,0 +1,85 @@
package designPattern.reseauSocial.core;
import java.util.Collection;
import java.util.Observable;
import java.util.Set;
import designPattern.facebookGhost.FacebookGhostNetwork;
import designPattern.grapheSimple.GrapheSimple;
@SuppressWarnings("deprecation")
public class SocialNetWorkImpl implements SocialNetworkInterface<Member>{
private String nom;
private GrapheSimple<Member> reseau;
public SocialNetWorkImpl() {
this("Default");
}
public SocialNetWorkImpl(String n) {
this.nom = n;
reseau = new GrapheSimple<Member>();
}
@Override
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
}
@Override
public Member getMember(String identifier) {
return reseau.getSommet(identifier);
}
@Override
public Collection<Member> getMembers() {
return reseau.sommets();
}
@Override
public void addMember(Member m) {
reseau.ajouterSommet(m);
}
@Override
public Member addMember(String ident, FacebookGhostNetwork fg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Member addMember(String identifier) {
// TODO Auto-generated method stub
return null;
}
@Override
public void relate(Strength force, Member member, Member friend) {
// TODO Auto-generated method stub
}
@Override
public Set<Member> relatedToRank(Member member, int rank) {
// TODO Auto-generated method stub
return null;
}
@Override
public int distance(Member member1, Member member2) {
// TODO Auto-generated method stub
return 0;
}
public String getNom() {
return nom;
}
public void setNom(String n) {
this.nom = n;
}
}

View File

@@ -0,0 +1,74 @@
package designPattern.reseauSocial.core;
import java.util.Collection;
import java.util.Observer;
import java.util.Set;
import designPattern.facebookGhost.FacebookGhostNetwork;
/**
*
* Basic" interface for defining a social network
*
* @author blay
*
*/
@SuppressWarnings("deprecation")
public interface SocialNetworkInterface<T> extends Observer{
/**
* @param identifier for a member
* @return member if known by the network
*/
public T getMember(String identifier);
/**
* @return the set of members belonging to the network
*/
public Collection<T> getMembers();
/**
* add a member to the network
*/
public void addMember(T membre);
/**
* @param ident
* @param fg a facebookGhostNetwork, if the member belongs to fg, an adapter to this network is created.
* @return the member corresponding to the identifier. If a member with this identifer already exists, the member is not created.
*/
public T addMember(String ident, FacebookGhostNetwork fg);
public T addMember(String identifier);
/**
*
* Add the relationship between a member and a friend with a given force.
*
* @param force
* @param member
* @param friend
*
*/
public void relate(Strength force, T member, T friend);
/**
* @param member
* @param rank
* @return returns all members given the rank (at rank 1 : direct neighbors; at rank 2 : neighbors of neighbors.
* A member appears at the lowest rank, it does not appear in a higher rank
*/
public Set<T> relatedToRank(T member, int rank);
/**
* @param member1
* @param member2
* @return distance between the two members
*/
public int distance(T member1, T member2);
}

View File

@@ -0,0 +1,17 @@
package designPattern.reseauSocial.core;
public enum Strength {
LOW (4), MEDIUM (3), HIGH (2), STRONG(1);
int value;
public int getValue() {
return value;
}
Strength( int pvalue){
value = pvalue;
}
}

15
src/forum/Administrateur.java Executable file
View File

@@ -0,0 +1,15 @@
package forum;
public class Administrateur {
private String nom;
public Administrateur() {
}
public Administrateur(String nomAdmin) {
this.nom = nomAdmin;
}
}

17
src/forum/Canal.java Executable file
View File

@@ -0,0 +1,17 @@
package forum;
import java.util.ArrayList;
public class Canal {
private int maxMessage;
private String nomCanal;
private Message message;
ArrayList canal = new ArrayList();
public Canal(String nomCanal, int maxMessage) {
this.nomCanal = nomCanal;
this.maxMessage = maxMessage;
}
}

14
src/forum/CanalDeBreve.java Executable file
View File

@@ -0,0 +1,14 @@
package forum;
public class CanalDeBreve {
private int tailleBreves;
private String nomCanal;
private Message message;
public CanalDeBreve(String nomCanal, int tailleBreves) {
this.nomCanal = nomCanal;
this.tailleBreves = tailleBreves;
}
}

9
src/forum/CanalParDefaut.java Executable file
View File

@@ -0,0 +1,9 @@
package forum;
public class CanalParDefaut {
public String nom;
public CanalParDefaut(String nom) {
}
}

88
src/forum/Controleur.java Executable file
View File

@@ -0,0 +1,88 @@
package forum;
public class Controleur {
private GestionnaireForum registreF = new GestionnaireForum();
private GestionnaireCanal registreC = new GestionnaireCanal();
private UserConsole ui = new UserConsole();
public void start() throws Exception {
String commande = ui.lireCommande();
switch (commande.charAt(0)) {
case UserConsole.COM_CREER_FORUM:
creerForum();
start();
break;
case UserConsole.COM_CREER_CANAL:
creerCanal();
start();
break;
case UserConsole.COM_POSTER_MESSAGES:
// posterMessage();
start();
break;
case UserConsole.COM_LIRE_MESSAGES:
// lireMessage();
start();
break;
case UserConsole.COM_STOP:
ui.afficher("Au revoir ");
// Memoire.save(registre, "sauvegarde.txt");
System.exit(0);
break;
default:
ui.afficher("La commande sp<73>cifi<66>e n'existe pas\n");
Thread.sleep(1000);
start();
}
}
private void creerForum() {
String nomForum = ui.getValeur("Nom du forum :");
registreF.addForum(nomForum);
}
private void creerCanal() {
String nomForum = ui.getValeur("Entrer le nom du forum dans lequel vous voulez cr<63>er un canal :");
while (!GestionnaireForum.doesExist(nomForum)) {
System.out.println("Erreur : Il n'y a aucun forum de ce nom.");
nomForum = ui.getValeur("Entrer le nom du forum dans lequel vous voulez cr<63>er un canal :");
}
String typeCanal;
System.out.println("Quel type de canal voulez-vous cr<63>er ?");
typeCanal = ui.getValeur("Entrer \"c\" pour canal ou \"b\" pour canal de br<62>ves");
while (!(typeCanal.contentEquals("c") || typeCanal.contentEquals("b"))) {
System.out.println("Erreur : donn<6E>e invalide.");
typeCanal = ui.getValeur("Quel type de canal voulez-vous cr<63>er ?");
}
String nomCanal = ui.getValeur("Entrer le nom du canal");
if (typeCanal.contentEquals("c")) {
System.out.println("Voulez-vous changer le nombre de messages max possibles pour ce canal?");
String nb = ui.getValeur("R<EFBFBD>pondre y pour oui, n pour non");
try {
int maxMessage = Integer.parseInt(nb);
registreC.CreerCanal(nomCanal, maxMessage);
} catch (NumberFormatException nfe) {
System.out.println("Erreur, ce n'est pas un entier");
}
} else {
String nb = ui.getValeur("Quelle taille max voulez-vous pour les br<62>ves?");
try {
int tailleBreve = Integer.parseInt(nb);
registreC.CreerCanalDeBreve(nomCanal, tailleBreve);
} catch (NumberFormatException nfe) {
System.out.println("Erreur, ce n'est pas un entier");
}
}
}
public static void main(String[] args) throws Exception {
Controleur c = new Controleur();
c.start();
}
}

17
src/forum/Forum.java Executable file
View File

@@ -0,0 +1,17 @@
package forum;
public class Forum {
private String title;
private CanalParDefaut defaultCanal;
public Forum(String nomForum) {
this.title = nomForum;
this.defaultCanal = new CanalParDefaut("defaut");
}
public String getTitle() {
return title;
}
}

View File

@@ -0,0 +1,26 @@
package forum;
import java.util.HashMap;
public class GestionnaireCanal {
private static HashMap<String, Canal> canal = new HashMap<String, Canal>();
private static HashMap<String, CanalDeBreve> canalDeBreve = new HashMap<String, CanalDeBreve>();
public void CreerCanal(String nomCanal, int maxMessage) {
canal.put(nomCanal, new Canal(nomCanal, maxMessage));
}
public void CreerCanalDeBreve(String nomCanal, int tailleBreves) {
canalDeBreve.put(nomCanal, new CanalDeBreve(nomCanal, tailleBreves));
}
public static boolean doesExist(String nomCanal) {
if (canal.containsKey(nomCanal)) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,29 @@
package forum;
import java.util.HashMap;
public class GestionnaireForum {
private static HashMap<String, Forum> forum = new HashMap<String, Forum>();
public Forum getForum(String nomForum) {
return forum.get(nomForum);
}
public void addForum(String nomForum) {
if (!doesExist(nomForum)) {
forum.put(nomForum, new Forum(nomForum));
} else {
System.out.println("erreur : Un forum du m<>me nom existe d<>j<EFBFBD>.");
}
}
public static boolean doesExist(String nom) {
if (forum.containsKey(nom)) {
return true;
}
return false;
}
}

52
src/forum/Memoire.java Executable file
View File

@@ -0,0 +1,52 @@
package forum;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Based on http://www.jmdoudoux.fr/java/dej/chap-serialisation.htm
*
* @author Mireille Blay
*
*/
public class Memoire {
static Logger monLog = Logger.getLogger(Memoire.class.getName());
private Memoire() {
super();
}
public static void save(Object o, String fileName) {
try (FileOutputStream fichier = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fichier);) {
oos.writeObject(o);
oos.flush();
} catch (java.io.IOException e) {
monLog.log(Level.SEVERE, e.getMessage(), e);
}
}
public static Object read(String fileName) {
Object o = null;
try (FileInputStream fichier = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fichier);) {
o = ois.readObject();
} catch ( java.io.FileNotFoundException e) {
monLog.log(Level.SEVERE, "Pas de precedentes sauvegardes",e);
} catch (final java.io.IOException e) {
monLog.log(Level.SEVERE, "Pbme de fichier",e);
} catch (final ClassNotFoundException e) {
monLog.log(Level.SEVERE, "Pbme de sauvegarde, classe inattendue",e);
}
return o;
}
}

7
src/forum/Message.java Executable file
View File

@@ -0,0 +1,7 @@
package forum;
public class Message {
private String contenu;
}

15
src/forum/Producteur.java Executable file
View File

@@ -0,0 +1,15 @@
package forum;
import java.util.ArrayList;
public class Producteur extends Administrateur {
public String nom;
public ArrayList<Canal> canal = new ArrayList<Canal> ();
public Producteur() {
super();
// TODO Auto-generated constructor stub
}
}

80
src/forum/UserConsole.java Executable file
View File

@@ -0,0 +1,80 @@
package forum;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class UserConsole {
Scanner sc = new Scanner(System.in);
public static final char COM_CREER_FORUM = 'f';
public static final char COM_CREER_CANAL = 'c';
public static final char COM_LIRE_MESSAGES = 'l';
public static final char COM_POSTER_MESSAGES = 'p';
public static final char COM_STOP = 's';
//On pourra modifier facilement pour par exemple utiliser des logger.
private final void sop(String s) {
System.out.println(s);
}
public String lireCommande() {
sop("------- COMMANDES ----------");
sop("creer Forum : " + COM_CREER_FORUM ) ;
sop("creer Canal : " + COM_CREER_CANAL);
sop("lire messages : " + COM_LIRE_MESSAGES);
sop("poster un nouveau message : " + COM_POSTER_MESSAGES);
sop("stop : " + COM_STOP);
sop("Que voulez-vous faire ?");
String str = sc.nextLine().toLowerCase();
sop("Vous avez saisi la commande: " + str);
return str;
}
public void afficher(String str) {
sop(str);
}
public void afficherMessages(List<Message> arrayList) {
int i = 1;
sop("\t messages : ");
if (arrayList == null) {
sop("\t Pas de messages ");
} else
for (Message m : arrayList) {
sop("\t" + i + "-\t" + m);
i++;
}
}
public String getNomDuForum(Set<String> nomsForum) {
sop("--- Forum disponibles --- ");
afficheListe(nomsForum);
sop("==> Nom du Forum ?");
return sc.nextLine();
}
public void afficheListe(Set<String> noms) {
for (String nom : noms)
sop("\t"+ nom);
}
public String getNomCanal(Set<String> nomsCanaux) {
sop("--- Canals disponibles --- ");
afficheListe(nomsCanaux);
sop("==> Nom du Canal ?");
return sc.nextLine();
}
public String getValeur(String message) {
sop(message);
return sc.nextLine();
}
public String write(){
return sc.nextLine();
}
}

View File

@@ -0,0 +1,18 @@
package openClosedPrinciples.core;
/**
* @author Mireille Blay-Fornarino
*
*/
public class AlreadyBooked extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public AlreadyBooked(String message) {
super(message);
}
}

View File

@@ -0,0 +1,14 @@
package openClosedPrinciples.core;
public class AucunItemCorrespondant extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public AucunItemCorrespondant(String message) {
super(message);
}
}

View File

@@ -0,0 +1,50 @@
package openClosedPrinciples.core;
/**
* @author Mireille Blay-Fornarino
*
*/
public class Car {
private String numberPlate;
private double dayPrice;
/// Constructeurs
public Car(String numberPlate, double dayPrice) {
super();
this.numberPlate = numberPlate;
this.dayPrice = dayPrice;
}
/// Accesseurs et mutateurs
public String getNumberPlate() {
return numberPlate;
}
public void setNumberPlate(String numberPlate) {
this.numberPlate = numberPlate;
}
public double getDayPrice() {
return dayPrice;
}
public void setDayPrice(double dayPrice) {
this.dayPrice = dayPrice;
}
/// Méthodes
// Afficher
@Override
public String toString() {
return "Car [numberPlate=" + numberPlate + // ", rentals=" + rentals +
", dayPrice=" + super.toString() + "]";
}
}

View File

@@ -0,0 +1,77 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
/**
* @author Mireille Blay-Fornarino
*
* 6 oct. 2018
*/
public class CarRental extends PayingItem {
private String carNumber;
private int duration;
private LocalDate beginDate;
/// Constructeurs
private CarRental(String carNumber, double dayPrice, int duration, LocalDate beginDate) {
super(dayPrice);
this.carNumber = carNumber;
this.duration = duration;
this.beginDate = beginDate;
}
public CarRental(Car c, LocalDate beginDate, int duration) {
//On considere que le prix de la location ne doit plus bouger même si le prix de la voiture change
this(c.getNumberPlate(),c.getDayPrice(),duration,beginDate);
}
/// Accesseurs et mutateurs
public String getCarNumber() {
return carNumber;
}
public void setCarNumber(String carNumber) {
this.carNumber = carNumber;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public LocalDate getBeginDate() {
return beginDate;
}
public void setBeginDate(LocalDate beginDate) {
this.beginDate = beginDate;
}
/// Méthodes
// Récupérer le prix
public double getPrice() {
return super.price*duration;
}
// Rechercher si dispo un jour
public boolean includeADate(LocalDate[] dates) {
for (LocalDate d : dates) {
if (d.equals(beginDate))
return true;
if ( (d.isAfter(beginDate)) &&
(d.isBefore(beginDate.plusDays(duration) ) ) )
return true;
}
return false;
}
// Afficher
@Override
public String toString() {
return "CarRental [carNumber=" + carNumber.toString() + ", duration=" + duration + ", beginDate=" + beginDate + ", price=" +super.toString() + "]";
}
}

View File

@@ -0,0 +1,77 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* @author Mireille Blay-Fornarino
*
* 6 oct. 2018
*/
public class CarRentalService extends Service<CarRental> {
private ArrayList<Car> cars;
/// Constructeurs
public CarRentalService(ArrayList<Car> cars) {
super(new ArrayList<CarRental>());
this.cars = cars;
}
/// Méthodes
// Récupérer la liste des voitures dispo tel date et telle durée
public List<Car> getAvailableCars(LocalDate d, int duration) {
ArrayList<Car> availableCars = new ArrayList<>();
LocalDate[] dates = DateTools.getDays(d, duration);
for (Car c : cars) {
if (isAvailable(c, dates)) {
availableCars.add(c);
}
}
return availableCars;
}
// On voit si une voiture est dispo pendant ces dates
private boolean isAvailable(Car c, LocalDate[] dates) {
for (CarRental carRental : payingItemList) {
if (c.getNumberPlate().equals(carRental.getCarNumber()) &&
(carRental.includeADate(dates)) ) {
return false;
}
}
return true;
}
// On réserve une voiture
public CarRental book(Car c, LocalDate d, int duration) throws NotPossibleCarRentalException {
CarRental carRental = null;
if (cars == null || !(cars.contains(c)) )
throw new NotPossibleCarRentalException("Not known car");
LocalDate[] dates = DateTools.getDays(d, duration);
if (isAvailable(c, dates)) {
carRental = new CarRental(c, d, duration);
payingItemList.add(carRental);
}
return carRental;
}
// Recherche d'une voiture correspondant à la description
public CarRental find(Description description) {
List<Car> listeVoitures = this.getAvailableCars(description.getDateDepart(), description.getDuree());
listeVoitures.sort(Comparator.comparing(Car::getDayPrice));
CarRental cr = null;
try{
if(listeVoitures.isEmpty()) {
return null;
}
cr = this.book(listeVoitures.get(0), description.getDateDepart(), description.getDuree());
}catch(NotPossibleCarRentalException e) {
e.getMessage();
}
return cr;
}
}

View File

@@ -0,0 +1,37 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
/**
* Classe Utilitaire
*
*
* @author Mireille Blay-Fornarino
*
*
* 6 oct. 2018
*/
public final class DateTools {
private DateTools() {
throw new IllegalStateException("Utility class");
}
public static LocalDate addDays(LocalDate date, int nbJour) {
return date.plusDays(nbJour);
}
public static LocalDate[] getDays(LocalDate date, int nbJour) {
int i = 0;
LocalDate[] dates = new LocalDate[nbJour];
dates[i] = date;
i+=1;
while (i < nbJour) {
dates[i] = addDays(date,i);
i++;
}
return dates;
}
}

View File

@@ -0,0 +1,68 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
import java.util.Date;
public class Description {
private String depart;
private String destination;
private LocalDate dateDepart;
private int duree;
/// Constructeurs
// Vide
public Description() {
depart = null;
destination = null;
dateDepart = null;
duree = 0;
}
// Avec tout rempli
public Description(String depart, String destination, LocalDate dateDepart, int duree) {
this.depart = depart;
this.destination = destination;
this.dateDepart = dateDepart;
this.duree = duree;
}
/// Accesseurs et mutateurs
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getDepart() {
return depart;
}
public void setDepart(String depart) {
this.depart = depart;
}
public LocalDate getDateDepart() {
return dateDepart;
}
public void setDateDepart(LocalDate dateDepart) {
this.dateDepart = dateDepart;
}
public int getDuree() {
return duree;
}
public void setDuree(int duree) {
this.duree = duree;
}
}

View File

@@ -0,0 +1,92 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Random;
/**
* @author Mireille Blay-Fornarino
*
* 6 oct. 2018
*/
public class Flight extends PayingItem {
private LocalDate departDate;
private String departAirport;
private String arrivalAirport;
private LocalTime departTime;
/// Constructeurs
public Flight(String departAirport) {
this(-1, LocalDate.now(), LocalTime.now(), departAirport, "Paris");
}
public Flight(double price, LocalDate departDate, LocalTime departTime, String departAirport, String arrivalAirport) {
super(price);
this.departDate = departDate;
this.departAirport = departAirport;
this.arrivalAirport = arrivalAirport;
this.departTime= departTime;
}
/// Accesseurs et mutateurs
public LocalTime getDepartTime() {
return departTime;
}
public void setDepartTime(LocalTime departTime) {
this.departTime = departTime;
}
public LocalDate getDepartDate() {
return departDate;
}
public void setDepartDate(LocalDate departDate) {
this.departDate = departDate;
}
public String getDepartAirport() {
return departAirport;
}
public void setDepartAirport(String departAirport) {
this.departAirport = departAirport;
}
public String getArrivalAirport() {
return arrivalAirport;
}
public void setArrivalAirport(String arrivalAirport) {
this.arrivalAirport = arrivalAirport;
}
public void setPrice(double price) {
super.setPrice(price);
}
public double getPrice() {
if (super.price == -1) {
double start = 10;
double end = 1000;
double random = new Random().nextDouble();
super.setPrice(start + (random * (end - start)));
}
return super.price;
}
/// Méthodes
// On voit si le vol correspond à celui entré en paramètres
public boolean match(LocalDate d, String from, String to) {
return getDepartDate().equals(d) && getDepartAirport().equals(from) && getArrivalAirport().equals(to);
}
// Affichage
@Override
public String toString() {
return "Flight [price=" + super.toString() + ", departDate=" + departDate + ", departAirport=" + departAirport
+ ", arrivalAirport=" + arrivalAirport + ", departTime=" + departTime + "]";
}
}

View File

@@ -0,0 +1,50 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Mireille Blay-Fornarino
*
* 6 oct. 2018
*/
public class FlightService extends Service<Flight> {
/// Constructeurs
public FlightService(ArrayList<Flight> flights) {
super(flights);
}
/// Méthodes
// Récupérer les vols de cette date
public List<Flight> getFlights(LocalDate d) {
Stream<Flight> parallelStream = super.getpayingItemList().parallelStream();
Stream<Flight> results = parallelStream.filter(f -> (f.getDepartDate().equals(d)) ) ;
return results.collect(Collectors.toCollection(ArrayList::new));
}
// Récupérer les vols de cette date + lieux départ et destination
public ArrayList<Flight> getFlights(LocalDate d, String from, String to) {
Stream<Flight> parallelStream = super.getpayingItemList().parallelStream();
Stream<Flight> results = parallelStream.filter(f ->
f.match(d, from, to)) ;
return results.collect(Collectors.toCollection(ArrayList::new));
}
// Recherche d'un vol correspondant à la description
public Flight find(Description description) {
ArrayList<Flight> listeVols = this.getFlights(description.getDateDepart(), description.getDepart(), description.getDestination());
listeVols.sort(Comparator.comparing(Flight::getPrice));
if(listeVols.isEmpty()) {
return null;
}
return listeVols.get(0);
}
}

View File

@@ -0,0 +1,112 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Scanner;
public class GestionnaireVoyages {
private static TravelOrganizer to = new TravelOrganizer();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//// GESTION DU VOYAGE CHOISI PAR L'UTILISATEUR
/// On récupère le départ
System.out.println("De où partez-vous ?");
String depart = sc.nextLine();
/// On récupère la destination
System.out.println("Où voulez-vous aller ?");
String destination = sc.nextLine();
/// On récupère la durée du voyage
System.out.println("Combien de temps voulez-vous partir?");
int duree = Integer.parseInt(sc.nextLine());
//Date (non demandée par l'utilisateur)
LocalDate ld = LocalDate.of(2019, Month.OCTOBER, 18);
//Date pour tester
LocalDate ldr = LocalDate.of(2019, Month.JUNE, 18);
LocalTime lt = LocalTime.now();
//Description du voyage de l'utilisateur
Description d = new Description(depart, destination, ld, duree);
/// GESTION DES VOLS
// Première compagnie de vols
Flight f1 = new Flight(350, ld, lt, depart, destination);
Flight f2 = new Flight(100, ld, lt, depart, destination); // moins cher
Flight f3 = new Flight(56, ld, lt, "Cannes", destination); // n'a pas le bon départ
ArrayList<Flight> flights1 = new ArrayList<>();
flights1.add(f1);
flights1.add(f2);
flights1.add(f3);
FlightService fs1 = new FlightService(flights1);
to.addAirlineCompany(fs1);
// Deuxième compagnie de vols
Flight f4 = new Flight(20, ld, lt, depart, "Tokyo"); // n'a pas la bonne destination
Flight f5 = new Flight(22, ldr, lt, depart, destination); // n'a pas la bonne date
ArrayList<Flight> flights2 = new ArrayList<>();
flights2.add(f4);
flights2.add(f5);
FlightService fs2 = new FlightService(flights2);
to.addAirlineCompany(fs2);
/// GESTION DES LOCATIONS DE VOITURES
// Première compagnie qui contiendra 3 voitures
Car c1 = new Car("111", 10); //sera réservée plus tard
Car c2 = new Car("222", 15);
Car c3 = new Car("333", 30); //sera réservée plus tard
ArrayList<Car> cs1 = new ArrayList<>();
cs1.add(c1);
cs1.add(c2);
cs1.add(c3);
CarRentalService crs1 = new CarRentalService(cs1);
to.addCarRentCompany(crs1);
// Deuxième compagnie qui contiendra 2 voitures S
Car c4 = new Car("444", 4); //voiture la moins chère, mais sera réservée plus tard
Car c5 = new Car("555", 50);
ArrayList<Car> cs2 = new ArrayList<>();
cs2.add(c4);
cs2.add(c5);
CarRentalService crs2 = new CarRentalService(cs2);
to.addCarRentCompany(crs2);
try {
// On réserve 3 voitures
crs1.book(c1, ld, duree);
crs1.book(c3, ld, duree);
crs2.book(c4, ld, duree);
} catch (NotPossibleCarRentalException e) {
System.out.println(e.getMessage());
}
try {
Trip voyageChoisi = to.createATrip(d);
//Affichage du meilleur vol
System.out.println("Le meilleur vol pour partir de "+ depart +" et arriver à " + destination +
" le 18/10/2019 est : \n\t" + voyageChoisi.getItems().get(0));
//Affichage de la meilleure location de voiture
System.out.println("La meilleure voiture à louer pour une durée de " + duree +
" jours à partir du " + ld +" est : \n\t" + voyageChoisi.getItems().get(1));
} catch(AucunItemCorrespondant e) {
System.out.println(e.getMessage());
}
}
}

View File

@@ -0,0 +1,19 @@
package openClosedPrinciples.core;
/**
* @author Mireille Blay-Fornarino
*
* 6 oct. 2018
*/
public class NotPossibleCarRentalException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public NotPossibleCarRentalException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,30 @@
package openClosedPrinciples.core;
public abstract class PayingItem {
protected double price;
/// Constructeurs
public PayingItem(double price) {
this.price = price;
}
/// Accesseurs et mutateurs
// Méthode abstraite parce que le calcul du prix n'est pas le même pour une voiture et pour une vol
public abstract double getPrice();
public void setPrice(double price) {
this.price = price;
}
/// Méthodes
// Affichage
@Override
public String toString() {
return "" + price;
}
}

View File

@@ -0,0 +1,46 @@
package openClosedPrinciples.core;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public abstract class Service<T extends PayingItem>{
protected List<T> payingItemList = new ArrayList<>();
/// Constructeurs
public Service(List<T> payingItemList) {
this.payingItemList = payingItemList;
}
/// Accesseur
protected List<T> getpayingItemList(){
return payingItemList;
}
/// Méthodes
// Trier la liste d'item par prix
public List<T> sortedByPrice() {
payingItemList.sort(Comparator.comparing(PayingItem::getPrice));
return payingItemList;
}
// Récupérer l'item le moins cher
public T lessExpensiveItem(){
sortedByPrice();
return payingItemList.get(0);
}
// Ajouter un item à la liste
public void add(T payingItem) {
payingItemList.add(payingItem);
}
// Trouver
public abstract T find(Description description) throws AucunItemCorrespondant;
}

View File

@@ -0,0 +1,99 @@
package openClosedPrinciples.core;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class TravelOrganizer {
List<FlightService> airlinesCompanies;
List<CarRentalService> carRentCompanies;
/// Constructeurs
public TravelOrganizer() {
airlinesCompanies = new ArrayList<>();
carRentCompanies = new ArrayList<>();
}
/// Accesseurs et mutateurs
public List<FlightService> getAirlinesCompanies() {
return airlinesCompanies;
}
public void setAirlinesCompanies(List<FlightService> airlinesCompanies) {
this.airlinesCompanies = airlinesCompanies;
}
public List<CarRentalService> getCarRentCompanies() {
return carRentCompanies;
}
public void setCarRentCompanies(List<CarRentalService> carRentCompanies) {
this.carRentCompanies = carRentCompanies;
}
/// Méthodes
// Ajouter une compagnie aérienne
public void addAirlineCompany(FlightService company) {
airlinesCompanies.add(company);
}
// Ajouter une compagnie de location de voitures
public void addCarRentCompany(CarRentalService company) {
carRentCompanies.add(company);
}
// Créer un voyage
public Trip createATrip(Description description) throws AucunItemCorrespondant {
Trip t = new Trip(description);
Flight f = this.findFlight(description);
CarRental cr = this.findCar(description);
if(f!=null && cr!=null) {
t.addItem(f);
t.addItem(cr);
}else {
throw new AucunItemCorrespondant("Aucun voyage ne correspond aux critères recherchés.");
}
return t;
}
// Recherche un vol
public Flight findFlight(Description description) throws AucunItemCorrespondant {
List<Flight> flights = new ArrayList();
for(FlightService fs : airlinesCompanies) {
Flight f = fs.find(description);
if(f != null)
flights.add(f);
}
flights.sort(Comparator.comparing(Flight::getPrice));
if(flights.isEmpty()) {
throw new AucunItemCorrespondant("Aucun vol correspondant à votre recherche.");
}
return flights.get(0);
}
// Recherche une voiture
public CarRental findCar(Description description) throws AucunItemCorrespondant {
List<CarRental> cars = new ArrayList();
for(CarRentalService c : carRentCompanies) {
CarRental cr = c.find(description);
if(cr!=null)
cars.add(cr);
}
cars.sort(Comparator.comparing(CarRental::getPrice));
if(cars.isEmpty()) {
throw new AucunItemCorrespondant("Aucune location de voiture correspondant à votre recherche.");
}
return cars.get(0);
}
}

View File

@@ -0,0 +1,49 @@
package openClosedPrinciples.core;
import java.util.ArrayList;
import java.util.List;
public class Trip {
private Description description;
private List<PayingItem> items;
/// Constructeurs
// Vide
public Trip() {
description = null;
items = new ArrayList();
}
// Avec la description
public Trip(Description description) {
this.description = description;
items = new ArrayList();
}
/// Accesseurs et mutateurs
public Description getDescription() {
return description;
}
public void setDescription(Description description) {
this.description = description;
}
public List<PayingItem> getItems() {
return items;
}
public void setItems(List<PayingItem> items) {
this.items = items;
}
/// Méthodes
public void addItem(PayingItem item) {
items.add(item);
}
}

26
src/td5/p1/Launch.java Normal file
View File

@@ -0,0 +1,26 @@
package td5.p1;
import td5.p1.personnage.Orc;
import td5.p1.personnage.Tauren;
public class Launch {
public static void main(String[] args) {
Tauren diablon = new Tauren("Diablon", 15);
Orc azag = new Orc("Azag", 5);
diablon.attack(azag);
azag.attack(diablon);
azag.setHp(15);
System.out.println(azag.getState());
System.out.println(diablon.getState());
}
}

View File

@@ -0,0 +1,37 @@
package td5.p1;
import td5.p1.arme.*;
public class ModernWeaponFactory extends WeaponFactory {
public ModernWeaponFactory() {
super();
}
public Arme createWeapon(String t, String n) {
Arme a;
switch (t) {
case "Epee":
a = new Epée(n);
break;
case "Dague":
a = new Dague(n);
break;
case "Bouclier":
a = new Bouclier(n);
break;
case "Fusil":
a = new Fusil(n);
break;
default:
a = null;
break;
}
super.ajoute(a);
return a;
}
public Arme getWeapon(String n) {
return super.getWeapon(n);
}
}

View File

@@ -0,0 +1,74 @@
package td5.p1;
import java.util.ArrayList;
import td5.p1.arme.*;
public class WeaponFactory {
private static ArrayList<Arme> l = new ArrayList<Arme>();
public WeaponFactory() {
Arme d = new Arme("Arme1");
l.add(d);
}
public Arme createWeapon(String t, String n) {
Arme a;
switch (t) {
case "SWORD":
a = new Epée(n);
break;
case "DAG":
a = new Dague(n);
break;
case "SHIELD":
a = new Bouclier(n);
break;
default:
a = new Arme(n);
break;
}
l.add(a);
return a;
}
public Arme getWeapon(String n) {
boolean trouve = false;
int i = 0;
if (l.isEmpty()) {
return null;
} else {
while (!trouve) {
l.get(i);
if (i < l.size()) {
if (l.get(i).getNom().equals(n)) {
trouve = true;
return l.get(i);
}
i++;
} else {
return null;
}
}
}
return null;
}
// ==========================================================================
public ArrayList<Arme> getL() {
return l;
}
public void setL(ArrayList<Arme> l) {
this.l = l;
}
public void ajoute(Arme a) {
l.add(a);
}
}

74
src/td5/p1/arme/Arme.java Normal file
View File

@@ -0,0 +1,74 @@
package td5.p1.arme;
public class Arme {
private int force;
private int protection;
private String nom;
public Arme() {
this(0, 0, null);
}
public Arme(String n) {
this(0, 0, n);
}
public Arme(int f, int p, String n) {
this.setForce(f);
this.setProtection(p);
this.setNom(n);
}
@Override
public String toString() {
return this.nom;
}
public int getForce() {
return force;
}
public void setForce(int force) {
this.force = force;
}
public int getProtection() {
return protection;
}
public void setProtection(int protection) {
this.protection = protection;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Arme other = (Arme) obj;
if (force != other.force)
return false;
if (nom == null) {
if (other.nom != null)
return false;
} else if (!nom.equals(other.nom))
return false;
if (protection != other.protection)
return false;
return true;
}
}

View File

@@ -0,0 +1,14 @@
package td5.p1.arme;
public class Bouclier extends Arme {
public Bouclier() {
this("Bouclier");
}
public Bouclier(String n) {
super(5, 20, n);
}
}

View File

@@ -0,0 +1,13 @@
package td5.p1.arme;
public class Dague extends Arme {
public Dague() {
this("Dague");
}
public Dague(String n) {
super(20, 10, n);
}
}

View File

@@ -0,0 +1,13 @@
package td5.p1.arme;
public class Epée extends Arme {
public Epée() {
this("Epée");
}
public Epée(String n) {
super(25, 5, n);
}
}

View File

@@ -0,0 +1,14 @@
package td5.p1.arme;
public class Fusil extends Arme {
public Fusil() {
this("Fusil");
}
public Fusil(String n) {
super(30, 1, n);
}
}

View File

@@ -0,0 +1,24 @@
package td5.p1.etat;
import td5.p1.personnage.Personnage;
public class Faible extends PlayerState {
public Faible(Personnage p) {
super(p);
}
public void attack(Personnage p) {
int damage = player.getWeapon().getForce() - p.getWeapon().getProtection() - (1 - 1/p.getHp());
if(damage != 0) {
System.out.print(player.getNom() + player.vie() + " a attaqué " + p.getNom() + p.vie() + ".");
p.getDamage(damage);
System.out.println(" " + p.getNom() + " a perdu " + damage + " HP" + p.vie() + "!");
} else {
System.out.println(player.getNom() + " a attaqué " + p.getNom() + ". " + p.getNom() + " n'a pris aucun dégats.");
}
}
}

17
src/td5/p1/etat/Mort.java Normal file
View File

@@ -0,0 +1,17 @@
package td5.p1.etat;
import td5.p1.personnage.Personnage;
public class Mort extends PlayerState {
public Mort(Personnage p) {
super(p);
}
public void attack(Personnage p) {
}
}

View File

@@ -0,0 +1,41 @@
package td5.p1.etat;
import td5.p1.personnage.Personnage;
public class PlayerState {
protected Personnage player;
public PlayerState(Personnage p) {
this.player = p;
}
public void attack(Personnage p) {
}
public void checkState(Personnage p) {
checkAlive(p);
checkFaible(p);
checkMort(p);
}
protected static void checkMort(Personnage p) {
if(p.getHp() <= 0 ) {
p.setState(new Mort(p));
}
}
protected static void checkFaible(Personnage p) {
if((p.getHp() <= 25) && (p.getHp() > 0)) {
p.setState(new Faible(p));
}
}
protected static void checkAlive(Personnage p) {
if(p.getHp() >= 25) {
p.setState(new Vivant(p));
}
}
}

View File

@@ -0,0 +1,24 @@
package td5.p1.etat;
import td5.p1.personnage.Personnage;
public class Vivant extends PlayerState {
public Vivant(Personnage p) {
super(p);
}
public void attack(Personnage p) {
int damage = player.getWeapon().getForce() - p.getWeapon().getProtection();
if(damage != 0) {
System.out.print(player.getNom() + player.vie() + " a attaqué " + p.getNom() + p.vie() + ".");
p.getDamage(damage);
System.out.println(" " + p.getNom() + " a perdu " + damage + " HP" + p.vie() + "!");
} else {
System.out.println(player.getNom() + " a attaqué " + p.getNom() + ". " + p.getNom() + " n'a pris aucun dégats.");
}
}
}

View File

@@ -0,0 +1,27 @@
package td5.p1.personnage;
import td5.p1.arme.Epée;
public class Humain extends Personnage {
private String eyeColor;
public Humain() {
this(null, null);
}
public Humain(String n, String c) {
super(n);
this.setEyeColor(c);
super.setWeapon(new Epée());
}
public String getEyeColor() {
return this.eyeColor;
}
public void setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
}
}

View File

@@ -0,0 +1,27 @@
package td5.p1.personnage;
import td5.p1.arme.Epée;
public class Orc extends Personnage {
private int earSize;
public Orc() {
this(null, 0);
}
public Orc(String n, int e) {
super(n);
this.setEarSize(e);;
super.setWeapon(new Epée());
}
public int getEarSize() {
return earSize;
}
public void setEarSize(int earSize) {
this.earSize = earSize;
}
}

View File

@@ -0,0 +1,86 @@
package td5.p1.personnage;
import td5.p1.arme.Arme;
import td5.p1.etat.*;
public class Personnage {
private int hp;
private String nom;
private Arme weapon;
private PlayerState state = new Vivant(this);
public Personnage() {
this("DefaultCharater");
}
public Personnage(String n) {
this.setNom(n);
this.setHp(100);
}
public void attack(Personnage p) {
/**
* int damage = this.getWeapon().getForce() - p.getWeapon().getProtection();
if(damage != 0) {
System.out.print(this.getNom() + this.vie() + " a attaqué " + p.getNom() + p.vie() + ".");
p.getDamage(damage);
System.out.println(" " + p.getNom() + " a perdu " + damage + " HP" + p.vie() + "!");
} else {
System.out.println(this.getNom() + " a attaqué " + p.getNom() + ". " + p.getNom() + " n'a pris aucun dégats.");
}
*/
}
public void getDamage(int a) {
this.setHp(this.hp - a);
}
public String vie() {
return " (" + this.getHp() + "/100 HP)";
}
//======================================================================================================
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public Arme getWeapon() {
return weapon;
}
public void setWeapon(Arme weapon) {
this.weapon = weapon;
}
public Object getArme() {
return this.getWeapon();
}
public PlayerState getState() {
return state;
}
public void setState(PlayerState s) {
this.state = s;
}
}

View File

@@ -0,0 +1,26 @@
package td5.p1.personnage;
import td5.p1.arme.Bouclier;
public class Tauren extends Personnage {
private int hornSize;
public Tauren() {
this(null, 0);
}
public Tauren(String n, int c) {
super(n);
this.setHornSize(c);
super.setWeapon(new Bouclier());
}
public int getHornSize() {
return hornSize;
}
public void setHornSize(int hornSize) {
this.hornSize = hornSize;
}
}

View File

@@ -0,0 +1,26 @@
package td5.p1.personnage;
import td5.p1.arme.Dague;
public class Troll extends Personnage {
private String favouriteBeer;
public Troll() {
this(null, null);
}
public Troll(String n, String b) {
super(n);
this.setFavouriteBeer(b);
super.setWeapon(new Dague());
}
public String getFavouriteBeer() {
return favouriteBeer;
}
public void setFavouriteBeer(String favouriteBeer) {
this.favouriteBeer = favouriteBeer;
}
}

BIN
src/td5/p1/td5p1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB