Python - play it for fun

Python: play it for fun

标签:Python


Introduction

光给字典一样的教程不是很无聊嘛,不如一边玩一边学吧。
看完这篇博客就可以完成一个小游戏噢~


下载安装

鉴于 numpy 过几年就要停止 python2 了,以后能用 python3 就用 3 不要犹豫。
在官网下载好对应版本安装,windows 记得配一下环境变量。
在 linux 下不管后缀名是不是 .py 都可以运行只要第一行加

#!/usr/bin/python

如果找不到 python 程序,就用 env 去找或者自己手动定位到程序的位置

#!/usr/bin/env python

写代码嘛,个人喜欢用 sublimectrl+b 编译运行,但是输入数据的时候会发现不行,可以去安装插件 SublimeREPL,默认 F5 可以运行,或者在 Preferences -> Key Binding 自行添加热键

{
    "keys":["f5"],
    "caption":"SublimeREPL:Python - RUN current file",
    "command":"run_existing_window_command","args":
    {
        "id":"repl_python_run",
        "file":"config/Python/Main.sublime-menu"
    }
}

基本语句:wumpus hunt

既然学过C语言,话不多说,就看看Python的特别之处!下面是一个小游戏:

#wumpus hunt v1.0
from random import choice
cave_numbers = range(1, 10)
wumpus = choice(cave_numbers)
print("Welcome! Darling! Here is ", len(cave_numbers), " caves")
while True:
    your = input("input you position>")
    if (not your.isdigit()) 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!")        

预设了目标位置,玩家输入猜测的位置看能不能猜中!

in or not in

直接用 in 判断是否是子串,在C语言里还要调用函数 strstr 要烦一点。

True: "ab" in "abcde"
False: not "ab" in "abcde"
False: "xyz" in "abcde"
True: not "xyz" in "abcde"
True: "xyz" not in "abcde"

或和且 用 or and

if while for

一开始容易忘了在这几句话写完以后要加 : ,不然肥肠容易报错。

True False

注意首字母大写,如上面代码的第6行。

input()

python3 里的输入没有 raw_input() 了,输入默认都是字符串类型,所以当输入的是数字时注意强制转换。如上面代码的第8,11行。


加入管道地图

对上面的游戏做一些限制,设置联通道路的约束

# wumpus hunt v2.0
from random import choice
cave_numbers = range(1, 10)
wumpus = choice(cave_numbers)

tunnel = []     # 新加入的管道地图
for i in range(10):
    t = []
    while len(t) < 3:
        r = choice(cave_numbers)
        if r not in t:
            t.append(r)
    print(t)
    tunnel.append(t);
print(tunnel)

print("Welcome! Darling! Here is ", len(cave_numbers), " caves")
player = wumpus
while player == wumpus:
    player = choice(cave_numbers)
while True:
    print("You're in cave ", player, " to choose")
    print(tunnel[player])
    your = input("input you position>")
    if not your.isdigit():
        print("Not a number")
        continue
    old_player = player
    player = int(your)
    if player 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!") 

range()

表示自然数范围:

  • 若有三个参数,前两个参数表示左闭右开的区间,第三个参数表示增量值
  • 若有两个参数,即第三个参数默认为1
  • 当有单个参数时,即第一个参数默认为0
for x in range(2, 50, 6):
    print(x)
==============================
2
8
14
20
26
32
38
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}
仔细看的话,上面的代码的cave编号从1到9,但地图却有从0出发的路线,是多余的安排。看在对运行没影响,所以姑且不做处理。

list

可以放进不同类型元素(字符串、数字、list等)的数组,且有很多简便的操作

arraylist = ['mother', 'father', 45, 77]
print(arraylist)
arraylist.append(10)   // 增加到末尾
arraylist.remove(45)   // 找到对应元素并删除
cut = arraylist[-2:]   // 倒数第2个元素开始到末尾

下面有个诡异的地方,这里Python变量不是传统意义上的变量,实际上是指向内存的指针,所以

a = [10]
b = a
a[0] = 20
print(b)
a = 30
print(b)
================================
[20]
[20]

可以将区间直接转化到 list 放进去

arr = list(range(2, 50, 6))
print(arr)
=================================
[2, 8, 14, 20, 26, 32, 38, 44]

坑人的地图

随机生成的地图倒是很有可能出现不连通的情况,难不成让玩家一直白忙活?还是一开始就写好能愉快胜利的地图吧!

# wumpus hunt v3.0 - tunnel
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)

这段地图生成从1开始,慢慢加入未访问过的点,生成双向边,得到完一副连通图。为了让条件更加丰富,再随机加入一些单向边。


封装函数

有些代码块可以被替换成函数,使整个代码看起来更加整洁。比如生成地图的部分,以后也可以考虑新的生成办法,只需要改动子函数就足够了。

# 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("You're in cave ", player, " to choose")
    print(tunnel[player])
    your = input("input you position>")
    if not your.isdigit():
        print("Not a number")
        return -1;
    return int(your)

cave_numbers = range(1, 10)
wumpus = choice(cave_numbers)
tunnel = create_tunnels(cave_numbers)
player = wumpus
while player == wumpus:
    player = choice(cave_numbers)

print("Welcome! Darling! Here is ", len(cave_numbers), " caves")
while True:
    old_player = player
    player = follow_new_step(player)
    if player 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!") 

后续

考验想象力的时刻到了,新功能和洞穴名字balabala请随意添加修改……

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页