Details of this Paper

PYTHON PART 1 List Module and PART 2 SnakeGame

Description

solution


Question

PART ISPECIFICATION ?WRITING A PYTHON MODULE (LIST MANIPULATION FUNCTIONS);You are required to implement a Python module containing the following functions;1.Write a function called length(my_list)that takes a list as a parameter and returns the length of the list. You must use a loop in your solution.You must notuse built-in functions, list methods or string methods in your solution.;2.Write a function called to_string(my_list, sep=', ')that takes a list and a separator value as parametersand returns the stringrepresentationof the list (separated by the separator value) in the following form;Listis: item1, item2, item3, item4;The separator value mustbe a default argument. i.e. sep=',;You must use a loop in your solution. You must notuse built-in functions (other than the range()and str()functions), slice expressions, list methods or string methods in your solution.You may use the concatenation (+) operator to build thestring.;3.Write a function called count(my_list, value) that takes a list and a value as parameters. The function searches for the value in the list and returns how many times the value appears in the list. You may assume that the elements of the list can be compared using the comparison operators ==, !=, etc. You must use a loop in your solution. You must not use built-in functions (other than the range()function), list methods or string methods in your solution.;4.Write a function called find(my_list, value) that takes a list and a value as parameters. The function searches for the value in the list and returns the index at which the first occurrence of value is found in the list. The function returns -1 if not found. You must use a loop in your solution. You must not use built-in functions (other than the range() function), slice expressions, list methods or string methods in your solution.;5.Write a function called starts_with(list1, list2)that takes two lists as parameters. The function returns True if list1starts with list2, and False;otherwise. You may assume that the elements of the list can be compared using the comparison operators ==, !=, etc. You must use a loop in your solution. You must not use built-in functions (other than the range()function), list methods or string methods in your solution. Hint: Check that the length ofthe second list (list2) does not exceed the length of list1 before continuing to determine whether list1 begins with list2.;6.Write a function called remove_value(my_list, value)that takes a list and a value as parameters. The function returns a copyofthe list with all occurrences of the value removed from the list. You must use a loop in your solution. You may make use of the list_name.append(value)method in order to build the new list. You must not;use built-in functions(other than the range()function), slice expressions, list methods (other than the append()method) or string methods in your solution.;?;7.Write a function called insert(list1, list2, index)that takes two lists (list1 and list2), and an index as parameters. The function returns a copy of list1 with list2 inserted at the position specified by index.Check for the index value exceeding the list1 bounds. If the index value is greater than the list1 bounds, then make the index value the length of the list (i.e. append to the end of the list). If the index value is less than zero, then append to position 0 (i.e. the start of the list).You must use a loop(s) in your solution. You may make use of the list_name.append(value)method in order to build the new list. You must notusebuilt-in functions (other than the range()function), slice expressions, list methods (other than the append()method) or string methods in your solution.For example;list1= ["b", "o", "o", "m"];list2 = ["r", "e", "d"];index = 2;The call to insert(list1, list2, index)should return the new list as follows;["b", "o", "r", "e", "d", "o", "m"];8.Write a function called reverse(my_list, number)that takes a list and a number as parameters. The function returns a copy of the list with the first number of items reversed. Check for the number value exceeding the list bounds. If the number value exceeds the list bounds, then make the number value the length of the list. If the number value entered is less than two (including negative numbers), then return a copy of the list with no items reversed. You must use a loop(s)in your solution. You may make use of the list_name.append(value)method in order to build the new list. You must not use built-in functions (other than the range()function), slice expressions, list methods (other than the append()method) or string methods in your solution.For example;numList = [1, 2, 3, 4, 5,6, 7];number = 4;The call to reverse(numList, number)should return the new list;[4, 3, 2, 1, 5, 6, 7].;You must test your functions to ensure that they are working correctly. So you do not have to write your own test file, one has been provided for you. The partI_test_file.py file is a test file that contains code that calls the functions contained in the list_function.py module. Please do not modify the test file.;?;PRACTICAL REQUIREMENTS (PART I);It is recommended that you develop this part of theassessment in the suggested stages. Each stage is worth a portion of the marks. It is expected that your solution will include the use of: The supplied list_function.py module (containing the functions listed below).This is provided for you ?you will need to modify this file. Functions (length, to_string, count, find, starts_with, remove_value, insert, and reverse) implemented adhering to the assignment specifications. The supplied partI_test_file.py file. This is provided for you ?please DO NOT modify this file. Well constructed while loops. (Marks will be lost if you use break statements in order to exit from loops). Well constructed for loops. (Marks will be lost if you use break statements in order to exit from loops). Appropriate if/elif/else statements. Output that strictly adheres to the assessment specifications.;Good programming practice;o Meaningful variable names. Your solutions MAYmake use of the following built-in functions and methods;o Built-in functions range()and str().;o List method append()to create/build new lists. i.e. list_name.append(item).;Your solutions MAY ALSO make use of the following;o Concatenation (+) operator to create/buildnew strings.;o Comparison operators (==, !=,, etc).;o Access the individual elements in a list with an index (one element only). i.e. list_name[index].;o Use of any of the functions you have written as part of the assignment. i.e. length() function. Your solutions MUST NOT use;o Built-in functions (other than range()and str()functions).;o Slice expressions to select a range of elements from a list. i.e.;list_name[start:end].;o List methods(other than the append()method. i.e. list_name=.append(item)).;o String methods. NOTE: Do not use break, or continue statements in your solution ?doing so will result in a significant mark deduction.Do notuse the quit()or exit()functions as a way to break out of loops.;MUST be running Python 3.4.1;?;SAGES (PART I);Stage 1;You will need both the list_function.py and partI_test_file.py files for this assessment. These have been provided for you. Ensure that they are in the same directory as each other. Test to ensure that this is working correctly by opening and running the partI_test_file.pyfile.;If this is working correctly, you should now see the following;output in the Python shell when you run your program;Start Testing!;length Test;In function length();List length: None;In function length();List length: None;to_string Test;In function to_string();None;In function to_string();None;In function to_string();None;count Test;In function count();None;In function count();None;In function count();None;find Test;In function find();None;In function find();None;starts_with Test;In function starts_with();None;In function starts_with();None;In function starts_with();None;remove_value Test;In function remove_value();None;In function remove_value();None;insert Test;In function insert();None;In function insert();None;In function insert();None;?;reverse Test;In function reverse();None;In function reverse();N;one;In function reverse();None;----------;length Test;In function length();List length: None;to_string Test;In function to_string();None;In function to_string();None;count Test;In function count();None;find Test;In function find();None;starts_with Test;In function starts_with();None;In function starts_with();None;remove_value Test;In function remove_value();None;insert Test;In function insert();None;reverse Test;In function reverse();None;End Testing!;Stage 2;Implement one function at a time. The following implementation order is a recommendation only: length()to_string()count()find()remove_value()starts_with()insert() reverse() Place the code that implements each function in the appropriate place in the list_function.py file;For example, if you were implementing the length()function, you would place the code that calculates and returns the length of the list under the comment ?Place your code here?(within the length function definition) seen below.;# Function length() ? place your own comments here...:);def length(my_list);# This line will eventually be removed -used for development purposes only. print("In function length()");# Place your code here;Test your function by running the partI_test_file.py test file to ensure each function is working correctly before starting on the next function. Compare your output with the sample output provided (at the end of this document) to ensure that your function is working as it should.;Stage 3;Finally, check the sample output (see section titled ?Sample Output ?Part I? towards the end of this document) and if necessary, modify your functions so that:The output produced by your program EXACTLY adheres to the sample output provided. Your program behaves as described in these specs and the sample output provided.;?;PARTIISPECIFICATION ?CLASSIC SNAKEGAME;PRACTICAL REQUIREMENTS(PART II);It is recommended that you develop this part of the assessment in the suggested stages. Each stage is worth a portion of the marks.;Well constructed while loops. (Marks will be lost if you use break statements in order to exit from loops).;Well constructed for loops. (Marks will be lost if you use break statements in order to exit from loops). Appropriate if/elif/else statements.;Appropriate functions(collide, handleKeys and playSnakeGame). A list data type in order to implement the snake.;The graphics and game modules (these are provided for you?please do not modify them). Please note: You are not required to have extensive knowledge or understand either of these modules, you are only required to be familiar enough in order to be able to use them in order to complete.;Output and game play that strictly adheres to the assignment specifications.;Good programming practice;o Consistent commenting and code layout. You are to provide comments to describe: your details, program description, all variable definitions, functions;and every significant section of code.;o Meaningful variable names.;NOTE: Do not use break, or continue statements in your solution ? doing so will result in a significant mark deduction;MUST use Python 3.4.1;?;STAGES(PART II);Stage 1-setup;We are using a simple graphics package that has been built on top of Tkinter in order to implement the snake game. The module, called graphics, was written by John Zelle (for his book ?Python Programming: An introduction to Computer Science?). You may find it useful to refer to the short document (graphics.pdf) which describes the graphics module. You will need both the graphics.py and game.py modules for this.;The game.py module was written specifically for this assignment and will be used to implement the objects (snake?s body and food-it also uses the graphics module).;Ensure both modules (graphics.py and game.py) are in the same;directory as your part2.py file. A description of the game.py module is available towards the end of this document. Test to ensure that this is working correctly by placing the following code in your part2.py file;import graphics;# Width and height of the window;WIN_WIDTH = 500;WIN_HEIGHT = 500;# Create the graphics window for the;snake game (win is global)win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT);# Set background to white;win.setBackground("white");# For testing purposes only ? this will be removed in later stages.;point = graphics.Point(250, 250);circle = graphics.Circle(point, 20);circle.setFill('green');circle.draw(win);win.getMouse();win.close();Stage 2;Import the game module and test to ensure that this is working correctly by modifying stage 1 code as follows (the following code should be in your part2.py file);import graphics;import game;# Width and height of the window;WIN_WIDTH = 500;WIN_HEIGHT = 500;# Size of the game block objects (food and snake's body);BLOCK_SIZE = 20;# Create the graphics window for the snake game (win is global);win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT);# Set background to white;win.setBackground("white");# For testing purposes only ?this will be modified in later stages.;# Create the food block object -start in the middle of the;# screen -BLOCK_SIZE big, colour green, no image, no block type, 0 points;# *** image, block type and points are not used in this game so will always be;# *** None, None and 0 respectively.;food = game.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE;BLOCK_SIZE, "green", None, None, 0);# Draw the food block to the screen;food.draw(win);win.getMouse();win.close();GameBlock objects will be used to represent the snake?s body and food that the snake will ?eat?.;Stage 3;Define global variables needed to store the snake and direction needed for game play: the Snake (list which will store GameBlockobjects ?representing the snake?s body). direction (the direction the snake is moving).;import graphics;import game;######################################################################;######################################################################;#########################################################;#############;### The following are the only global variables that are allowed to be;### used in this(along with those mentioned in stage 10);# Width and height of the window;WIN_WIDTH = 500;WIN_HEIGHT = 500;# Size of the game block objects;food and snake's body);BLOCK_SIZE = 20;# Direction the snake is moving;direction = ";# List of GameBlock objects -snake's body;theSnake = [];# Create the graphics window for the snake game (win is global);win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT);# Set background to white;win.setBackground("white");# For testing purposes only ?this will be modified in later stages.;# Create the food block object -start in the middle of the;# screen -BLOCK_SIZE big, colour green, no image, no block type, 0 points;# *** image, block type and points are not used in this game so will always be;# *** None, None and 0 respectively;food = game.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE;BLOCK_SIZE, "green", None, None, 0);# Draw the food block to the screen;food.draw(win);win.getMouse();win.close();If it is working correctly, your output should be the same as the output produced in stage 2.;Stage 4;Write a function called playSnakeGame (this function will eventually contain;the code which allows the player to play one game of snake). For now, let?s move the following code into the function;# Create the food block object -start in the middle of the;# screen -BLOCK_SIZE big, colour green, no image, no block type, 0 points;# *** image, block type and points are not used in this game so will always be;# *** None, None and 0 respectively;food = game.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE;BLOCK_SIZE, "green", None, None, 0);# Draw the food block to the screen;food.draw(win);Call the function to ensure it is working correctly.;import graphics;import game;def playSnakeGame();# Create the food block object -start in the middle of the;# screen -BLOCK_SIZE big, colour green, no image, no block type, 0 points;# *** image, block type and points are not used in this game so will always be;# *** None, None and 0 respectively;food = game.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE;BLOCK_SIZE, "green", None, None, 0);# Draw the food block to the screen;food.draw(win);##############################################################;########;######################################################################;######################################################################;### The following are the only global variables that are allowed to be;### used in this(along with those mentioned in stage 10);# Width and height of the window;WIN_WIDTH = 500;WIN_HEIGHT = 500;# Size of the game block objects (food and snake's body);BLOCK_SIZE = 20;# Direction the snake is moving;direction = ";# List of GameBlock objects -snake's body;theSnake = [];# Create the graphics window for the snake game (win is global);win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT);# Set background to white;win.setBackground("white");# Play one game of snake.;playSnakeGame();win.getMouse();win.close();If it is working correctly, your output should be the same as the output produced in stage 2;?;Stage 5;Create the head and one body piece of the snake (the snake starts with a body length of two) and append it to theSnake list (this will be the first and second elementsof the list). The snake will always start in the middle of the window.;import graphics;import game;def playSnakeGame();global direction;global theSnake;# Create snake -Length of 2 blocks.;# Create the starting place for the snake -always in the middle of the window.;# Create a snake block object, positioned in the middle of the;# screen -WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE big, colour red, no image;# no block type, 0 points block = game.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0);block.draw(win);# Add the GameBlock to the list (that makes up the snake's body).;theSnake.append(block);# Create the starting place for the snake -always in the middle of the window.;# Create a snake block object, positioned in the middle of the;# screen -WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE big, colour red, no image;# no block type, 0 points;block = game.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0);block.draw(win);# Add the GameBlock to the list (that makes up the snake's body).;theSnake.append(block);# Create the food block object -start in the middle of the;# screen -BLOCK_SIZE big, colour green, no image, no block type, 0 points;# *** image, block type and points are not used in this game so will always be;# *** None, None and 0 respectively;food = game.GameBlock(100, 100, BLOCK_SIZE, BLOCK_SIZE,"green", None, None, 0);# Draw the food block to the screen;food.draw(win);######################################################################;######################################################################;######################################################################;### The following are the only global variables that are allowed to be;### used in this(along with those mentioned in stage 10);# Width and height of the window;WIN_WIDTH = 500;WIN_HEIGHT = 500;# Size of the game block objects (food and snake's body);BLOCK_SIZE = 20;# Direction the snake is moving;direction = ";# List of GameBlock objects -snake's body;theSnake = [];# Create the graphics window for the snake game (winis global);win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT);# Set background to white;win.setBackground("white");# Play one game of snake.;playSnakeGame();win.getMouse();win.close();Stage 6;Now let?s get the snake to move based on keyboard input from the player. The player controls the direction of the snake?s head (up = up arrow key, down = down arrow key, left = left arrow key or right = right arrow key), and the snake?s body follows.;There are a few things that we need to include in order to make the snake to move.;Part A;Define a function called handleKeys which will determine the key that was pressed and update the global variable direction accordingly.;# Handle key press event;def handleKeys(event);global direction;print('Key pressed', event.keysym, event.keycode);# Update direction of snake.;if event.keysym == 'Left;direction = 'Left;elif event.keysym == 'Right;direction = 'Right;elif event.keysym == 'Up;direction = 'Up;elif event.keysym ==;Down;direction = 'Down;In your program(at the end), if your GraphWin object is called win, add the lines;# Wait for events -key entry events;win.bind_all(' ', handleKeys);# Play one game of snake;playSnakeGame();# Wait for events -main loop;win.mainloop();The first line binds the function handleKeys()as an event handler for the event' '?any key being pressed. The second line makes the graphics window go into a loop waiting for events to occur. You can end the program by closing the graphics window.;This will not cause the snake to move at this stage, but if your program is working correctly, when you press a key on the keyboard, you should see output on the shell window that describes the key that was pressed, i.e.;Key pressed Right 39;Key pressed Down 40;Key pressed Left 37;Key pressed Up 38;?;Part B;Okay, now let?s get that snake to actually move... we will need a loop to do this;speed = 0.1 # Speed the snake is moving (delay speed).;playing = True # Still playing flag -set to False when game over conditions met;# Loop while still playing -i.e. we have not encountered game over condition(s);while playing;Within the (while playing) loop: Write the code to move the snake?s body.;Moving the snake?s body as the snake moves forward, the whole body follows. This will require updating all of the points in the body of the snake (list). Use a for loop to update/move the snake. Your loop should start at the last element of the snake list and loop backwardsto the first element of the snake list. As you iterate;through the snake list, the current element should be updated to move to the position of the element in front of it.;The following algorithm may help you with this;for k in range(last element of snake list to first element of snake list);i.e. range(len(theSnake)-1, 0, -1);moveX = theSnake[k-1].getCentreX() ? theSnake[k].getCentreX();moveY = theSnake[k-1].getCentreY() ?theSnake[k].getCentreY();move theSnake[k] to new position (coordinates of moveX, moveY) using method move;Move the position of the snake?s head(calling method move()).;# Update the position of snake's head based on user input.;if direction == 'Left;theSnake[0].move(-MOVE_DISTANCE, 0);elif direction == 'Right;theSnake[0].move(MOVE_DISTANCE, 0);elif direction == 'Up;theSnake[0].move(0, -MOVE_DISTANCE);elif direction == 'Down;theSnake[0].move(0, MOVE_DISTANCE);Add a delay after each move in order to slow down the snake?s movement (otherwise it is moving way too fast).;# Slow down snake?s movement.;time.sleep(speed);Putting it all together (check your solution against this solution in case your code is not working correctly);import graphics;import game;# Import python standard modules.;import random;import time;import math;# Handle key press event;def handleKeys(event);global direction;print('Key pressed', event.keysym, event.keycode);# Update direction of snake.;if event.keysym == 'Left;direction = 'Left;elif event.keysym == 'Right;direction = 'Right;elif;event.keysym == 'Up;direction = 'Up;elif event.keysym == 'Down;direction = 'Down;def playSnakeGame();global direction;global theSnake;# Create snake;-;Length of 2 blocks.;# Create the start;ing place for the snake;-;always in the middle of the window.;# Create a snake block object, positioned in the middle of the;#;screen;-;WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE big, colour red, no image;#;no block type, 0 points;block = g;ame.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0);block.draw(win);# Add the GameBlock to the list (that makes up the snake's body).;theSnake.append(block);# Create the starting place for the snak;e;-;always in the middle of the window.;# Create a snake block object, positioned in the middle of the;#;screen;-;WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE big, colour red, no image;#;no block type, 0 points;block = game.GameBlock(WIN_WIDT;H//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0);block.draw(win);# Add the GameBlock to the list (that makes up the snake's body).;theSnake.append(block);# Create the food block object;-;start in the middle of th;e;# screen;-;BLOCK_SIZE big, colour green, no image, no block type, 0 points;# *** image, block type and points are not used in this game so will always be;# *** None, None and 0 respectively;food = game.GameBlock(100, 100, BLOCK_SIZE, BLO;CK_SIZE;green", None, None, 0);# Draw the food block to the screen;food.draw(win);speed = 0.1 # Speed the snake is moving (delay speed).;playing = True # Still playing flag;-;set to False when game over;conditions are met;# Loop while still playing;-;i.e. we have not encountered game over condition(s);while playing;# Move the snake's body.;#;for;loop here...;# Update the position of snake's he;ad based on user input.;if direction == 'Left;theSnake[0].move;-;MOVE_DISTANCE, 0);elif direction == 'Right;theSnake[0].move(MOVE_DISTANCE, 0);elif direction == 'Up;the;Snake[0].move(0;-;MOVE_DISTANCE);elif direction == 'Down;theSnake[0].move(0, MOVE_DISTANCE);# Slow down snake's movement.;time.sleep(speed);####################################################;##################;######################################################################;######################################################################;### The following are the only global variables that are allowed to be;### used in this(along with those mentioned in stage 10);# Width and height of the window.;WIN_WIDTH = 500;WIN_HEIGHT = 500;# Size of the game block objects (food and snake's body).;BLOCK_SIZE = 20;# Move displacement of game block (i.e. snake's body).;MOVE_DISTANC;E = 20;# Direction the snake is moving.;direction = ";# List of GameBlock objects;-;snake's body.;theSnake = [];# Create the graphics window for the snake game (win is global).;win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT);# Set background t;o white.;win.setBackground("white");# Wait for events;-;key entry events.;win.bind_all(' ', handleKeys);# Play one game of snake.;playSnakeGame();# Wait for events;-;main loop.;win.mainloop();If your code is working correctly, your snake (the two GameBlock objects that we added to the list) should now be moving on the screen based on keyboard input from the player. The snake should be moving up when the up arrow key is pressed, left when the left arrow key is pressed, and so on. You will need to press a direction key(up, down, left, right) before the snake starts to move.;Stage 7;You will notice that at the moment the snake does not stop moving (i.e. game over) when it hits the boundary. Write code that will check to see whether the snake has hit the boundary, if it has, stop playing (i.e. stop looping by setting variable playing = False).;Refer to the comments through the code in stage 9if you need help with where this section of code should be placed. Place your code under the corresponding comments.;Stage 8;You will also notice that at the moment, the snake does not currently ?eat? the food (represented by the green block). Write a function called collide which checks for collisions between the snake and the food. The function should take in the head of the snake and the food block as parameters and return either a True or a False depending on whether the two collide. Call this function in order to determine whether it is working correctly. When the food and snake?s head collide (i.e. the snake eats the food), cause the old food to be removed (function undraw()) and place the new food at a random location on the window.;Collision algorithm;if the distance between the centre point of the snake?s head and the food

 

Paper#65088 | Written in 18-Jul-2015

Price : $207
SiteLock