亚洲十八**毛片_亚洲综合影院_五月天精品一区二区三区_久久久噜噜噜久久中文字幕色伊伊 _欧美岛国在线观看_久久国产精品毛片_欧美va在线观看_成人黄网大全在线观看_日韩精品一区二区三区中文_亚洲一二三四区不卡

AIST1110代做、Python編程設(shè)計(jì)代寫

時(shí)間:2024-03-21  來(lái)源:  作者: 我要糾錯(cuò)



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."
請(qǐng)加QQ:99515681  郵箱:99515681@qq.com   WX:codehelp 

標(biāo)簽:

掃一掃在手機(jī)打開當(dāng)前頁(yè)
  • 上一篇:代做Lab 2: Time Series Prediction with GP
  • 下一篇:代做COMP226、代寫solution.R設(shè)計(jì)編程
  • 無(wú)相關(guān)信息
    昆明生活資訊

    昆明圖文信息
    蝴蝶泉(4A)-大理旅游
    蝴蝶泉(4A)-大理旅游
    油炸竹蟲
    油炸竹蟲
    酸筍煮魚(雞)
    酸筍煮魚(雞)
    竹筒飯
    竹筒飯
    香茅草烤魚
    香茅草烤魚
    檸檬烤魚
    檸檬烤魚
    昆明西山國(guó)家級(jí)風(fēng)景名勝區(qū)
    昆明西山國(guó)家級(jí)風(fēng)景名勝區(qū)
    昆明旅游索道攻略
    昆明旅游索道攻略
  • 短信驗(yàn)證碼平臺(tái) 理財(cái) WPS下載

    關(guān)于我們 | 打賞支持 | 廣告服務(wù) | 聯(lián)系我們 | 網(wǎng)站地圖 | 免責(zé)聲明 | 幫助中心 | 友情鏈接 |

    Copyright © 2025 kmw.cc Inc. All Rights Reserved. 昆明網(wǎng) 版權(quán)所有
    ICP備06013414號(hào)-3 公安備 42010502001045

    黄色片视频在线观看| 日韩精品免费| 亚欧色一区w666天堂| 欧美经典一区| 久久综合国产精品| 中文字幕一区二区三区四区| 日韩欧美黄色影院| 激情黄产视频在线免费观看| 91精品综合久久久久久久久久久| 欧美美女一区二区在线观看| 色婷婷综合久久久久久| 亚洲一区二区高清| 日韩久久综合| 国产美女精品| 秋霞影院一区二区三区| 国产精品av久久久久久麻豆网| 欧美视频免费看| 神马精品久久| 国产精品久久精品日日| 日韩影片在线观看| 黄色在线视频网站| 国产精品国产精品国产专区不蜜| 懂色中文一区二区在线播放| 丁香花在线电影| 亚洲另类黄色| 男女羞羞电影免费观看| 亚洲人成网站精品片在线观看| 在线观看不卡| 日本成人一区二区三区| 国产片在线观看| 久久精品伊人| 精品sm在线观看| 99re热这里只有精品视频| 美女久久久久| 91p九色成人| www国产在线观看| 免费国产在线观看| 性感美女激情视频在线观看| 中文字幕综合网| 国产精品久久占久久| 欧美专区视频| 精品视频国产| 美女爽到高潮91| 中文字幕日韩在线| av超碰在线| 色小子综合网| 1区不卡电影| av不卡在线看| 蜜桃传媒九九九| 国产午夜电影| 一本大道av一区二区在线播放| 麻豆极品一区二区三区| 国产精品99精品久久免费| 中文字幕一区二区三区乱码图片 | 欧美色国产精品| 天堂在线亚洲视频| 国产激情精品久久久第一区二区| 国产日产欧美一区| 日韩在线精品强乱中文字幕| 久久网站免费观看| 久久一本综合频道| 欧美精品中文| 在线免费观看黄色av| 久久久久久毛片| 精品一区二区三区中文字幕老牛| 国产毛片久久久| 黄色的视频在线免费观看| 91这里只有精品| 99精品老司机免费视频| 欧美性片在线观看| 亚洲精品视频区| 久久综合欧美| 无线免费在线视频| 成人网在线免费视频| 中文无码久久精品| 2024国产精品视频| 2019一级黄色毛片免费看网| 草民电影神马电影一区二区| 老司机精品视频网站| 日韩欧美aⅴ综合网站发布| 人人干在线视频| 成人四虎影院| 日韩不卡一区二区| 国产亚洲欧美日韩日本| 夜夜精品浪潮av一区二区三区| 黄色精品一区二区| 91.com在线观看| 日韩在线免费看| 黑丝美女一区二区| 欧美国产一区视频在线观看| 色屁屁一区二区| 日本视频一二区| 欧美人与牲禽动交com| 亚洲日本va| 欧美一区二区三区久久精品| 亚洲一区影音先锋| 国产在线xxx| 麻豆一区二区三区| 成人www视频网站免费观看| 国产三级视频在线看| 围产精品久久久久久久| 东方欧美亚洲色图在线| 好紧好硬好湿我太爽了| 欧美草逼视频| 日韩综合一区二区| 一区二区激情视频| 黄色羞羞视频在线观看| 精品一区二区三区在线视频| 亚洲亚洲精品在线观看| 91av久久| 综合一区二区三区| 欧美日韩精品一区二区三区| jzzjzzjzz亚洲成熟少妇| 午夜日韩视频| 国产精品久久久久影院| 国产激情在线视频| av一区二区在线观看| 国产成人免费视频网站| 欧美性xxxx极品hd欧美风情| 视频国产一区二区三区| 国一区二区在线观看| 欧美大肚乱孕交hd孕妇| 成人免费观看在线观看| 亚洲欧美在线专区| 国产精品毛片无遮挡高清| 天天色天天草天天射| 欧美大片1688| 亚洲欧美成人| 成全视频全集| 激情欧美丁香| 婷婷久久综合九色国产成人| 国产第一亚洲| 另类激情亚洲| 色偷偷成人一区二区三区91| 久久麻豆视频| 亚洲一区电影777| 日韩在线激情| 亚洲一区二区在线播放相泽| 91麻豆精品国产综合久久久 | 日本在线不卡视频一二三区| 免费一级淫片| 男女精品网站| 神马久久精品| 国产69精品一区二区亚洲孕妇| 成人免费网址| 国产网红主播福利一区二区| 伊人久久精品一区二区三区| 中文亚洲字幕| 欧美性大战久久| 亚洲播播91| 激情综合网天天干| www.亚洲免费| 国产精品a久久久久| 黄色大秀av大片| 美女网站色91| 黄页网站在线观看免费| 中文字幕中文字幕一区二区 | 不卡一区二区在线| 国产字幕中文| 午夜一级久久| 免费av网站在线看| 国产日韩欧美麻豆| 榴莲视频成人app| 国产日韩欧美亚洲| 国产精品视频一区视频二区 | 欧美视频一区在线| 在线中文字幕亚洲| 三级av在线播放| 99久久国产综合精品女不卡| 精品网站在线| 欧美日韩一区二区三区高清| 欧美视频亚洲视频| 99riav在线| 日韩毛片在线免费观看| 久久久免费毛片| 成人午夜激情| 成人免费毛片高清视频| 日韩av首页| 在线播放日韩导航| 久久一区激情| 成人在线黄色电影| 欧美午夜性色大片在线观看| 在线看片不卡| 国产日产一区二区三区| 亚洲一区二区精品视频| 在线一区免费| 亚洲丝袜精品| 国产在线精品一区二区不卡了| 国产精品视频一区二区图片| 免费不卡在线观看| 一区二区三区视频国产日韩| 国产综合色产| 先锋成人av| 欧美性生活大片视频| 久久天堂成人| 欧美韩国亚洲| 国产黄视频网站| 国产情人综合久久777777| 精品国产不卡| h片在线免费|