2016-08-27 106 views
-1

我正在試圖建立一個岩石,紙,剪刀遊戲。有人可以告訴我,或者指出我錯誤地使用這段代碼的正確方向嗎?在一個方法內增加變量?

我希望players_scorecpu_score變量增加1,每次有一個人贏得一輪。

choice = ["rock", "paper", "Scissors"] 

players_score = 0 
cpu_score = 0 


def win_lose(a,b,c,d) 

    if a == "rock" && b == "scissors" 
     c+=1 
     puts "YOU WIN!!" 

    elsif a == "scissors" && b == "rock" 
     d+=1 
     puts "YOU LOSE!!" 

    elsif a =="paper" && b == "rock" 
     c+=1 
     puts "YOU WIN!!" 

    elsif a =="rock" && b == "paper" 
     d+=1 
     puts "YOU LOSE!!" 

    elsif a == "scissors" && b == "paper" 
     c+=1 
     puts "YOU WIN!!" 

    elsif a == "paper" && b == "scissors" 
     d+=1 
     puts "YOU LOSE!!" 

    else a == b 
     puts "Its a Draw this time!!" 
    end 

end 

while players_score < 2 && cpu_score < 2 


    print "Lets play. Plese choose rock, paper or scissors: " 
    players = gets.chomp.downcase 
    puts "You have #{players}" 

    cpu = choice.sample.downcase 
    puts "Computer has #{cpu}" 

    win_lose(players, cpu, players_score, cpu_score) 
    puts "scores are player #{players_score} , cpu #{cpu_score}" 
end 

回答

0

返回從win_lose的值,並用它來確定增加變量,如:

def win_lose(a,b,c,d) 
    if a == "rock" && b == "scissors" 
     c+=1 
     winner = 'player' 
    elsif a == "scissors" && b == "rock" 
     d+=1 
     winner = 'computer' 
    # [.. etc ..] 
    else a == b 
     winner = 'draw' 
    end 

    return winner 
end 

player_score = 0 
cpu_score = 0 
choice = ["rock", "paper", "Scissors"] 

while players_score < 2 && cpu_score < 2 
    print "Lets play. Plese choose rock, paper or scissors: " 
    players = gets.chomp.downcase 
    puts "You have #{players}" 

    cpu = choice.sample.downcase 
    puts "Computer has #{cpu}" 

    winner = win_lose(players, cpu, players_score, cpu_score) 
    if winner == 'player' 
     player_score += 1 
     puts "YOU WIN!!" 
    elsif winner == 'computer' 
     cpu_score += 1 
     puts "YOU LOSE!!" 
    else 
     puts "It's a draw" 
    end 

    puts "scores are player #{players_score} , cpu #{cpu_score}" 
end 

正如你所看到的,這也可以讓你不重複同樣的「你贏! 「一遍又一遍的句子。讓我感動的是,win_lose功能外,使這個函數只一個件事:確定贏家還是輸家,而不是方面:確定贏家還是輸家,通知他們這一點。

這種區別對於這樣一個小程序來說可能並不重要,但隨着程序的增長,保持程序的可理解性至關重要。