AIST1110代做、Python编程设计代写
时间:2024-03-21 来源: 作者: 我要纠错
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
1
Assignment 2
Instructions
• Unless specified otherwise,
o you can use anything in the Python Standard Library;
o don’t use any third-party library including NumPy in your code for this assignment except for the
requests package;
o you can assume all user inputs are always valid and require no validation.
• The blue texts, if any, in the Sample Runs section of each question refers to the user inputs.
• Please follow closely the format of the sample output for each question. Your program should produce
exactly the same output as the sample (same text, symbols, letter case, spacing, etc.). The output for
each question should end with a single newline character, which has been provided by the print()
function by default.
• Please follow exactly the specified name, parameter list and return value(s) for the functions to be
written if a question has stated (for easier grading). You may define additional (inner) functions for
specific tasks or further task decomposition in any question if you see fit.
• For questions that require you to define specific functions, your main client code (for calling and
testing the functions) must be put under an if __name__ == '__main__': check because we
may import your script into our test scripts calling your functions in our own ways for grading.
• Your client code will not be graded unless specified otherwise in the question.
• Name your script files as q1.py for Question 1, q2.py for Question 2, … (case-sensitive). Using other
names may affect our marking and may result in deduction.
• Your source files will be tested in script mode rather than interactive mode.
• You are highly encouraged to annotate your functions to provide type information for parameters and
return values, and to include suitable comments in your code to improve the readability.
Question 1 (20%)
In this question, you are going to write a couple of functions related to the classical games Tic-Tac-Toe and
Minesweeper in the same script (q1.py).
(a) Write a function tic_tac_toe(board: list[list[str]]) -> str, which takes a nested list of
strings which represents the 3x3 matrix of a completed tic-tac-toe game and returns a string that tells
which of the players is the game winner. Suppose that letters ‘X’ and ‘O’ are used as the marks in the
game (i.e., elements in the matrix) and they represent the two players. The function returns ‘X’ if
player X wins, ‘O’ if player O wins, and ‘Draw’ if it is a draw game.
Notes:
• An empty spot is denoted by a single space in the matrix.
• All the letters ‘X’ and ‘O’ and the letter ‘D’ of ‘Draw’ must be upper case.
(b) Write a function minesweeper(board: list[list[int]]) -> list[list[int]], which takes a
nested list representation of a Minesweeper board and returns another board of the same dimension
where the value of each cell is the number of its neighboring mines.
The input board matrix contains either 0 or 1, where 0 represents an empty space and 1 represents
a mine. To produce the output, you will have to replace each mine with the number 9 and each empty
space with the number of adjacent mines.
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
2
Notes:
• The board can be in any rectangular shape of reasonable size to be fully viewed on the screen.
• Assume that board is always a valid nested list (e.g., it won’t be empty).
• Since the number of adjacent mines around a cell is at most 8, the number 9 will be used to denote
the mines for convenience.
• An online version of the game is available in case you have no ideas how the game is like.
Sample Runs
tic_tac_toe([
["X", "O", "X"],
["O", "X", "O"],
["O", "X", "X"]
]) -> "X"
tic_tac_toe([
["O", "O", "O"],
["O", "X", "X"],
[" ", "X", "X"]
]) -> "O"
tic_tac_toe([
["X", "X", "O"],
["O", "O", "X"],
["X", "X", "O"]
]) -> "Draw"
minesweeper([[1]]) -> [[9]]
minesweeper([[0, 1]]) -> [[1, 9]]
minesweeper([
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 1],
[1, 1, 0, 0]
]) -> [
[1, 9, 2, 1],
[2, 3, 9, 2],
[3, 9, 4, 9],
[9, 9, 3, 1]
]
minesweeper([
[1, 0, 0, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 1]
]) -> [
[9, 3, 1, 2, 1, 2, 9, 1],
[9, 3, 9, 2, 9, 2, 1, 1],
[2, 3, 3, 3, 2, 1, 1, 1],
[1, 9, 2, 9, 1, 0, 1, 9]
]
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
3
Question 2 (20%)
In this question, we are going to download and analyze a data set about schools in Hong Kong, namely
School Location and Information. The URL for downloading the data set is as follows:
https://www.edb.gov.hk/attachment/en/student-parents/sch-info/sch-search/sch-locationinfo/SCH_LOC_EDB.json
Below is an example JSON object in this data set:
To understand this JSON file, you may read its associated data specification for its field names, their
meanings, and the valid values for some of the fields. You may ignore the Chinese characters in the file
and the specification as we will retrieve those English fields only in this question. Instead of manually
downloading the data set using a web browser, you are required to download the data in JSON format by
coding in a Python script (q2.py).
To facilitate the data download and analysis tasks, you are required to write several (general-purpose)
functions specified as follows:
(a) Write a function get_data(url: str, filename: str) -> list[dict], which takes a string
url that specifies the website (URL) to download a JSON file and a string filename specifying the
name of a local JSON file (assumed in the current directory) which stores the downloaded JSON data.
This function will perform the following tasks:
• If the JSON file with name filename already exists in the current directory, load the data from the
file into a list of Python dictionaries (one dictionary corresponds to one JSON object).
• If the file does not exist, download the JSON data from the specified url into a list of Python
dictionaries, and dump it into a local JSON file with name filename in the current directory. Set
the indentation in the JSON file to 4 spaces and make sure that non-ASCII characters in the file will
be output as-is instead of escaped (so Chinese characters instead of Unicode escape sequences in
the form "uXXXX" can be seen in the output). Hints:
o Explore the use of the ensure_ascii argument in the dump() or dumps() function.
o You may use the 3rd-party package Requests for easing this task.
o The download is triggered only if the specified JSON file cannot be found locally. This makes
sure subsequent data retrieval is fast (done locally rather than remotely).
• Return the list of dictionaries loaded from filename or from the URL.
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
4
To download the data set about schools, the client for using this function is like:
URL = 'https://www.edb.gov.hk/.../sch-location-info/SCH_LOC_EDB.json'
schools = get_data(URL, 'SCH_LOC_EDB.json')
After execution, besides getting the list of dictionaries of school information as schools, the file
SCH_LOC_EDB.json will be saved in the current directory containing the running script. A sample of
the expected output SCH_LOC_EDB.json is provided on Blackboard.
(b) Write a function filter_data(data: list[dict], criteria: dict[str, list[str]]) ->
list[dict], which takes a list of dictionary objects called data and a dictionary called criteria,
and returns a subset of data that contains dictionary objects that match all the criteria specified (in
the form of key-value pairs) through the criteria dictionary.
For example, suppose that
data = [
{'a': 'x', 'b': 'y', 'c': 'z'},
{'a': 'p', 'b': 'q', 'c': 'r'},
{'a': 'u', 'b': 'v', 'c': 'w'}
]
criteria1 = {'a': ['x', 'p']}
criteria2 = {'a': ['x', 'p'], 'b': ['q']}
Then note the expected results returned by the function calls below:
filter_data(data, criteria1) -> [
{'a': 'x', 'b': 'y', 'c': 'z'},
{'a': 'p', 'b': 'q', 'c': 'r'}
]
filter_data(data, criteria2) -> [
{'a': 'p', 'b': 'q', 'c': 'r'}
]
By criteria1, we want to get all dictionaries whose key 'a' equals the value 'x' or 'p'. Therefore,
two dictionaries in the list get selected.
By criteria2, we want to get all dictionaries whose key 'a' equals the value 'x' or 'p' and key
'b' equals the value 'q'. Only one dictionary in the list fulfils the compound criteria.
(c) Write a function print_school_list(schools: list[dict], fields: list[str],
sorted_by: list[str] = None) -> None, which prints a list of schools in tabular format. The
school data are provided in the form of a list of dictionaries. The fields being printed in the table are
listed in the fields list. The printed rows are sorted by the fields specified in the sorted_by list
which allows at most three fields to be included as the sort fields.
The required output format is demonstrated by the sample output file (q2-output.txt) that was
generated by the provided sample client code (q2-starter.py).
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
5
For example, the following client code:
EN = "ENGLISH NAME"
RE = "RELIGION"
SG = "STUDENTS GENDER"
western_kgs_in_christ = filter_data(
schools,
criteria={
"SCHOOL LEVEL": ["KINDERGARTEN"],
"DISTRICT": ["CENTRAL AND WESTERN"],
"RELIGION": ["PROTESTANTISM / CHRISTIANITY", "CATHOLICISM"],
},
)
print_school_list(western_kgs_in_christ, [EN, SG, RE], [EN])
prints all the kindergartens with Christianity or Catholicism as religion in the Central and Western
district (sorted by the schools’ English names) in the tabular format below:
ENGLISH NAME | STUDENTS GENDER | RELIGION
---------------------------------------------- | --------------- | ----------------------------
CANNAN KINDERGARTEN (CENTRAL CAINE ROAD) | CO-ED | PROTESTANTISM / CHRISTIANITY
CARITAS LING YUET SIN KINDERGARTEN | CO-ED | CATHOLICISM
CARITAS ST. FRANCIS KINDERGARTEN | CO-ED | CATHOLICISM
HONG KONG TRUE LIGHT KINDERGARTEN (CAINE ROAD) | CO-ED | PROTESTANTISM / CHRISTIANITY
KAU YAN SCHOOL | CO-ED | PROTESTANTISM / CHRISTIANITY
RHENISH MISSION SCHOOL | CO-ED | PROTESTANTISM / CHRISTIANITY
SACRED HEART CANOSSIAN KINDERGARTEN | CO-ED | CATHOLICISM
SMALL WORLD CHRISTIAN KINDERGARTEN | CO-ED | PROTESTANTISM / CHRISTIANITY
ST. CLARE'S PRIMARY SCHOOL | GIRLS | CATHOLICISM
ST. MATTHEW'S CHURCH KINDERGARTEN | CO-ED | PROTESTANTISM / CHRISTIANITY
ST. PAUL'S CHURCH KINDERGARTEN | CO-ED | PROTESTANTISM / CHRISTIANITY
ST. STEPHEN'S GIRLS' COLLEGE KINDERGARTEN | CO-ED | PROTESTANTISM / CHRISTIANITY
WISELY KINDERGARTEN | CO-ED | PROTESTANTISM / CHRISTIANITY
Notes:
• The column headers are the same as the field names included in the fields list.
• The width (w) of each field is set to be the width of the longest string value being printed. That
includes the field value and the column header.
• There is a line of w hyphens separating the column header row and the first data row.
• There is a single space before and after the | separator between every two columns.
• Without extra handling, there can be duplicate rows in the table because the data set may contain
multiple objects having the same English Name, e.g., one school name may correspond to several
campus addresses or several sessions (am, pm, whole day), which span multiple objects. Your
implementation must get rid of the printing of duplicate schools.
(d) Write a function print_count_by_district(schools: list[dict]) -> None, which prints a
table showing the count of schools grouped by the District field. The results are sorted and
grouped by District. Again, refer to the sample output file for the expected output for a particular
input of schools.
For example, the following client code:
primary = filter_data(schools, criteria={"SCHOOL LEVEL": ["PRIMARY"]})
print_count_by_district(primary)
prints the counts of all primary schools in Hong Kong by district in the tabular format below:
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
6
District #Schools
CENTRAL AND WESTERN 28
EASTERN 39
ISLANDS 23
KOWLOON CITY 62
KWAI TSING 38
KWUN TONG 45
NORTH 33
SAI KUNG 38
SHA TIN 51
SHAM SHUI PO 42
SOUTHERN 32
TAI PO 31
TSUEN WAN 23
TUEN MUN 43
WAN CHAI 26
WONG TAI SIN 32
YAU TSIM MONG 29
YUEN LONG 57
Total: 672
Notes:
• The above result may differ from some other information sources like this webpage of EDB. Ignore
the discrepancies.
• You may hardcode the width for the District column as 20.
• There is a single space separating the District and #Schools columns.
• There may be objects of the same school name in different districts or school levels. For example,
some schools may use the same school name to offer both primary and kindergarten education in
different sectors of the same campus. Therefore, we need to use the combination of fields
DISTRICT + SCHOOL LEVEL + ENGLISH NAME to distinguish the objects as unique schools.
• There is a total number of schools printed on the last line of the table. The word “Total:” is right
adjusted in the first column.
Question (40%)
Write a Python script (q3.py) to implement a two-player board game called Gekitai (a Japanese word
which means “repel” or “push away”). Here is the game description from the designer (we rephrased a
little bit): Gekitai is a 3-in-a-row game played on a 6x6 grid. Each player has eight colored pieces and takes
turns placing them anywhere on any open space on the board. When placed, a piece pushes all adjacent
pieces outwards one space if there is an open space for it to move to (or off the board). Pieces shoved off
the board are returned to the player. If there is not an open space on the opposite side of the pushed piece,
it does not push (a newly played piece cannot push two or more other lined-up pieces). The first player who
either (1) lines up three of their color in a row (horizontal or vertical or diagonal) at the end of their turn
(after pushing), or (2) has all eight of their pieces on the board (also after pushing) wins. To quickly
understand how to play this game, you may also watch this game review video or play this online game
implementing Gekitai.
The key idea of this game is the “repel” effect when placing a piece onto the board. For example, refer to
Figure 1 below. Suppose that the player (Red) of the current turn is to put a piece at location B2. Then all
the three pieces (both the player’s and opponent’s) adjacent to B2 will be pushed away by one square
outward. So, the black piece originally at A1 is shoved off the board and recycled to the player (Black) for
making future turns whereas the pieces at C2 and B3 will be repelled to new positions D2 and B4
respectively.
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
7
A B C D E F
1
2
3
4
5
6
A B C D E F
1
2
3
4
5
6
Figure 1: An example move on the game board and its effect on the adjacent pieces
However, remember (from the above description) that a move cannot push away a piece which has
another adjacent piece (both the player’s and opponent’s) occupying the square it is being pushed onto.
For example, look at Figure 2 below. If the player (Black) puts a piece at B3, it won’t repel the piece at B4
downward because there is no open space (B5 is already occupied), and only the piece at B2 will be pushed
upward to position B1.
A B C D E F
1
2
3
4
5
6
A B C D E F
1
2
3
4
5
6
Figure 2: Another example move on the game board and its effect on the adjacent pieces
The last move made by Black was indeed a bad one – if Red puts a piece at B6 now, Red will win the game
because three red pieces have formed a vertical line (see Figure 3).
A B C D E F
1
2
3
4
5
6
A B C D E F
1
2
3
4
5
6
Figure 3: A move that lets Red win the game
To achieve the repelling effect, your program may need to scan all the eight directions (N, NE, E, SE, S, SW, W,
NW) around the target position for a piece placement. For example, to put a piece at D3 in Figure 4, it should
board
transition
Shoved off the board and came
back to the Black player
board
transition
board
transition
Red wins!
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
8
check if there exist any piece(s) at all the blue cells, and if any, it should check if the corresponding purple cell(s)
are empty before moving the pieces outward into the purple cells.
Figure 4: Positions to check to repel pieces adjacent to a target cell
Figure 5 below shows other possible winning conditions. Recall that a line can be formed horizontally, vertically,
and diagonally, and that there is another winning condition: if all the eight pieces of the same color are placed
on the board, the player of that color will win.
Black first formed a diagonal line and wins.
Red first formed a diagonal line and wins.
Red first has 8 pieces on board and wins.
Figure 5: Other winning conditions
Game Board Representation
We are going to implement this game as a console-based program and the game board will be represented
by characters arranged in Figure 6 below:
A B C D E F
+---+---+---+---+---+---+
1 | X | | | | | |
+---+---+---+---+---+---+
2 | | | | | | |
+---+---+---+---+---+---+
3 | | O | X | | X | |
+---+---+---+---+---+---+
4 | | | | | | |
+---+---+---+---+---+---+
5 | | O | | | | |
+---+---+---+---+---+---+
6 | | | | | | |
+---+---+---+---+---+---+
A B C D E F
1
2
3
4
5
6
Figure 6: An example game board in the console
ç
equivalent
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
9
In the beginning, all cells on the board are empty. Pieces of player 1 (Black) and player 2 (Red) are denoted
by 'X' and 'O' symbols, respectively.
Program Flow
1. The program starts the game with an empty board. Player 1 (X) takes the first turn.
2. Then, prompt the current player to enter a cell address to put a piece onto the board.
3. A piece cannot be placed onto the board if the target cell is not empty or if the position is outside the
board’s boundaries. In case it is not placeable, display an error message “Invalid move!” and go back
to Step 2.
4. Update the board by putting the input piece to the target position and repelling existing adjacent
pieces away if there exists open space. Recycle any off-the-board pieces to their own players.
5. Switch to the other player to take the next turn.
6. Repeat steps 2–5 until a player wins (forming a line of L pieces or having all P pieces put on the board).
If both players satisfy either of the winning conditions concurrently, the moving player (i.e., the one
taking the current turn) is regarded the winner.
7. When a game finishes, display the message “Player X wins!” or “Player O wins!” accordingly.
Assumptions
• There are three basic configuration parameters for this game:
o size = (6, 6) is the board size (size[0] * size[1] = number of cells);
o P = 8 is the number of pieces per player;
o L = 3 is the (least) number of pieces of a line to form.
• In most cases, the board is a square, but your program should NOT assume that (it may be a rectangle).
• To check if your program is scalable on these parameters instead of hardcoding, we may have a few
test cases that vary their values although this may affect the original game rules. To support our testing,
the constructor of your Gekitai class must follow this method signature:
__init__(self, size: tuple[int, int] = (6, 6), P: int = 8, L: int = 3)
Then we can create game objects for different test cases such as:
g1 = Gekitai() # 6x6 board, 8 pieces, 3-in-a-lins
g2 = Gekitai((7, 8), 9, 4) # 7x8 board, 9 pieces, 4-in-a-line
g3 = Gekitai(P=6) # 6x6 board, 6 pieces, 3-in-a-line
• You may assume the range for size’s values is between 6 and 8, P between 6 and 12, and L between
3 and the minimum of size’s values and P. Your program should add the following assertion in the
constructor of Gekitai to avoid creating a game with out-of-range parameters:
assert (
all(6 <= s <= 8 for s in size)
and 6 <= P <= 12
and 3 <= L <= min(size[0], size[1], P)
)
• We assume that cell address inputs always follow the Excel-like format of one letter (A-Z or a-z) plus
one integer (1-26). Uppercase or lowercase inputs like "A1", "c6", or even having some spaces in the
string like " b 5 " will be accepted as normal. Use exception handling techniques in the get_input()
method of Player to avoid program crash due to weird inputs like "AA1", "A01", "abc", "A3.14",
"#a2", … for cell addresses, which may raise ValueError when getting the user input.
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
10
• There is no draw game based on the official game rules. Due to the repelling effect, it is possible that
a move may cause both players to form a line of L pieces at the same time. In this case, the official
game rules regard the moving player as the winner. The same applies to the case that the moving
player putting his/her last piece on the board but causing the opponent to form a line.
OO Design for this Game
You must use OOP to develop this program. Refer to the UML class diagram below for the OO design for
this program.
Figure 7: UML class diagram for the game program design
Note: For the operations or methods in the UML diagram, we omit the self parameter which is Pythonspecific and not meaningful in UML which is independent of the OOP language being used.
This question aims at testing your implementation skills rather than your OO design skills. Therefore,
whenever possible, just follow our given design in your submitted code (while you are encouraged to try
other designs in your own separate code versions that need not be submitted). But you are allowed to add
extra (private) attributes or methods to facilitate some tasks when you see it fit. If you would do so, it is
better to name them with an underscore, e.g., you may write a private method _game_winner() in the
Gekitai class to determine which player has won the game.
Some points to assist your understanding of the UML diagram and coding:
• A player holds P pieces. In OO terms, one Player object aggregates P Piece objects.
• Gekitai is a two-player board game. So, one Gekitai object aggregates 2 Player objects.
• In coding, we usually use an array or list to realize an aggregation relationship, e.g., for the Player
class, define an instance variable which is a list of P Piece objects.
Specification of Each Required Class
To allow our grading by unit testing your functions, you are required to follow the following specification
when implementing each class.
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
11
Color Enum Class
Pieces and players should have a color attribute for identification purpose. Regarding this, a simple way
can be adding an integer 0 or 1 to the objects to distinguish black from red. But we recommend using an
enumeration class to define a new type for color. Check out the enum module in Python. For example, you
can define the following Color class by extending Enum:
from enum import Enum
class Color(Enum):
BLACK = 'X'
RED = 'O'
c = Color.RED
Then you can get the name string 'RED' via c.name and the value string 'O' via c.value.
Piece Class
Attributes:
• color: the color identifying which player this piece belongs to
Methods:
__str__(self) -> str
Override the __str__() special method to print the Piece object as a string showing the 'X' or 'O' symbol
instead of the object’s type and memory address.
Player Class
Attributes:
• color: the color identifying the player
• pieces: a list of Piece objects which represent game pieces that are with the player, i.e., pending to
be put onto the game board.
Methods:
get_input(self) -> tuple[int, int]
Prompt the user (current player) for a cell address input (Excel-format) by showing the prompt message:
"Player X's turn: " or "Player O's turn: ". Convert the string into a tuple (y, x) and return
it, where y and x (zero-based indexes) refer to the target cell at row y and column x. The conversion must
handle possible ValueError exceptions due to wild user inputs. In this case, the handler simply returns
the tuple (-1, -1) that represents an invalid move, which will be detected by the is_move_valid()
method of the Gekitai class (to be discussed later).
__str__(self) -> str
Override the __str__() special method to print the Player object as a string showing the 'X' or 'O'
symbol instead of the object’s type and memory address.
Gekitai Class
Attributes:
• cells: a nested list (2D array) implementing the game board. Each element (representing a cell) is
storing either a Piece object or something such as None that represents an empty cell.
• rows: the number of rows for the cells array
• cols: the number of columns for the cells array
• players: a list of the two Player objects
• P: the total number of pieces given to each player
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
12
• L: the (least) number of pieces required to form a line
Methods:
is_move_valid(self, y: int, int x: int) -> bool
Return True if it is valid to move a piece onto the board at row y and column x (zero-based indexes), i.e.,
if the element cells[y][x] is an empty cell. Otherwise, it returns False. If x and y are beyond the
board’s boundaries, it also returns False.
This method must be called inside the move() method to confirm that the move is valid before it updates
the cells array. This method will also be called by the start() method, which will keep prompting the
current player to enter the cell address again until it is a valid move.
move(self, piece: Piece, y: int, x: int)
Provided that (y, x) is a valid position, this function carries out updates of the cells array to actualize
the effects of moving a piece of the current player into the cell at row y and column x (zero-based indexes).
This includes setting the element cells[y][x] to piece and moving its adjacent pieces (the 8 possible
cells surrounding cells[y][x]) outward by one square if there is open space for them to move into. And
if there are any pieces being shoved off the board by this move action, they are recycled to the
corresponding player’s pieces list.
line_formed(self, player: Player) -> bool
Return True if it can find L consecutive pieces in a line on the board that belong to the specified player,
and False otherwise. Calling this method will be useful to assist determining whether the game is over.
When it returns True, that means the specified player has won.
print_board(self)
Print the game board in the format as shown in Figure 6. Besides printing the game board, it also prints
the list of pieces that are still with each player, i.e., those that are not yet on the board. See our provided
Sample Runs to know more.
start(self)
This method implements the main loop of the game. It keeps printing the game board, prompting players
to make moves in turns, and detecting who has won the game and printing the game-over message.
This method will call the following methods (directly or indirectly via your extra methods, if any):
• print_board() to print the game board;
• get_input() of each Player object to get the cell address input from the current player;
• is_move_valid() to check if the input (y, x) is a valid move;
• move() to actualize a move, repelling adjacent pieces if any;
• line_formed() to see if the game should end.
If the move entered by the player is not a valid one, print the error message "Invalid move!" and
prompt the player for a new input again. Repeat this until the input is valid.
This method also prints the game-over messages like "Game over:", "Player X wins!" and the final
game board when the game ends. See Sample Runs for the expected output.
Notes:
• You should avoid using global variables whenever possible (except for those that are read-only). If some
constant is needed and relevant to a certain class, you may define it as a class variable in that class.
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
13
• Defining some class or static methods is also allowed if it can help. But better name them with a leading
underscore (meaning private) if they are not meant to be used by the outside world.
• Don’t perform something more than required in each specified method, i.e., keep the implementation
of each function minimal (or “do one thing and do it well”). For example, in the move() method, its
only duty is to actualize the move by updating the cells array. Checking whether the move is valid or
whether a line has been formed is the duty of the other methods. The is_move_valid() method, on
the other hand, should not perform any board updates but checking the move’s validity alone. Violating
this rule will hamper our unit testing of your program and you may lose marks.
• Your program should include suitable, concise comments as documentation. Each class must have a
“doc string” to describe what it is (our sample program has purposely omitted all docstringsso that you
cannot copy them by doing help() on the class). You are also highly encouraged to do the same at
method level. Missing class-level doc strings may invite some mark deduction.
Sample Runs
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
Player O wins!
Sample Executable
For more sample runs, you can execute our provided modules in binary format:
• q3sample.so (for macOS)
• q3sample.pyd (for Windows)
Put the corresponding binary file in your current directory. Start a Python shell and type the following to
start a game using the default configuration for size, P and L.
from q3sample import Gekitai
game = Gekitai()
game.start()
If you want to customize any of size, P and L, it is just a matter of passing valid arguments when
constructing the game object. For example,
from q3sample import Gekitai
Gekitai((7, 7), 9, 4).start()
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
18
Important Note: The sample executable was built in the latest Python 3.12.2 environment. This requires
a Python runtime of 3.12.x to execute it. Using an older Python runtime like 3.9 may run into subtle import
errors such as not able to find or load the module. You may create a virtual environment using conda and
install Python 3.12 to run the executable.
Question 4 (20%)
Write a Python script (q4.py) to implement the following UML diagram:
Figure 8: UML class diagram for a “polymorphic” file explorer
The File classis an abstract base class. It can be made abstract by deriving it from the metaclass ABCMeta
or from the helper class ABC from the abc module and declaring an abstract instance method in the class.
The abstract method is called explore().
This File class resembles but simplifies the os.DirEntry class and has only three attributes below
whose semantics are the same as those defined under os.DirEntry (check their documentation):
• path – the full path of the file object on the file system
• size – size of the file in bytes
• mtime – last modified time expressed in seconds
This abstract class is realized into two concrete subclasses Directory and RegularFile, where the
RegularFile classis further extended into three subclasses HiddenFile, TextFile and ScriptFile,
which exhibit different behaviors when running their own versions of the explore() method. Refer to
Table 1 for how to implement all these classes.
To ease your testing, a zip of a sample directory has been provided. Unzip the file q4-sample-dir.zip and
put the directory q4-sample-dir in the same directory containing q4.py. Run the following client code and
refer to Sample Run or our given q4-output.txt for the expected output:
sample_dir = Directory('q4-sample-dir')
sample_dir.explore()
Reminder:
Italic means “abstract”.
That is, File is an abstract
base class with an abstract
method called explore().
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
19
Table 1. Description of the Subclasses Involved
Subclass Superclass Methods (and Behaviors to perform)
Directory File list() Returns a list of file objects sorted by their path
values under the directory specified by the path
attribute of this Directory object.
Hint: use the scandir() function in the os module
which returns a list of DirEntry objects. For each
entry in the list returned, create an object with a
correct type based on to the rules below:
• Directory: entries that return True when
is_dir() is called upon
• RegularFile: entries that return True when
is_file() is called upon
• HiddenFile: regular files of names starting with a
dot '.'
• TextFile: regular files of names ending with
'.txt'
• ScriptFile: regular files of names ending with
'.py'
Create each object with its path, size and mtime
attributes populated with their values retrieved from
the corresponding DirEntry object.
explore() Calls the list() method to get a list of all file objects
under the directory specified by the path attribute.
For each entry, print its path and call its explore()
method.
For consistent output, when printing file paths, make
sure that the file path separators follow the POSIX
convention (/) instead of the NT convention () even if
the program is running on Windows.
RegularFile File explore() Prints a string
"last modified: <lm> size: <size> bytes"
<lm> is a date time string of the following format:
YYYY-MM-DD HH:MM:SS
e.g. 2024-03-09 00:18:39
HiddenFile RegularFile explore() Does nothing
TextFile RegularFile explore() Opens the text file and prints its content.
ScriptFile RegularFile explore() Executes the Python script file.
Notes:
• For simplicity, assume that there are no symbolic links and hidden directories (i.e., directory namesthat
start with a dot) involved but hidden files may exist. And script files are always in Python only.
AIST1110 Introduction to Computing Using Python 2023-24 Term 2
Department of Computer Science and Engineering, The Chinese University of Hong Kong
20
More Hints:
• Populate the size and mtime attributes of File with the st_size and st_mtime attributes of the
os.stat_result object returned by the stat() method of os.DirEntry.
• The datetime class in the datetime module provides a class method fromtimestamp() that can
help produce the required last modified time string.
• To execute a Python script file, you may use the run() function in the subprocess module or the
system() function in the os module to call "python <script_file_path>".
Sample Run
Below is the expected output for the given client (no matter whether Windows or POSIX platforms).
q4-sample-dir/.DS_Store
q4-sample-dir/.hidden_file.txt
q4-sample-dir/assignment1.pdf
last modified: 2024-02-06 23:13:55 size: 289813 bytes
q4-sample-dir/assignment2.pdf
last modified: 2024-03-09 04:14:48 size: 737982 bytes
q4-sample-dir/hello_world.py
Hello, World!
q4-sample-dir/inner_dir
q4-sample-dir/inner_dir/.DS_Store
q4-sample-dir/inner_dir/dump.py
Love For All
0 1 2 3 4
q4-sample-dir/inner_dir/innermost
q4-sample-dir/inner_dir/innermost/.DS_Store
q4-sample-dir/inner_dir/innermost/dumper.py
Aspire to inspire before we expire!
0 1 2 3 4 5 6 7 8 9
q4-sample-dir/inner_dir/innermost/quotes3.txt
Abraham Lincoln - "Nearly all men can stand adversity,
but if you want to test a man's character, give him power."
Benjamin Harrison - "Great lives never go out; they go on."
q4-sample-dir/inner_dir/quotes2.txt
William Henry Harrison - "Times change, and we change with them."
John Quincy Adams - "Try and fail, but don't fail to try."
q4-sample-dir/quotes1.txt
John Adams - "To be good, and to do good, is all we have to do."
Abraham Lincoln - "God must love common-looking people.
That's why he made so many of them."
请加QQ:99515681 邮箱:99515681@qq.com WX:codehelp
标签:
扫一扫在手机打开当前页
注:本网条致力提供真实有用信息,所转载的内容,其版权均由原作者和资料提供方所拥有!若有任何不适烦请联系我们,将会在24小时内删除。
无相关信息 昆明生活资讯
昆明图文信息