Menu
CoddyTech

Book and User Classes

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 57 of 65.

challenge icon

Challenge

Easy

Add the classes Book and User, each in its own file, and make the library store them. Keep everything you wrote in the previous step.

Book in book.gd:

  • The constructor takes title, author and isbn (all String) and stores them in properties with the same names.
  • available starts as true and borrower_id starts as "".
  • _to_string() returns TITLE by AUTHOR (ISBN: ISBN) - Available, with Not Available at the end when available is false.

User in user.gd:

  • The constructor takes user_id and user_name and stores them.
  • borrowed_isbns is an Array[String] that starts empty.
  • _to_string() returns User: NAME (ID: ID) - Books borrowed: N, where N is the size of borrowed_isbns.

In library.gd, change books to an Array[Book] and users to an Array[User], and add the methods add_book(book: Book) and add_user(user: User), which append to them.

A book remembers its borrower by the user's id, and a user remembers books by their ISBN. If the book stored the User object and the user stored the Book object, the two would keep each other alive and Godot would report them as leaked when the program ends.

The supplied code in main.gd changed: fields are now separated by |. The commands are book TITLE|AUTHOR|ISBN, user ID|NAME, lend ISBN|ID (it sets the properties of the book and the user directly), books and users (print every book or user) and show. For this input:

Riverside
book Dune|Frank Herbert|111
user U001|Alice
user U002|Bob
lend 111|U002
books
users
show

the output is:

Dune by Frank Herbert (ISBN: 111) - Not Available
User: Alice (ID: U001) - Books borrowed: 0
User: Bob (ID: U002) - Books borrowed: 1
Riverside Library (books: 1, users: 2)

Your code goes in book.gd, user.gd and library.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var library := Library.new(OS.read_string_from_stdin())
	var line := OS.read_string_from_stdin()
	while line != "":
		var parts := line.split(" ", true, 1)
		var fields: PackedStringArray = parts[1].split("|") if parts.size() > 1 else PackedStringArray()
		match parts[0]:
			"book":
				library.add_book(Book.new(fields[0], fields[1], fields[2]))
			"user":
				library.add_user(User.new(fields[0], fields[1]))
			"lend":
				for book in library.books:
					if book.isbn == fields[0]:
						book.available = false
						book.borrower_id = fields[1]
				for user in library.users:
					if user.user_id == fields[1]:
						user.borrowed_isbns.append(fields[0])
			"books":
				for book in library.books:
					print(book)
			"users":
				for user in library.users:
					print(user)
			"show":
				print(library)
		line = OS.read_string_from_stdin()

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler