帮我用python做一个电影院购票系统代码
时间: 2024-01-03 07:04:58 浏览: 90
好的,下面是一个简单的电影院购票系统的 Python 代码:
```python
class Movie:
def __init__(self, title, rating, genre, duration):
self.title = title
self.rating = rating
self.genre = genre
self.duration = duration
class Cinema:
def __init__(self):
self.movies = []
def add_movie(self, movie):
self.movies.append(movie)
def show_movies(self):
for i, movie in enumerate(self.movies):
print(f"{i+1}. {movie.title} ({movie.rating}) - {movie.genre} ({movie.duration} mins)")
class Ticket:
def __init__(self, movie_index, seat_number):
self.movie_index = movie_index
self.seat_number = seat_number
class BookingSystem:
def __init__(self):
self.cinema = Cinema()
self.tickets = {}
def add_movie(self, title, rating, genre, duration):
movie = Movie(title, rating, genre, duration)
self.cinema.add_movie(movie)
def show_movies(self):
self.cinema.show_movies()
def buy_ticket(self, movie_index, seat_number):
if movie_index < 1 or movie_index > len(self.cinema.movies):
print("Invalid movie index.")
return False
if seat_number in self.tickets:
print("Seat already taken.")
return False
self.tickets[seat_number] = Ticket(movie_index, seat_number)
print("Ticket purchased successfully!")
return True
```
这个代码中包含了三个类:Movie、Cinema 和 BookingSystem。Movie 类用于存储电影信息,Cinema 类用于管理电影库和展示电影信息,BookingSystem 类用于购票和管理已购票的信息。
你可以通过以下代码来测试这个系统:
```python
booking_system = BookingSystem()
booking_system.add_movie("Avengers: Endgame", "PG-13", "Action, Adventure, Drama", 181)
booking_system.add_movie("The Lion King", "PG", "Animation, Adventure, Drama", 118)
booking_system.show_movies()
booking_system.buy_ticket(1, "A1")
booking_system.buy_ticket(1, "A1")
booking_system.buy_ticket(3, "B2")
```
输出结果为:
```
1. Avengers: Endgame (PG-13) - Action, Adventure, Drama (181 mins)
2. The Lion King (PG) - Animation, Adventure, Drama (118 mins)
Ticket purchased successfully!
Seat already taken.
Invalid movie index.
```
希望这个代码能够帮到你!
阅读全文