Menu
CoddyTech

Sistema di prestito

Fa parte della sezione Programmazione orientata agli oggetti del percorso GDScript di Coddy. Lezione 58 di 65.

challenge icon

Sfida

Medio

Sposta il prestito nella biblioteca. Conserva tutto ciò che hai scritto nei passaggi precedenti; cambia solo library.gd.

Aggiungi tre metodi a Library:

  1. find_book(isbn: String) -> Book restituisce il libro con quel ISBN, oppure null se non esiste.
  2. find_user(user_id: String) -> User restituisce l'utente con quell'ID, oppure null.
  3. borrow_book(isbn: String, user_id: String) -> String presta un libro e restituisce un messaggio. Controlla nell'ordine seguente:
    • nessun libro con quell'ISBN: restituisci Book not found
    • nessun utente con quell'ID: restituisci User not found
    • il libro non è disponibile: restituisci Book is not available
    • altrimenti imposta available del libro su false e il suo borrower_id sull'ID utente, aggiungi l'ISBN a borrowed_isbns dell'utente e restituisci Book borrowed successfully

Il codice fornito sostituisce lend con borrow ISBN|ID, che stampa il messaggio, e aggiunge loans ID (i titoli presi in prestito da un utente) e holder ISBN (chi ha un libro). Entrambi usano find_book() e find_user(). Con questo input:

Community
book Dune|Frank Herbert|111
user U001|Alice
user U002|Bob
borrow 999|U001
borrow 111|U999
borrow 111|U001
borrow 111|U002
holder 111
loans U001

l'output è:

Book not found
User not found
Book borrowed successfully
Book is not available
Dune is borrowed by Alice
Alice has borrowed:
- Dune

Il tuo codice va in book.gd, user.gd e library.gd. main.gd contiene il codice fornito per input/output e non può essere modificato.

Provalo tu

extends Node

func _ready():
	# Codice di input/output fornito: lascialo così com'è
	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]))
			"borrow":
				print(library.borrow_book(fields[0], fields[1]))
			"loans":
				var reader: User = library.find_user(fields[0])
				print(reader.user_name, " has borrowed:")
				for isbn in reader.borrowed_isbns:
					print("- ", library.find_book(isbn).title)
			"holder":
				var book: Book = library.find_book(fields[0])
				if book.available:
					print(book.title, " is on the shelf")
				else:
					print(book.title, " is borrowed by ", library.find_user(book.borrower_id).user_name)
			"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()

Tutte le lezioni di Programmazione orientata agli oggetti

Esercitati da solo: Compilatore GDScript online