Python-play it for Fun__python

Source: Internet
Author: User
Python:play it for fun

It's not boring to give the same tutorial as a dictionary, so let's learn it while playing.
After reading this blog can complete a little game Oh ~ Download Installation

In view of NumPy in a few years will stop Python2, later can use the Python3 with 3 don't hesitate.
In the official website to download the corresponding version of the installation, Windows remember to match the environment variables.
In Linux, no matter whether the suffix name is. PY can run as long as the first line plus

#!/usr/bin/python

If you can't find a Python program, use env to find it or manually navigate to the location of the program

#!/usr/bin/env python

Write code, the individual likes to use sublime,ctrl+b compile to run, but when the input data will find no, can go to install plug-in SUBLIMEREPL, the default F5 can run, or in Preferences-> key Binding Add Hotkey

{
    "keys": ["F5"],
    "caption": "Sublimerepl:python-run Current File",
    "command": "Run_existing_window_ Command "," args ":
    {
        " id ":" Repl_python_run ",
        " file ":" Config/python/main.sublime-menu "
    }
}
Basic statement: Wumpus Hunt

Since I've learned C, I don't say much, just look at Python's special place. Here is a little game:

#wumpus Hunt v1.0 from
random import choice
cave_numbers = range (1)
Wumpus = Choice (cave_numbers)
Print ("welcome! darling! Here's, Len (cave_numbers), "caves") while
True:
    your = input (' Input you position> ')
    if (not Your.isdigi T ()) or (int (your) not in cave_numbers):
        print (' Not in any cave! ')
    else:
        player = int (your)
        if Wumpus = = Player:
            print ("You win!")
            Break
        elif Wumpus = = player+1 or Wumpus = = player-1:
            print ("Smell the Wumpus")
        else:
            print (" Continue to Guess! ")        

Preset the target position, the player input guessing position to see whether guessed. In or don't in

Directly in the judge whether it is a substring, in the C language to call the function strstr a bit annoying.

True: ' ab ' in ' abcde '
false:not ' ab ' in ' ABCDE '
False: ' xyz ' in ' ABCDE '
true:not ' xyz ' in ' ABCDE '
Tr UE: "XYZ" not in "ABCDE"

Or and and with or if while for

At first easy to forget in these words after writing to add:, otherwise the broth is prone to error. True False

Note that the first letter is capitalized, as in line 6th of the above code. input ()

The input in the Python3 is not raw_input () and the input defaults to the string type, so be aware of the cast when you enter a number. Like the 8th, 11 lines of code above. Add Pipeline Map

Make some restrictions on the above game, set the constraint of the Unicom road

# Wumpus Hunt v2.0 from random import choice cave_numbers = Range (1,) Wumpus = Choice (cave_numbers) tunnel = [] #
            Newly added piping map for I in Range (Ten): t = [] while Len (t) < 3:r = Choice (cave_numbers) if R is not in T:
T.append (r) print (t) tunnel.append (t); Print (tunnel) print ("welcome! darling! Here's, Len (cave_numbers), "caves") player = Wumpus while player = = Wumpus:player = Choice (cave_numbers) while Tr Ue:print ("You ' re in Cave", player, "to choose") print (tunnel[player) your = input ("Input for You position>" 
    If not Your.isdigit (): Print (' not a number ') Continue Old_player = player player = Int (your)
        If player not in Tunnel[old_player]: # slightly modified print (' Not in any cave! ')
            Player = Old_player else:if Wumpus = = Player:print ("You win!") Break elif Wumpus = = player+1 or Wumpus = = player-1: Print (Smell the Wumpus") Else:print (" Continue to Guess! ")  
Range ()

Indicates the range of natural numbers: if there are three parameters, the first two parameters represent the left open interval, and the third parameter represents the increment value if there are two parameters, that is, the third parameter defaults to 1 when there is a single argument, the first parameter defaults to 0

For x in range (2, 6):
    print (x)
==============================
2
8
32
44

Cave_numbers = Range (1, 10): = [1, 10) = [1, 9] = {1,2,3,4,5,6,7,8,9}
Range (3): = [0, 3) = [0, 2] = {0,1,2}
If you look carefully, the code above has a cave number from 1 to 9, but the map has a route from 0, which is redundant. Look at the operation has no effect, so do not handle. List

You can put an array of different types of elements (strings, numbers, lists, and so on) and have a lot of easy operations

ArrayList = [' mother ', ' father ', a.]
print (ArrayList)
Arraylist.append (+)   //Add to end
Arraylist.remove   //Find the corresponding element and delete the cut
= arraylist[-2:]   ////Countdown 2nd element start to end

Here's a weird place where Python variables are not variables in the traditional sense and are actually pointers to memory, so

A = [ten]
B = a
a[0] =
print (b)
a =
print (b)
================================
[A]
[20]

You can transfer the range directly into the list.

arr = List (range (2, 6))
print (arr)
=================================
[2, 8, 14, 20, 26, 32, 38, 44]
Deceptive's Map

Randomly generated map is very likely to be disconnected, it is difficult to let the player has been white busy. It's still a good time to write a happy victory map.

# Wumpus Hunt v3.0-tunnel
tunnel = [] for
x in range (Ten):
    tunnel.append ([])
visited = [1]
unvisted = List (cave_numbers)
Unvisted.remove (1) while
unvisted!= []:
    x = Choice (visited)
    if Len (tunnel[x)) >= 3:
        continue
    y = choice (unvisted)
    tunnel[x].append (y)
    tunnel[y].append (x)
    Visited.append (y)
    unvisted.remove (y) for
T in tunnel: while
    Len (t) < 3:
        v = choice (cave_numbers )
        if v not in T:
            t.append (v)
print (tunnel)

This map generation starts from 1, slowly joins the inaccessible point, produces the bidirectional edge, obtains the connected graph. In order to make the conditions richer, then randomly add some one-way edges. Encapsulation Function

Some blocks of code can be replaced with functions to make the entire code look neater. For example, to generate a map of the section, you can also consider a new generation method, only to change the child function is enough.

# Wumpus Hunt v4.0 from random import choice def create_tunnels (cave_numbers): tunnel = [] for x in range (10): Tunnel.append ([]) visited = [1] unvisted = List (cave_numbers) Unvisted.remove (1) while unvisted!= []
        : x = Choice (visited) if Len (Tunnel[x]) >= 3:continue y = choice (unvisted) 
        Tunnel[x].append (y) tunnel[y].append (x) visited.append (y) unvisted.remove (y) for T in tunnel:
    While Len (t) < 3:V = Choice (cave_numbers) if v not in T:t.append (v) Print (tunnel) return tunnel def follow_new_step (player): print ("Your ' re in Cave", player, "to choose") p
        Rint (Tunnel[player]) your = input ("Input you position>") if not Your.isdigit (): Print (' not a number ')
    return-1;  return int (your) cave_numbers = range (1) Wumpus = Choice (cave_numbers) tunnel = Create_tunnels (cave_numbers) player = WUmpus while player = = Wumpus:player = Choice (cave_numbers) print ("welcome! darling! Here's, Len (cave_numbers), "caves") while True:old_player = player player = follow_new_step (player) if PL
        Ayer not in Tunnel[old_player]: print (' Not in any cave! ')
            Player = Old_player else:if Wumpus = = Player:print ("You win!")
            Break elif Wumpus = = player+1 or Wumpus = = player-1: Print ("Smell the Wumpus") Else:  Print ("Continue to Guess!")
follow-up

Time to test the imagination, new features and cave names Balabala please add changes ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.