import copy import random class map(): chess_number=None; livcell=[]; def init(self, chess_number=60, density=0.5): self.livcell = [[0] * chess_number for i in range(chess_number)] for i in range(chess_number): for j in range(chess_number): pwall = random.random() if pwall < density: self.livcell[i][j] = 1 self.chess_number=chess_number self.density=density def neighborcell(self,pos): neighborList = [] x = pos[0] y = pos[1] neighborList = [[x - 1, y - 1], [x - 1, y], [x - 1, y + 1], [x, y - 1], [x, y + 1], [x + 1, y - 1], [x + 1, y], [x + 1, y + 1]] realnList = copy.deepcopy(neighborList) for i in neighborList: if i[0] < 0 or i[0] > self.chess_number - 1 or i[1] < 0 or i[1] > self.chess_number - 1: realnList.remove(i) return realnList 使用pytext写一个上述代码的单元测试
时间: 2024-04-29 19:19:45 浏览: 18
import unittest
from map import Map
class TestMap(unittest.TestCase):
def test_init(self):
m = Map()
self.assertEqual(m.chess_number, 60)
self.assertEqual(m.density, 0.5)
def test_neighborcell(self):
m = Map()
n = m.neighborcell([0, 0])
self.assertEqual(len(n), 3)
self.assertIn([0, 1], n)
self.assertIn([1, 0], n)
self.assertIn([1, 1], n)
def test_livcell(self):
m = Map()
self.assertEqual(len(m.livcell), 60)
self.assertEqual(len(m.livcell[0]), 60)
self.assertIn(0, m.livcell[0])
self.assertIn(1, m.livcell[0])
if __name__ == '__main__':
unittest.main()
相关问题
chess_location_b = chess_location[0::2]
这是一个Python中的切片语法,意思是从列表 `chess_location` 中取出所有偶数索引位置的元素,并将它们放入一个新的列表 `chess_location_b` 中。具体来说,这个语法中的 `0::2` 表示从索引位置0开始,每隔两个位置取一个元素,直到取完整个列表。例如,如果 `chess_location` 是 `[1, 2, 3, 4, 5, 6, 7, 8]`,那么 `chess_location_b` 就会是 `[1, 3, 5, 7]`。
def count_line(self,direct,row,col,chess_color): ''' :param direct: :param row: :param col: :param chess_color: :return: ''' c1,c2,c3 = 1,1,1 for i in range(2): deta_row, deta_col = direct[i] flag_continous = True for i in range(1,6): next_row,next_col = row + i *deta_row,col + i * deta_col if not self.is_pos_inside(next_row,next_col): break if self.matrix[next_row][next_col] != 3-chess_color: c3 += 1 if self.matrix[next_row][next_col]: if flag_continous: c1 += 1 c2 += 1 else: flag_continous = False else: break return c1,c2,c3
这段代码是一个类的一个方法`count_line`,它接受一些参数,并返回三个计数值。这个方法用于计算给定位置在某个方向上的连续棋子数。
在方法中,首先初始化三个计数器`c1`、`c2`、`c3`的值为1。然后使用一个循环两次,每次迭代处理一个方向。在每个方向上,通过给定的行、列和方向来计算下一个位置的行和列。然后,检查下一个位置是否在棋盘内,如果不在,则跳出循环。如果下一个位置的棋子颜色不是与给定的棋子颜色相反,则增加`c3`计数器的值。如果下一个位置有棋子,根据连续性标志`flag_continous`的值来增加计数器`c1`和`c2`的值。如果下一个位置没有棋子,则将连续性标志设置为False。如果下一个位置的棋子颜色与给定的棋子颜色相反,则跳出循环。
最后,返回三个计数器的值。
这个方法可能是用于评估给定位置在某个方向上的连续棋子数,并用于计算分数或决策下一步的最佳位置。