Python Read in Battleship Board and Index It

Python for Beginners: Battleship

10 minute read

At the start of the Covid-19 pandemic, my friend Avery had an idea to create videos to help beginners learn about Python. He chose common games every bit the artery to explore and started by coding a simple game of Rock, Paper, Scissors. I thought it was a pretty neat idea, and Avery agreed to let me join in his efforts! This is the first 'lesson' I developed. I take made some tweaks since I presented information technology on video as I thought more about how to expand the game. I'll start posting each notebook and video as we make these videos!

Battleship for Beginners

battleship

Developed by:

              - Austin Montgomery - Avery Smith                          

Date: 27 April 2020

Introduction

In Avery's previous lesson, we saw the start steps of how to create Mario Party with Python. We saw examples of creating graphs, creating characters, and simulating dice. In this lesson, we will learn some more basic Python concepts including functions, lists, and if-else statements!

Lists

We saw examples of lists in our Mario Party example from final week.

              characters_list = ['Mario', 'Diddy Kong', 'Waluigi', 'Boom Boom']                          

Lists are Python objects that let us shop things in a convenient location so nosotros can find them later. It'southward like when you go to a shop with a list written down and so you can remember what you lot need.

Bananas, OJ, yogurt, Chewbacca onesie pajamas

Chewbacca

One nice thing well-nigh lists is that you are able to add together and remove things from them. Adding to a list is also known as 'appending.'

              characters_list.append('Luigi')                          

When you lot append to a list, the matter you lot are appending gets added to the last chemical element of the list. Removing something from a list works the same way.

              characters_list.remove('Boom Boom')                          

Lists besides let you find specific elements within them. Suppose we had forgotten which character was second in our list (Think that Python is 0-indexed, meaning that the first alphabetize is 0. So our second grapheme volition take an alphabetize of one). Nosotros could type:

and nosotros would meet that it was Diddy Kong!

Creating lists

We can manually add elements to our list like we did with our character_list simply sometimes that takes besides long or we don't know exactly what will go into our lists. Nosotros are able to fix that trouble by using 'for loops' and 'list comprehension.' Nosotros volition come across an example of list comprehension later on on just we will skip the details of it for now.

If-else statements

If-else statements are exactly what they say they are. If something is truthful, exercise this. If not, so practise that.

              if 'Mario' in characters_list:     print("Plumber detected") else:     print("How tin can this exist Mario Political party without Mario?!?")                          

Sometimes nosotros have more than two possible conditions. In these situations, we can utilize an 'elif' (combining else and if). Allow'southward say that you ask your friend who their favorite Mario Party character is. Your response to them will depend on their favorite character.

              if friend_favorite == 'Mario':     print('Irksome') elif friend_favorite == 'Bowser':     print('But he is the bad guy!') else:     print('Absurd')                          

Elif isn't used that often but information technology'southward proficient to understand how to call up about conditions like these.

Functions

Sometimes we find ourselves writing the same code over and over again. A good rule of thumb is that if you ever write the aforementioned code 3 times or 3more, it's time to write a function.

What is a office?

A function is a chunk of code that runs when y'all tell information technology to. It breaks your program into smaller chunks and makes it more organized.

How do I build a part?

When yous build a part you must starting time define information technology; what will the role exist named? This is done by typing def followed by your chosen role name, parentheses, and a colon.

Subsequently defining y'all function, you can put in the clamper of code you want to run each fourth dimension you telephone call the function.

              def random_character():     character_list = ['Mario', 'Luigi', 'Peach', 'Bowser']     random_num = random.randint(0, len(character_list) - one)     character = character_list[random_num] # Case of list indexing     return character                          

At present we have a part that volition give u.s.a. a random character anytime nosotros call it. Characters

How do I telephone call a office?

A function is called by but typing the role's name with the associated parentheses. The result of the function (in the above case, character) can also be assigned to a new variable if the effect is needed for later.

              random_character() # or new_character = random_character()                          

What are part parameters?

Function parameters are things that are 'passed into' a function. These parameters are typed in the parentheses when defining and calling a function. Let's say that instead of having the same character_list every fourth dimension in our random_character role, nosotros desire to be able to select from our original list. We will add a parameter to the part so an outside list can be used.

              def random_character(char_list):     random_num = random.randint(0, len(char_list) - 1)     character = char_list[random_num]     return character      new_character = random_character(['Mario', 'Diddy Kong', 'Waluigi', 'Boom Blast'])                          

Note that char_list is just a placeholder in our function. We can laissez passer in any list as a parameter for the part and it will work. Nosotros don't demand to pass in a variable already named char_list.

Battleship

At present that nosotros've learned some basic Python concepts, let'southward get started building a game of battleship.

Objective

Build a game where we gauge a row and column until we sink the CPU's randomly placed and randomly sized battleship.

Note: We oasis't learned how some of the code works. Information technology'southward okay to not sympathise how something works. Inquire questions along the way.

                              # Import random package to exist able to create random integers                                import                random                          

First detail of business is we need to build a board. The jail cell below is our first office that nosotros write called, y'all guessed it, build_board. build_board takes an integer equally a parameter for withal big of a square you desire.

We build the board with something called listing comprehension. Basically, we are proverb that we want to add an chemical element to the list withal many times nosotros tell it to. ['O' for count in range(dims)] will add together an 'O' to the listing 'dims' times. This list will and then be added to a listing (And then a listing of lists) 'dims' times.

                              # Create a square board based on dims value                                def                build_board                (                dims                ):                render                [[                'O'                for                count                in                range                (                dims                )]                for                count                in                range                (                dims                )]                          
              [['O', 'O', 'O', 'O'],  ['O', 'O', 'O', 'O'],  ['O', 'O', 'O', 'O'],  ['O', 'O', 'O', 'O']]                          

We built and printed our board merely it doesn't await very pretty. Allow'south write another function then that we become rid of the brackets, quotes, and commas.

The * symbol is use to print the list elements in a single line with a space. Nosotros use a for loop hither to print each list element.

                              def                print_board                (                lath                ):                for                b                in                lath                :                print                (                *                b                )                          
                              board                =                build_board                (                4                )                print_board                (                board                )                          
              O O O O O O O O O O O O O O O O                          

At present we're cooking with gas! Okay, time to build a transport. We want the send to exist in a random place on the board. Nosotros also don't want to know how long the transport is. We build our ship by placing the send coordinates into a listing. Steps to build our ship:

  1. Assign random length to ship
  2. Randomly decide if transport will be vertical or horizontal
  3. Depending on whether ship is vertical or horizontal, randomly select a row or column and then assign rest of send positions based on length and orientation.
  4. Render the list of ship coordinates
                              # Create and return transport positional coordinates                                def                build_ship                (                dims                ):                # Length of ship is random number between ii and length of board                                len_ship                =                random                .                randint                (                two                ,                dims                )                orientation                =                random                .                randint                (                0                ,                1                )                # Transport is horizontal if orientation is 0 and vertical if orientation is 1                                if                orientation                ==                0                :                # Randomly select row and create list of selected row * length of send                                row_ship                =                [                random                .                randint                (                0                ,                dims                -                1                )]                *                len_ship                # Randomly select column of start position of transport (Hence subtracting length of ship)                                col                =                random                .                randint                (                0                ,                dims                -                len_ship                )                # Create listing of cavalcade values                                col_ship                =                list                (                range                (                col                ,                col                +                len_ship                ))                # Create positional values from row and cavalcade lists                                coords                =                tuple                (                zero                (                row_ship                ,                col_ship                ))                else                :                # Same as higher up except switch column and row                                col_ship                =                [                random                .                randint                (                0                ,                dims                -                1                )]                *                len_ship                row                =                random                .                randint                (                0                ,                dims                -                len_ship                )                row_ship                =                listing                (                range                (                row                ,                row                +                len_ship                ))                coords                =                tuple                (                zippo                (                row_ship                ,                col_ship                ))                return                listing                (                coords                )                          
                              ship                =                build_ship                (                4                );                ship                          

We built a ship! We can run across our ship coordinates by calling ship after calling the office. (Retrieve that Python is 0-based indexed so a '0' really means the first cavalcade or row.

Now we demand to create a style for us to guess the coordinates of the CPU's ship. To allow for user input, Python has a built-in function called input(). Y'all can type whatever prompt you want into the input function.

It's important to know that calling input() volition return a string, or a bunch of grapheme types. Nosotros want our coordinates to be numbers, then we will convert them to numbers with the int() function (int for integer). We will as well subtract i from our guess so we don't take to remember that Python is 0-based indexed.

                              def                user_guess                ():                # Decrease 1 to accommodate for python 0-based indexing                                row                =                int                (                input                (                'Row: '                ))                -                1                col                =                int                (                input                (                'Col: '                ))                -                one                return                (                row                ,                col                )                          

Great! We guessed the offset row and 2d column and our function automatically converted it into a unmarried pair of numbers that will work with 0-based indexing.

When we make a guess, nosotros want the computer to know if we've already guessed information technology, if we hit the ship or if we missed. We volition create a part update_board that takes 4 parameters: our judge, the board, the ship, and a listing of all previous guesses. Then we will utilise if statements to update our board, guesses, and non-destroyed send coordinates. We will likewise have the reckoner print statements so we know the results of our judge!

                              def                update_board                (                gauge                ,                lath                ,                send                ,                guesses                ):                if                guess                in                guesses                :                print                (                'You already guessed that, dizzy!'                )                return                board                guesses                .                append                (                guess                )                if                approximate                in                ship                :                print                (                'You lot hit my battleship!'                )                # Update board with 'X' signifying a hit                                board                [                estimate                [                0                ]][                guess                [                1                ]]                =                'X'                # Remove this value from ship coordinates; useful for while loop in main()                                ship                .                remove                (                approximate                )                return                board                print                (                'LOL miss!'                )                return                board                          
                              # Since we oasis't made any guesses yet, we pass in an empty listing of guesses                                guesses                =                []                our_guess                =                user_guess                ()                lath                =                update_board                (                our_guess                ,                lath                ,                transport                ,                guesses                )                print_board                (                board                )                          
              Row: 2 Col: 2 You hit my battleship! O O O O O 10 O O O O O O O O O O                          

Terrific! We striking the battleship (we may have cheated by looking at the coordinates printed above lol). We made our guess and the computer told the states the outcome and what the lath now looks similar! We're almost at that place!

Let's create 1 more function. When we kickoff the game, let's have some instructions so we know what nosotros need to practice.

                              def                welcome_message                ():                print                (                'Welcome to Battleship!'                )                impress                (                'In that location is a battleship subconscious in this board. Enter your row and cavalcade guesses to sink it!'                )                          
              Welcome to Battleship! At that place is a battleship subconscious in this board. Enter your row and column guesses to sink information technology!                          

Now we have all the steps to brand our game! A good coding practice is to have a function at the terminate of your code that calls all your codes in one identify. This makes your program easy to read and organized! The function is traditionally named master().

In our main function, we have our instructions, we build a board and send, and nosotros create an empty listing of guesses. What's that while len(ship) > 0, though? Well our computer has to know how long to let us guess. This is a while loop. It says that while the length of the ship's coordinates is greater than 0, proceed asking for guesses (Call back we removed a ship coordinate if we guessed information technology correctly, then if nosotros hit all the coordinates, the ship's list of coordinates will be empty) and printing the lath. Once nosotros've guessed all the coordinates and the length of the ship's coordinates is 0, print out a victory message!

                              def                main                ():                welcome_message                ()                board                =                build_board                (                five                )                ship                =                build_ship                (                five                )                guesses                =                []                while                len                (                ship                )                >                0                :                board                =                update_board                (                user_guess                (),                lath                ,                ship                ,                guesses                )                print_board                (                board                )                print                (                'You sunk my battleship!'                )                return                          

We did it! Now merely telephone call the function! Accept fun playing!

mojicatheaut.blogspot.com

Source: https://bigmonty12.github.io/battleship

Belum ada Komentar untuk "Python Read in Battleship Board and Index It"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel