久久久久久精品无码人妻_青春草无码精品视频在线观_无码精品国产VA在线观看_国产色无码专区在线观看

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 

標簽:

掃一掃在手機打開當前頁
  • 上一篇:代做Lab 2: Time Series Prediction with GP
  • 下一篇:代做COMP226、代寫solution.R設計編程
  • 無相關信息
    昆明生活資訊

    昆明圖文信息
    蝴蝶泉(4A)-大理旅游
    蝴蝶泉(4A)-大理旅游
    油炸竹蟲
    油炸竹蟲
    酸筍煮魚(雞)
    酸筍煮魚(雞)
    竹筒飯
    竹筒飯
    香茅草烤魚
    香茅草烤魚
    檸檬烤魚
    檸檬烤魚
    昆明西山國家級風景名勝區
    昆明西山國家級風景名勝區
    昆明旅游索道攻略
    昆明旅游索道攻略
  • 短信驗證碼平臺 理財 WPS下載

    關于我們 | 打賞支持 | 廣告服務 | 聯系我們 | 網站地圖 | 免責聲明 | 幫助中心 | 友情鏈接 |

    Copyright © 2025 kmw.cc Inc. All Rights Reserved. 昆明網 版權所有
    ICP備06013414號-3 公安備 42010502001045

    久久久久久精品无码人妻_青春草无码精品视频在线观_无码精品国产VA在线观看_国产色无码专区在线观看

    国产黄色一级网站| 成年人视频大全| 熟妇熟女乱妇乱女网站| www黄色日本| 国产91在线亚洲| 亚洲日本黄色片| 爱爱爱爱免费视频| 国产一区二区在线免费播放| 看av免费毛片手机播放| 男女日批视频在线观看| 亚洲啊啊啊啊啊| 欧美日韩一级在线 | 欧美综合在线观看视频| 欧美精品久久久久久久久久久| 日韩中文在线字幕| 麻豆映画在线观看| 国产高清不卡无码视频| 欧洲美女和动交zoz0z| 99999精品| 一区二区三区国产好的精华液| 国产视频1区2区3区| 中文字幕 91| 国产无遮挡猛进猛出免费软件 | 色偷偷中文字幕| 在线观看中文av| 日本成人性视频| 亚洲精品国产suv一区88| 9l视频自拍9l视频自拍| 国产欧美123| www.射射射| 日韩视频第二页| 99草草国产熟女视频在线| 国产一线二线三线在线观看| 亚洲欧美在线精品| 欧美一级特黄aaa| 97久久国产亚洲精品超碰热| 欧美,日韩,国产在线| 国产一级不卡毛片| 亚洲人视频在线| 色婷婷777777仙踪林| 日韩精品在线观看av| 能在线观看的av| 午夜久久福利视频| 久久久久久久久网| 精品国产一二三四区| 777视频在线| 九九久久九九久久| 无码aⅴ精品一区二区三区浪潮 | 亚洲自偷自拍熟女另类| 亚洲一区二区蜜桃| 波多野结衣在线免费观看| 台湾无码一区二区| 亚洲爆乳无码专区| 国产九九九视频| 久草视频国产在线| 丁香婷婷激情网| 亚洲黄色网址在线观看| 国产96在线 | 亚洲| 冲田杏梨av在线| 国产免费内射又粗又爽密桃视频| 波多野结衣家庭教师在线播放| 手机版av在线| 丁香花在线影院观看在线播放| 九九热免费精品视频| 蜜桃视频一区二区在线观看| 国产精品无码av无码| 日韩中文在线字幕| 日本老熟妇毛茸茸| 国产成人艳妇aa视频在线| 91淫黄看大片| 黄色一级片黄色| 奇米影视四色在线| 久久综合九色综合88i| 亚洲欧美天堂在线| 国产成人无码一二三区视频| 日本免费在线视频观看| 日韩视频免费在线播放| 少妇一晚三次一区二区三区| jizz欧美性11| 中文字幕无码精品亚洲35| 久久久久久久久久毛片| 成人黄色片视频| 成人小视频在线观看免费| www.涩涩涩| 九色自拍视频在线观看| 国产精品嫩草影视| 成人性视频欧美一区二区三区| 国产精品va在线观看无码| 高潮一区二区三区| 日本男女交配视频| 国产又爽又黄ai换脸| 韩国一区二区av| 欧美综合在线播放| 中文字幕55页| 精品久久久久久久免费人妻| 欧美性受xxxx黑人猛交88| 熟女人妇 成熟妇女系列视频| 成人国产在线看| 亚洲国产精品三区| 久久精品xxx| 黄色一级片网址| 日本激情综合网| 日韩精品视频一区二区在线观看| 777久久精品一区二区三区无码| 免费av不卡在线| a在线观看免费视频| 亚洲国产精品毛片av不卡在线| 国产午夜大地久久| 97视频在线免费| 日韩黄色片在线| www.亚洲成人网| 久久人妻无码一区二区| 91九色国产ts另类人妖| 黄色一级视频播放| 国产又粗又大又爽的视频| 成年人网站av| 一本之道在线视频| 婷婷激情小说网| 欧美在线a视频| 日本高清免费观看| mm131午夜| 日本成人在线不卡| 成人在线视频一区二区三区| 国产精品久久国产| 丰满少妇大力进入| 精品视频免费在线播放| 欧美日韩二三区| 国产偷人视频免费| 99视频免费播放| 亚洲一区二区蜜桃| 欧美女同在线观看| 992kp免费看片| 成人性做爰片免费视频| 久久久久久久香蕉| 欧美久久久久久久久久久久久| 亚洲 欧美 日韩 国产综合 在线| 红桃一区二区三区| 欧美性猛交xxxx乱大交91| 99热一区二区| 伊人精品视频在线观看| 糖心vlog在线免费观看| 伊人久久在线观看| 99热久久这里只有精品| 国产在线播放观看| 亚洲精品中文字幕无码蜜桃| 国产精品人人爽人人爽| 精品亚洲一区二区三区四区| 女人扒开屁股爽桶30分钟| 天堂社区在线视频| 在线观看视频黄色| 人妻少妇精品无码专区二区 | 男女视频一区二区三区| 欧美午夜aaaaaa免费视频| 91高清国产视频| 超级碰在线观看| 欧美 日本 亚洲| 成人综合久久网| 蜜桃视频一区二区在线观看| 欧美日韩亚洲第一| 99九九99九九九99九他书对| 日韩专区第三页| 日韩毛片在线免费看| 波多野结衣免费观看| 精品无码一区二区三区爱欲| 国产精品亚洲二区在线观看| 91在线第一页| 国产二区视频在线播放| 中文av字幕在线观看| 男人添女荫道口喷水视频| 蜜臀av午夜一区二区三区| 亚洲一二区在线观看| 精品视频在线观看一区| 无尽裸体动漫2d在线观看| 国产一级大片免费看| 日本新janpanese乱熟| 特色特色大片在线| 狠狠热免费视频| 免费cad大片在线观看| 黄色三级视频在线| 亚洲熟妇无码av在线播放| 污色网站在线观看| 9久久9毛片又大又硬又粗| 五月天婷婷影视| 欧美 国产 日本| 国产日韩第一页| www.com操| 欧美在线观看成人| 男女激烈动态图| 中文字幕第88页| 国产aaa一级片| 国产乱子伦精品无码专区| 天堂av8在线| 37pao成人国产永久免费视频| 久久久久久久久久久久久国产| 激情五月婷婷久久| 免费一级特黄特色毛片久久看| 日韩欧美国产片| 丁香啪啪综合成人亚洲| 女人帮男人橹视频播放| 国产精品jizz在线观看老狼|