终端中的Python脚本

时间:2014-12-15 16:37:21

标签: python terminal

我是Python的初学者,我无法让我的一个脚本工作。

import random

def inputPlayerLetter():
    global Player, Computer
    letter = raw_input('Do you want to be X or O? \n')

    if letter == "X":
        print "You are now X's, you will go first"
        Player = "X"
        Computer = "O"
    elif letter == "O":
        print "You are now O's you will go second"
        Player = "O"
        Computer = "X"
    else:
    inputPlayerLetter()

inputPlayerLetter()

s1 = "*"
s2 = "*"
s3 = "*"
s4 = "*"
s5 = "*"
s6 = "*"
s7 = "*"
s8 = "*"
s9 = "*"

Spaces = [s1, s2, s3, s4, s5, s6, s7, s8, s9]

def Board():
    print ""
    print "",s1,"|",s2,"|",s3
    print "","---------"
    print "",s4,"|",s5,"|",s6
    print "","---------"
    print "",s7,"|",s8,"|",s9, "\n"

def Computer1():
    random.choice(Spaces)
    if random.choice(Spaces) == "s1":
        s1 = "X"
    elif random.choice(Spaces) == 's3':
        s3 = "X"
    elif random.choice(Spaces) == 's5':
        s5 = "X"
    elif random.choice(Spaces) == 's7':
        s7 = "X"
    elif random.choice(Spaces) == 's9':
        s9 = "X"
    Board()

Computer1()

当我在终端中运行时,这就是我得到的。

Do you want to be X or O? 
O
You are now O's you will go second

 * | * | *
 ---------
 * | * | *
 ---------
 * | * | * 

我如何制作这段代码,以便根据我在我的Computer1()函数中的随机选择,当它选择一个数字时,它会将指定的空间更改为X.我不知道如何制作这样的代码,以便如果当它执行此操作时,如果打印功能Board(),则板中的sN将更改为X.

2 个答案:

答案 0 :(得分:0)

random.choice(Spaces) == "s1":

这是将元素与字符串"s1"进行比较,这是永远不会成立的。你可能想要的是从列表中选择一个随机索引并分配给它:

Spaces[random.choice(range(1, len(Spaces)))] = "X"

答案 1 :(得分:0)

这是一个spiffed-up版本,使用列表来保存董事会状态和类以分离代码职责:

from itertools import cycle
import random

EMPTY   = " "
PLAYER1 = "X"
PLAYER2 = "O"

class Board:
    WINS = [
        # rows
        (0, 1, 2),
        (3, 4, 5),
        (6, 7, 8),
        # columns
        (0, 3, 6),
        (1, 4, 7),
        (2, 5, 8),
        # diags
        (0, 4, 8),
        (2, 4, 6)
    ]

    def __init__(self):
        self.bd = [EMPTY] * 9
        self.tokens = cycle([PLAYER1, PLAYER2])

    def __str__(self):
        return (
            "\n"
            " {} | {} | {}\n"
            " ---------\n"
            " {} | {} | {}\n"
            " ---------\n"
            " {} | {} | {}\n"
        ).format(*(self.bd))

    def available_moves(self):
        return [i for i,ch in enumerate(self.bd) if ch == EMPTY]

    def do_move(self, i):
        if self.bd[i] == EMPTY:
            self.bd[i] = next(self.tokens)
        else:
            raise ValueError("That spot is taken")

    def winner(self):
        for x, y, z in Board.WINS:
            tok = self.bd[x]
            if tok != EMPTY and tok == self.bd[y] and tok == self.bd[z]:
                return tok
        return None

class HumanPlayer:
    def pick_move(self, bd):
        moves = bd.available_moves()
        s = "".join(str(i) for i in moves)
        while True:
            try:
                mv = int(input("Which square do you wish to move to? [{}] ".format(s)))
                if mv in moves:
                    return mv
            except ValueError:
                pass

class ComputerPlayer:
    def pick_move(self, bd):
        return random.choice(bd.available_moves())

def get_players():
    hp = HumanPlayer()
    cp = ComputerPlayer()
    while True:
        tok = input("Do you want to play X or O?")
        if tok in {"x", "X"}:
            print("You go first:")
            return [hp, cp, hp, cp, hp, cp, hp, cp, hp]
        elif tok in {"o", "O"}:
            print("You go second:")
            return [cp, hp, cp, hp, cp, hp, cp, hp, cp]

def main():
    bd = Board()
    print(bd)
    for player in get_players():
        sq = player.pick_move(bd)
        bd.do_move(sq)
        print(bd)
        winner = bd.winner()
        if winner is not None:
            print("{} wins!".format(winner))
            break
    if winner is None:
        print("The game was a draw!")

if __name__=="__main__":
    main()