Akarsh Balaji 1 year ago
parent
commit
57b0b0f32b
1 changed files with 39 additions and 30 deletions
  1. 39 30
      players.c

+ 39 - 30
players.c

@@ -9,41 +9,50 @@
  * of players whose head is pointed to by *player_ptr_add.
  */
 int create_player(const char *name, Player **player_ptr_add) {
-	if (find_player(name, *player_ptr_add) != NULL) { //if a player already exists with that name return 1
-		return 1;
+	if(find_player(name, *player_ptr_add))
+		return 1; 
+	Player * p = calloc(1, sizeof(Player));
+	if(strlen(name) > MAX_NAME){
+      
+		strncpy(p->name, name, MAX_NAME - 1);
+		p->total_score = 0;
+        	p->max_score = 0;
+        	p->total_games = 0;
+        	p->next = NULL;
+        	Player * curr = *player_ptr_add;
+        	if(curr == NULL){
+                	*player_ptr_add = p;
+                return 0;
+              
+        }
+        while(curr->next)
+                curr = curr->next;
+        curr->next = p;
+		return 2;  	
 	}
-	
-	int retval = 0; //changes to 2 if name was truncated
-	Player* new_player = calloc(1, sizeof(Player)); //makes new player and inits stats
-
-	if (strlen(name) > MAX_NAME - 1) { //name is too long-- needs to be truncated
-		strncpy(new_player->name, name, MAX_NAME - 1); //copies safe amount
-		new_player->name[MAX_NAME - 1] = '\0'; //sets null terminator
-		retval = 2; //when done will return 2 to indicate truncated name
-	} else { //else copies whole name
-		strcpy(new_player->name, name);
-	}
-
-	new_player->total_score = 0;
-	new_player->max_score = 0;
-	new_player->total_games = 0;
-	
-	Player* curr = *player_ptr_add; //to go to the end of the list
-	
-	if (curr == NULL) { //no players in the list, just sets head to point to it
-		*player_ptr_add = new_player;
-		return retval;
+  
+	//Player * p = calloc(1, sizeof(Player));
+	strcpy(p->name, name);
+	p->total_score = 0;
+	p->max_score = 0;
+	p->total_games = 0;
+	p->next = NULL;
+	Player * curr = *player_ptr_add;
+	if(curr == NULL){
+      
+		*player_ptr_add = p;
+		return 0;
+      
 	}
-
-	while (curr->next != NULL) { //must be at least one player in the list, loops until it gets the last player and then sets that player's next to point to the new player
+	while(curr->next)
+      
 		curr = curr->next;
-	}
-
-	curr->next = new_player;
-
-	return retval;
+	curr->next = p;
+  
+	return 0;
 }
 
+
 //TODO - implement this
 /* 
  * Return a pointer to the player with this name in