import random
# 生成五盤九宮格
def generate_boards():
boards = []
for _ in range(5):
board = []
numbers = random.sample(range(1, 91), 15) # 從1到90中隨機選取15個數字
for i in range(3):
row = random.sample(numbers[i*5:(i+1)*5], 5) # 每行隨機選取5個數字
board.append(row)
boards.append(board)
return boards
# 電腦隨機選取數字
def select_number():
return random.randint(1, 90)
# 檢查是否連成三條線
def check_bingo(board):
# 檢查行
for row in board:
if all(cell == 'X' for cell in row):
return True
# 檢查列
for col in range(5):
if all(board[row][col] == 'X' for row in range(3)):
return True
# 檢查對角線
if all(board[i][i] == 'X' for i in range(3)) or all(board[i][2-i] == 'X' for i in range(3)):
return True
return False
# 主遊戲邏輯
def play_game():
boards = generate_boards()
selected_board = random.choice(boards)
print("五盤九宮格:")
for board in boards:
for row in board:
print(row)
print()
print("選中的盤:")
for row in selected_board:
print(row)
print()
while True:
input("按 Enter 鍵以繼續...")
number = select_number()
print("電腦選取的數字:", number)
# 在選中的盤上標記已選取的數字
for row in selected_board:
if number in row:
row[row.index(number)] = 'X'
print("選中的盤更新後:")
for row in selected_board:
print(row)
print()
if check_bingo(selected_board):
print("賓果!遊戲結束。")
break
# 運行遊戲
play_game()
這可以定義出一個Bingo
的Class,裡面的方法如下
所以假設你有n個玩家,你就可以簡單的透過陣列控制這n個玩家玩Bingo了
game_size = 3
n = int(input("How many player?"))
players = []
for i in range(n):
players.append(Bingo(game_size))
之後就是用for loop操作Players的陣列,讓各自陣列去玩遊戲,如果你想要更精進自己,還可以用MutiThread各自去玩,避免for loop都是由0~n,會有不公平的問題。
import random
class Bingo:
def __init__(self):
self.board = self.create_board()
def create_board(self):
# 創建一個3x3的空白板
board = []
nums = random.sample(range(1, 10), 9) # 1到9之間的不重複數字
for i in range(3):
row = nums[i * 3 : (i + 1) * 3]
board.append(row)
return board
def display_board(self):
print("Bingo Board:")
for row in self.board:
print(row)
def play(self):
print("歡迎來到 Bingo 遊戲!")
self.display_board()
while True:
number = random.randint(1, 9)
print("開出的號碼是:", number)
for row in self.board:
if number in row:
index = row.index(number)
row[index] = "X"
self.display_board()
if self.is_bingo():
print("Bingo!")
break
def is_bingo(self):
# 檢查行、列和對角線是否有連成一線的 "X"
for i in range(3):
# 檢查行
if all(cell == "X" for cell in self.board[i]):
return True
# 檢查列
if all(row[i] == "X" for row in self.board):
return True
# 檢查主對角線
if self.board[0][0] == self.board[1][1] == self.board[2][2] == "X":
return True
# 檢查副對角線
if self.board[0][2] == self.board[1][1] == self.board[2][0] == "X":
return True
return False
# 創建 Bingo 遊戲實例並開始遊戲
bingo_game = Bingo()
bingo_game.play()