python让我自己逻辑混乱

Python/PHP/Perl 开发与设计
tommmm3
帖子: 10
注册时间: 2011-03-22 20:19
送出感谢: 0
接收感谢: 0

python让我自己逻辑混乱

#1

帖子 tommmm3 » 2011-03-22 20:20

编程初学者,用while语句就开始逻辑混乱,自己做作业,已经发晕,每次调试都无法改正,求指导


规则是这样的:玩家和电脑,各两颗骰子,如果掷出的两颗骰子没有1,则分数累积,玩家可选择是否继续或结束回合,如果两颗骰子之中有一个1,则所得分数不予累计,强制结束回合,如果掷到两个1,累计的分数全部清零,并且强制结束回合,由电脑继续游戏。如此,直到有一方累计分数达到100或以上的,游戏胜利。题目中给予电脑的条件是只要在一回合中累计得分20点,则结束回合,由玩家继续游戏。


程序代码:

代码: 全选

# Start
# Play control:
play = input('Would you like to play PIG (y/n)? ')# Play control
while play == 'y':

    # Welcome:
    username = input('Great! What is your name? ')
    print('Hi',username)

    # Game:
    scoreP = 0# Player's potential score
    scoreC = 0# Computer's potential score
    turn = 0# Turn control(Player: 0, Computer:1)
   


    # Player's turn:
    print('|------------------- Start Player\'s Turn ---------------------')  

        # Roll or hold:
    while turn == 0:
        hold = input('| Would you like to roll or hold (r/h)? ')
        while hold =='r':
            totalP = 0# Player's turn total
            import random
            dicP1 = random.randint(1,6)# Player's dice 1
            dicP2 = random.randint(1,6)# Player's dice 2
            toP = 0# Total of this turn
            # No 1
            if dicP1 and dicP2 != 1:
                stepP = dicP1 + dicP2# Step total
                toP = totalP + stepP
                scoreP = scoreP + toP
                print('| Die 1:',dicP1,'| Die 2:',dicP2,'| Die total:',stepP)
                print('| Turn total:',toP,'| Potential score:',scoreP)
                print('|')
                hold = input('| Would you like to roll or hold (r/h)? ')
            # If end
                  

            # Single 1
            elif dicP1 or dicP2 == 1:
                stepP = dicP1 + dicP2
                print('| Die 1:',dicP1,'| Die 2:',dicP2,'| Die total:',stepP)
                print('|')
                print('| *** You rolled a ONE - Turn over - No points for you!')
                # Turn end show:
                print('| *** Kramer\'s score:',scoreP,'| Computer\'s score:',scoreC)
                print('|------------------- End Player\'s Turn -----------------------')
                print('|------------------- Start Computer\'s Turn -------------------')
                turn = turn + 1
            # Elif end
                  

            # Double 1s
            else:
                stepP = dicP1 + dicP2
                totalP = 0
                print('| Die 1:',dicP1,'| Die 2:',dicP2,'| Die total:',stepP)
                print('|')
                print('| *** Ouch! That hurts! Two ONEs - You lose your entire score!')
                print('| *** Kramer\'s score:',scoreP,'| Computer\'s score:',scoreC)
                print('|------------------- End Player\'s Turn -----------------------')
                print('|------------------- Start Computer\'s Turn -------------------')
                turn = turn + 1
            # Else end
                  

            # While End
        else:
            turn = turn+ 1
            print('| *** Kramer\'s score:',scoreP,'| Computer\'s score:',scoreC)
            print('|------------------- End Player\'s Turn -----------------------')
            print('|------------------- Start Computer\'s Turn -------------------')
        # while end
           

        # Else end
           


    # While end
    # Player's Turn end
      

    # Computer's turn:
    else:
        # Roll or hold:
        totalC = 0
        while totalC < 20:
            import random
            dicC1 = random.randint(1,6)# Computer's dice 1
            dicC2 = random.randint(1,6)# Computer's dice 2
           

            # No 1
            if dicC1 and dicC2 != 1:
                stepC = dicC1 + dicC2# Step total
                toC = stepC + totalC
                scoreC = scoreC + toC
                print('| Die 1:',dicC1,'| Die 2:',dicC2,'| Die total:',stepC)
                print('| Turn total:',toC,'| Potential score:',scoreC)
                print('|')
            # If end

            # Single 1
            elif dicC1 or dicC2 == 1:
                stepC = dicC1 + dicC2
                print('| Die 1:',dicC1,'| Die 2:',dicC2,'| Die total:',stepC)
                print('|')
                print('| *** Computer rolled a ONE - Turn over - No points for computer!')
                # Turn end show:
                print('| *** Kramer\'s score:',scoreP,'| Computer\'s score:',scoreC)
                print('|------------------- End Computer\'s Turn ---------------------')
                turn = turn - 1
            # Elif end
                  

            # Double 1s
            else:
                stepC = dicC1 + dicC2
                totalC = 0
                print('| Die 1:',dicC1,'| Die 2:',dicC2,'| Die total:',stepC)
                print('|')
                print('| *** Ouch! That hurts! Two ONEs - Computer lose entire score!')
                print('| *** Kramer\'s score:',scoreP,'| Computer\'s score:',scoreC)
                print('|------------------- End Computer\'s Turn ---------------------')
                turn = turn - 1
            # Else end
        # While end
           

        else:
            print('| *** Kramer\'s score:',scoreP,'| Computer\'s score:',scoreC)
            print('|------------------- End Computer\'s Turn ---------------------')
            turn = turn - 1

           



    # Else end
    # Computer's turn end
      

    # Replay control:
    play = input('Would you like to play again (y/n)? ')
# While end
#
else:
    print('Thanks for playing')
lubcat
帖子: 2061
注册时间: 2010-09-27 12:59
送出感谢: 0
接收感谢: 0

Re: python让我自己逻辑混乱

#2

帖子 lubcat » 2011-03-22 20:47

額。。 :em06
生活里,有很多转瞬即逝,像在车站的告别,刚刚还相互拥抱,转眼已各自天涯。很多时候,你不懂,我也不懂,就这样,说着说着就变了,听着听着就倦了,看着看着就厌了,跟着跟着就慢了,走着走着就散了,爱着爱着就淡了,想着想着就算了。
usernp
帖子: 15
注册时间: 2010-10-21 0:59
送出感谢: 0
接收感谢: 0

Re: python让我自己逻辑混乱

#3

帖子 usernp » 2011-03-23 12:56

首先规则没说明好,分数累积是累积几分?
其次这样的代码没法读,不要滥用if else
把判断代码写在def里调用
# Else end这类注释没有必要加
头像
eexpress
帖子: 58428
注册时间: 2005-08-14 21:55
来自: 长沙
送出感谢: 4 次
接收感谢: 256 次

Re: python让我自己逻辑混乱

#4

帖子 eexpress » 2011-03-23 13:56

换Perl。就不会这样。
● 鸣学
头像
HuntXu
论坛版主
帖子: 5776
注册时间: 2007-09-29 3:09
送出感谢: 0
接收感谢: 6 次

Re: python让我自己逻辑混乱

#5

帖子 HuntXu » 2011-03-23 22:09

eexpress 写了:换Perl。就不会这样。
同意
HUNT Unfortunately No Talent...
头像
hecha
帖子: 364
注册时间: 2007-09-23 13:36
送出感谢: 0
接收感谢: 2 次

Re: python让我自己逻辑混乱

#6

帖子 hecha » 2011-03-23 22:33

我贴一个面向对象的

代码: 全选

#!/usr/bin/env python
# encoding: utf-8

from random import randint

class GameOver(Exception):
	def __init__(self, winner):
		self.winner = winner

class Player:
	def __init__(self):
		self.score = 0
		self.turn_score = 0

	def throw(self):
		x, y = randint(1, 6), randint(1, 6)
		if x == 1 and y == 1:
			self.score = 0
			self.turn_score = 0
			print self, '丢出', x, ',', y, '回合结束, 累计得分清零!'
		elif x == 1 or y == 1:
			self.score = self.score - self.turn_score
			self.turn_score = 0
			print self, '丢出', x, ',', y, '回合结束, 得分不累计. 当前累计得分:', self.score
		else:
			score = x + y
			self.score = self.score + score
			self.turn_score = self.turn_score + score
			print self, '丢出', x, ',', y, '得分:', score, '回合得分:', self.turn_score, '累计得分:', self.score
			if self.score >= 100:
				raise GameOver(self)
	
	def turn(self):
		self.turn_score = 0
		self.throw()
		while self.turn_score and self.choose():
			self.throw()

class HumPlayer(Player):
	def choose(self):
		choice = raw_input('继续吗? ')
		return choice == 'y' or choice == 'Y'
	def __str__(self):
		return '玩家'

class ComPlayer(Player):
	def choose(self):
		return self.turn_score < 20
	def __str__(self):
		return '电脑'

if __name__ == '__main__':
	hum = HumPlayer()
	com = ComPlayer()

	try:
		while True:
			hum.turn()
			com.turn()
	except GameOver as e:
		print '--------------------------------'
		print '最终的胜利者是', e.winner
		print hum, '累计得分:', hum.score
		print com, '累计得分:', com.score
头像
anticlockwise
帖子: 2393
注册时间: 2007-03-01 20:46
来自: 湖南长沙
送出感谢: 0
接收感谢: 0
联系:

Re: python让我自己逻辑混乱

#7

帖子 anticlockwise » 2011-03-24 0:06

HuntXu 写了:
eexpress 写了:换Perl。就不会这样。
同意
额……其实用Python也不会这样,很多代码可以弄成函数啊~~~
头像
fanhe
帖子: 2357
注册时间: 2007-03-24 23:45
送出感谢: 0
接收感谢: 9 次

Re: python让我自己逻辑混乱

#8

帖子 fanhe » 2011-03-24 0:45

楼主,逻辑太复杂的话,自己先画个图,理清楚再写代码
不然就是越写越乱

某人说用perl就不会有事,别相信!
头像
BigSnake.NET
帖子: 12522
注册时间: 2006-07-02 11:16
来自: 廣州
送出感谢: 0
接收感谢: 7 次
联系:

Re: python让我自己逻辑混乱

#9

帖子 BigSnake.NET » 2011-03-24 0:50

用函数会死星人。。。
PS:这显然就是 PERL 的风格。。。
^_^ ~~~
要理解递归,首先要理解递归。

地球人都知道,理论上,理论跟实际是没有差别的,但实际上,理论跟实际的差别是相当大滴。
头像
eexpress
帖子: 58428
注册时间: 2005-08-14 21:55
来自: 长沙
送出感谢: 4 次
接收感谢: 256 次

Re: python让我自己逻辑混乱

#10

帖子 eexpress » 2011-03-24 9:10

py是为了合作,写给别人看的。语法僵硬。怎么会不影响自己的思维。
:em04
● 鸣学
头像
lerosua
论坛版主
帖子: 8455
注册时间: 2007-11-29 9:41
送出感谢: 0
接收感谢: 0
联系:

Re: python让我自己逻辑混乱

#11

帖子 lerosua » 2011-03-24 9:31

我讨厌python :em20 更讨厌perl
头像
lainme
论坛版主
帖子: 7805
注册时间: 2008-09-13 19:17
系统: Arch Linux (x86_64)
送出感谢: 3 次
接收感谢: 68 次
联系:

Re: python让我自己逻辑混乱

#12

帖子 lainme » 2011-04-03 11:56

为什么我感觉不到那是python代码,颇有perl风格
头像
greco
帖子: 2487
注册时间: 2007-04-06 10:24
来自: ~/Shanghai
送出感谢: 0
接收感谢: 0

Re: python让我自己逻辑混乱

#13

帖子 greco » 2011-04-03 12:47

那个说python语法僵硬的不是人,是神
http://silenceisdefeat.com/~greco

代码: 全选

''.join([chr(ord(c)-2) for c in 'O{"G/ockn"ku<"itgeq0ujkBiockn0eqo'])
echo -n "Z3JlY28uc2hpQGdtYWlsLmNvbQ==" | base64 -d
cheeselee
帖子: 353
注册时间: 2008-07-09 0:39
送出感谢: 1 次
接收感谢: 0

Re: python让我自己逻辑混乱

#14

帖子 cheeselee » 2011-04-05 4:38

用Perl (MooseX::Declare) 以相同行数重实现 6楼的脚本,在Ubuntu下先安装 libmoosex-declare-perl

代码: 全选

#!/usr/bin/perl
use strict;
use integer;
use MooseX::Declare;

role Player {
    has 'score', is => 'rw', isa => 'Int', default => 0;
    has 'turn_score', is => 'rw', isa => 'Int', default => 0;
    requires qw(choose type);

    method throw {
        my ($x, $y) = (1+rand(6), 1+rand(6));
        if ($x == 1 and $y == 1) {
            $self->score(0);
            $self->turn_score(0);
            print $self->type() . "丢出 $x,$y,回合结束,累计得分清零!\n";
        } elsif ($x == 1 or $y == 1) {
            $self->score($self->score() - $self->turn_score());
            $self->turn_score(0);
            print $self->type() . "丢出 $x,$y,回合结束, 得分不累计. 当前累计得分: " . $self->score() . "\n";
        } else {
            my $score = $x + $y;
            $self->score($self->score() + $score);
            $self->turn_score($self->turn_score() + $score);
            print $self->type(), "丢出 $x,$y,得分: $score,回合得分: ", $self->turn_score(), ",累计得分: ", $self->score(), "\n";
            die("Winner: " . $self->type()) if ($self->score() >= 100);
        }
    }

    method turn {
        $self->turn_score(0);
        do {$self->throw()} while $self->turn_score() and $self->choose();
    }
}

class HumPlayer with Player {
    method choose {
        print "继续吗?\n";
        my $a = <STDIN>;
        return $a=~/^y$/i;
    }

    method type {'玩家'}
}

class ComPlayer with Player {
    method choose { return $self->turn_score() < 20 }
    method type {'电脑'}
}

my $hum = HumPlayer->new();
my $com = ComPlayer->new();
eval {
    while(1){
        $hum->turn();
        $com->turn();
    }
};
print <<EOF if ($@=~/^Winner: (\S+)/);
--------------------------------
最终的胜利者是: $1
@{[$hum->type()]} 累计得分: @{[$hum->score()]}
@{[$com->type()]} 累计得分: @{[$com->score()]}
EOF
7号机-----神舟 优雅A460P-i7G D2
CPU: i7-2670QM
RAM: 8G
HD:500G
OS:Fedora 17 x86_64

热衷话题:Package Management\Programming
fnan
帖子: 919
注册时间: 2009-07-01 22:04
送出感谢: 0
接收感谢: 13 次

Re: python让我自己逻辑混乱

#15

帖子 fnan » 2011-05-12 10:14

翻了几下教程,可以写python了。
这种小游戏不用函数也很简单的,不过要先明确一下规矩:
玩家- 两个骰子都无1则分数加入积分,可以选择继续掷或停止回合,两个1则停止,积分清零,一个1也停止,积分不动。
电脑- 两个骰子都无1则分数加入积分,继续掷,两个1则停止,积分清零,一个1也停止,积分不动,如果在一个回合中得到20分或以上,也停止。
游戏结束条件:任何一方积分达到100或以上为赢家。

代码: 全选

#!/usr/bin/python
# encoding: utf-8

#玩家号码:1  电脑号码:0

from random import randrange
sum = [0,0]
string = ['电脑','玩家']
change = ['玩家','电脑']
player = 1
sum_pc = 0

print '*****玩家先掷*****'
while True:
	result = [randrange(1,7),randrange(1,7)]
	print '掷出了 ' + repr(result)
	if 1 in result:	
		print '换' + change[player] + '掷!'
		if result.count(1) == 2: sum[player] = 0
	else:
		sum[player] = sum[player] + result[0] + result[1]
		if sum[player] > 99:
			print '赢的是' + string[player] + '积分 ' + repr(sum[player]) + '。'
			break
		print '积分:' + repr(sum[player])
		if player == 1:
			answer = raw_input('继续掷吗(y/n)?  ')
			if answer == 'y': continue
		if player == 0:
			sum_pc = sum_pc + result[0] + result[1]
			if sum_pc < 20:
				 continue
			else:
				print '电脑在此回合得到' + repr(sum_pc) + '分,换玩家掷!'
	sum_pc = 0
	print string[player] + '的积分是:' + repr(sum[player])
	print
	if player == 1:
		player = 0
	else:
		player = 1
	print '*****现在到' + string[player] + '掷!*****'
bash不如perl精妙,学不到lisp的皮毛,远不够c++强悍,不过可以用。
回复

回到 “Python/Php/Perl”