Просмотр исходного кода

Trying to understand Rust's borrowing, lifetimes and ownership

Denis Merigoux лет назад: 9
Родитель
Сommit
37e53e42e0
4 измененных файлов с 64 добавлено и 64 удалено
  1. 14 20
      src/deck.rs
  2. 43 39
      src/game.rs
  3. 7 4
      src/main.rs
  4. 0 1
      src/params.rs

+ 14 - 20
src/deck.rs

3
 use rand::{thread_rng, Rng};
3
 use rand::{thread_rng, Rng};
4
 use std::collections::BTreeSet;
4
 use std::collections::BTreeSet;
5
 
5
 
6
-pub type Deck = [card::Card; params::DECK_SIZE];
7
-pub type Hand = (i32, BTreeSet<card::Card>);
6
+pub type Deck = Vec<card::Card>;
7
+pub type Hand = BTreeSet<card::Card>;
8
 
8
 
9
-// Creates a deck_size cards tarot deck, shuffled
9
+// Creates a tarot deck, shuffled
10
 pub fn new_deck() -> Deck {
10
 pub fn new_deck() -> Deck {
11
-    let mut deck: [card::Card; params::DECK_SIZE] = [card::Card::Fool; params::DECK_SIZE];
12
-    let mut counter = 0;
11
+    let mut deck: Vec<card::Card> = Vec::new();
13
     for suit in card::Suit::values() {
12
     for suit in card::Suit::values() {
14
         for symbol in card::Symbol::values() {
13
         for symbol in card::Symbol::values() {
15
-            deck[counter] = card::Card::Face(card::Face {
14
+            deck.push(card::Card::Face(card::Face {
16
                 suit: suit,
15
                 suit: suit,
17
                 symbol: symbol,
16
                 symbol: symbol,
18
-            });
19
-            counter += 1
17
+            }));
20
         }
18
         }
21
     }
19
     }
22
     for trump in card::Trump::values() {
20
     for trump in card::Trump::values() {
23
-        deck[counter] = card::Card::Trump(trump);
24
-        counter += 1
21
+        deck.push(card::Card::Trump(trump));
25
     }
22
     }
26
-    deck[counter] = card::Card::Fool;
23
+    deck.push(card::Card::Fool);
27
     let mut rng = thread_rng();
24
     let mut rng = thread_rng();
28
     rng.shuffle(&mut deck);
25
     rng.shuffle(&mut deck);
29
     deck
26
     deck
30
 }
27
 }
31
 
28
 
32
 // Distributes the deck between the four players and the dog
29
 // Distributes the deck between the four players and the dog
33
-pub fn distribute_cards(deck: Deck) -> (Hand, [Hand; params::NUMBER_OF_PLAYERS]) {
34
-    let (_, mut dog): Hand = (-1, BTreeSet::new());
35
-    let mut hands: [Hand; params::NUMBER_OF_PLAYERS] =
36
-        [(0, BTreeSet::new()), (1, BTreeSet::new()), (2, BTreeSet::new()), (3, BTreeSet::new())];
37
-    for i in 0..params::DECK_SIZE {
30
+pub fn distribute_cards(deck: &Deck) -> (Hand, Vec<Hand>) {
31
+    let mut dog: Hand = BTreeSet::new();
32
+    let mut hands: Vec<Hand> = Vec::new();
33
+    for i in 0..deck.len() {
38
         if i < params::DOG_SIZE {
34
         if i < params::DOG_SIZE {
39
             dog.insert(deck[i]);
35
             dog.insert(deck[i]);
40
         } else {
36
         } else {
41
-            hands[(i / params::CARDS_PER_DISTRIBUTION) % params::NUMBER_OF_PLAYERS]
42
-                .1
43
-                .insert(deck[i]);
37
+            hands[(i / params::CARDS_PER_DISTRIBUTION) % params::NUMBER_OF_PLAYERS].insert(deck[i]);
44
         }
38
         }
45
     }
39
     }
46
-    ((-1, dog), hands)
40
+    (dog, hands)
47
 }
41
 }

+ 43 - 39
src/game.rs

4
 use std::collections::BTreeSet;
4
 use std::collections::BTreeSet;
5
 
5
 
6
 type Heap = Vec<card::Card>;
6
 type Heap = Vec<card::Card>;
7
+pub struct Player {
8
+    pub id: i32,
9
+    pub name: String,
10
+    pub hand: deck::Hand,
11
+}
12
+
13
+pub fn initialize_players(hands: &mut Vec<deck::Hand>, names: &mut Vec<String>) -> Vec<Player> {
14
+    if hands.len() != names.len() {}
15
+    let mut counter = 0;
16
+    let mut players = Vec::new();
17
+    for i in 0..hands.len() {
18
+        let name = match names.pop() {
19
+            Some(name) => name,
20
+            None => panic!("the number of hands is different from the number of players"),
21
+        };
22
+        let hand = match hands.pop() {
23
+            Some(hand) => hand,
24
+            None => panic!("the number of hands is different from the number of players"),
25
+        };
26
+        players.push(Player {
27
+            id: counter,
28
+            name: name,
29
+            hand: hand,
30
+        });
31
+        counter += 1;
32
+    }
33
+    players
34
+}
7
 
35
 
8
-pub fn start_game(dog: deck::Hand, hands: [deck::Hand; params::NUMBER_OF_PLAYERS]) {
9
-    let cards_per_player = hands[0].1.len();
36
+pub fn start_game(dog: &deck::Hand, players: &mut Vec<Player>) {
37
+    let cards_per_player = players[0].hand.len();
10
     //Check if all players have same number of cards
38
     //Check if all players have same number of cards
11
     for i in 1..params::NUMBER_OF_PLAYERS {
39
     for i in 1..params::NUMBER_OF_PLAYERS {
12
-        if cards_per_player != hands[i].1.len() {
40
+        if cards_per_player != players[i].hand.len() {
13
             panic!("the players don't have the same number of cards")
41
             panic!("the players don't have the same number of cards")
14
         }
42
         }
15
     }
43
     }
16
-    //If yes start the game
17
-    let starting_player = 0;
18
-    (1..cards_per_player).fold((starting_player, hands), |(starting_player, hands), _| {
19
-        //For each turn
20
-        let mut new_hands: [deck::Hand; params::NUMBER_OF_PLAYERS] = [(0, BTreeSet::new()),
21
-                                                                      (1, BTreeSet::new()),
22
-                                                                      (2, BTreeSet::new()),
23
-                                                                      (3, BTreeSet::new())];
24
-        let end_heap = hands.into_iter().enumerate().fold(Vec::new(), |heap, (i, hand)| {
25
-            // For each player
26
-            let (new_hand, new_heap) = play_card(hand.clone(), heap);
27
-            new_hands[i - starting_player % params::NUMBER_OF_PLAYERS] = new_hand;
28
-            new_heap
29
-        });
30
-        let new_starting_player = winning_card(end_heap.clone());
31
-        println!("Les joueurs ont joué : {:?}", end_heap);
32
-        (new_starting_player, new_hands)
33
-    });
44
+    for i in 0..cards_per_player {
45
+        for player in players.iter_mut() {}
46
+    }
47
+    unimplemented!();
34
 }
48
 }
35
 
49
 
36
-fn play_card((player, hand): deck::Hand, cards_played: Heap) -> (deck::Hand, Heap) {
37
-    let valid_cards = valid_cards((player, hand.clone()), cards_played.clone());
38
-    let card_to_play = select_card(valid_cards, cards_played.clone());
39
-    println!("Card to play: {:?}", card_to_play.clone());
40
-    let mut new_hand = hand.clone();
41
-    new_hand.take(&card_to_play);
42
-    let mut new_cards_played = cards_played.clone();
43
-    new_cards_played.push(card_to_play);
44
-    ((player, new_hand), new_cards_played)
50
+fn play_card(player: &mut Player, cards_played: &mut Heap) {
51
+    unimplemented!();
45
 }
52
 }
46
 
53
 
47
-fn valid_cards(hand: deck::Hand, cards_played: Heap) -> deck::Hand {
48
-    hand
54
+fn valid_cards(hand: &deck::Hand, cards_played: &Heap) -> deck::Hand {
55
+    unimplemented!();
49
 }
56
 }
50
 
57
 
51
-fn select_card((player, valid_cards): deck::Hand, cards_played: Heap) -> card::Card {
52
-    match valid_cards.into_iter().next() {
53
-        Some(card) => card,
54
-        None => panic!("there is no valid card to play"),
55
-    }
58
+fn select_card(player: &Player, cards_played: &Heap) -> card::Card {
59
+    unimplemented!();
56
 }
60
 }
57
 
61
 
58
-fn winning_card(cards: Heap) -> usize {
59
-    0
62
+fn winning_card(cards: &Heap) -> usize {
63
+    unimplemented!();
60
 }
64
 }

+ 7 - 4
src/main.rs

11
 
11
 
12
 fn main() {
12
 fn main() {
13
     let deck = deck::new_deck();
13
     let deck = deck::new_deck();
14
-    let ((_, dog), hands) = deck::distribute_cards(deck);
14
+    let (dog, mut hands) = deck::distribute_cards(&deck);
15
     println!("-> Cartes du chien :");
15
     println!("-> Cartes du chien :");
16
     for card in dog.iter() {
16
     for card in dog.iter() {
17
         println!("{}", card);
17
         println!("{}", card);
18
     }
18
     }
19
-    for &(number, ref hand) in hands.into_iter() {
20
-        println!("-> Cartes du joueur {}:", number + 1);
19
+    for hand in hands.iter() {
20
+        println!("-> Cartes du joueur {}:", 0);
21
         for card in hand.iter() {
21
         for card in hand.iter() {
22
             println!("{}", card);
22
             println!("{}", card);
23
         }
23
         }
24
     }
24
     }
25
-    game::start_game((-1, dog), hands);
25
+    let mut names: Vec<String> =
26
+        vec!["A".to_string(), "B".to_string(), "C".to_string(), "D".to_string()];
27
+    let mut players = game::initialize_players(&mut hands, &mut names);
28
+    game::start_game(&dog, &mut players);
26
 }
29
 }

+ 0 - 1
src/params.rs

1
-pub const DECK_SIZE: usize = 78;
2
 pub const DOG_SIZE: usize = 6;
1
 pub const DOG_SIZE: usize = 6;
3
 pub const NUMBER_OF_PLAYERS: usize = 4;
2
 pub const NUMBER_OF_PLAYERS: usize = 4;
4
 pub const CARDS_PER_DISTRIBUTION: usize = 3;
3
 pub const CARDS_PER_DISTRIBUTION: usize = 3;