Python战舰游戏:简化舰船放置代码与单元测试实现
战舰游戏问题解决方案
一、优化舰船随机放置代码
你写的create_ships函数存在几个问题:未定义get_ship_location函数、变量未初始化、未调用函数导致舰船未生成,以下是修正后的完整代码及整合方式:
修正后完整代码
import random # Legend: # 1. "." = water # 2. "S" = ship position # 3. "O" = water that was shot with bullet, a miss because it hit no ship # 4. "X" = ship sunk! # global variable for grid size grid_size = 10 # global variable for grid myBoard = [['.']*grid_size for i in range(grid_size)] def get_ship_location(): """生成随机舰船坐标""" return random.randint(0, grid_size - 1), random.randint(0, grid_size - 1) def create_ships(board): """在棋盘上放置5个不重复的单格舰船""" for _ in range(5): row, col = get_ship_location() # 若位置已被占用,重新生成坐标 while board[row][col] == 'S': row, col = get_ship_location() board[row][col] = 'S' def drawBoard(myBoard): # Print header print(end=" ") for i in range(grid_size): print(i, end=" ") print() # Print rows for i in range(grid_size): print(i, end=" ") for j in range(grid_size): print(myBoard[i][j], end=" ") print() def user_guess(myBoard): # 可在此补充用户猜测逻辑 pass def main(): # 先放置舰船,再绘制棋盘 create_ships(myBoard) drawBoard(myBoard) user_guess(myBoard) # Call main function main()
关键修改点
- 新增
get_ship_location函数,专门生成随机坐标,代码更模块化 - 修正
create_ships逻辑:生成坐标后检查是否已被占用,重复直到找到空位置 - 在
main函数中先调用create_ships再绘制棋盘,确保舰船被放置后才显示 - 删除原重复5次的舰船放置代码,替换为函数调用
二、单元测试实现(基于Python内置unittest)
使用Python自带的unittest模块即可完成测试需求,以下是对应两个要求的测试示例:
测试代码(保存为test_battleship.py)
import unittest import sys # 假设主代码保存在battleship.py中,导入相关内容 sys.path.insert(0, '.') from battleship import grid_size, create_ships class TestBattleship(unittest.TestCase): def setUp(self): """每个测试用例执行前,创建全新空棋盘""" self.board = [['.']*grid_size for _ in range(grid_size)] def test_ship_count(self): """验证舰船数量为5""" create_ships(self.board) ship_count = sum(row.count('S') for row in self.board) self.assertEqual(ship_count, 5) def test_non_ship_cells(self): """验证非舰船位置均为水域'.'""" create_ships(self.board) for row in self.board: for cell in row: self.assertIn(cell, ['.', 'S']) if __name__ == '__main__': unittest.main()
运行测试
在终端执行:
python test_battleship.py
测试通过会输出:
.. ---------------------------------------------------------------------- Ran 2 tests in 0.001s OK
单元测试入门要点
setUp方法在每个测试用例前执行,确保测试用独立的棋盘,避免互相干扰self.assertEqual(a, b):断言a等于b,验证舰船数量self.assertIn(item, sequence):断言item在sequence中,验证单元格内容合法性
三、入门提示
- 每个测试用例只验证一个逻辑点,保持测试单一性
- 避免依赖全局变量状态,尽量为每个测试创建独立的测试对象
内容的提问来源于stack exchange,提问作者Ros
相关产品推荐
相关产品推荐

