The problem I've been getting is the program should produce player 2 Won! instead of draw
Can't figure it out
This is a question from CIE 9618\42\O\N\2022
Even the Code from thier marking scheme(for python)produces errors
Help would be apreciated
the code is pasted below:
Oh and i've tried to see what values are being assigned using print function but I get stuff like: <main.Card object at 0x000001FBCD177940>
maybe thats the problem
I have no idea how to fix it
#Part A i:
class Card:
# __Number as Integer
# __Colour as String
def __init__(self, Number, Colour):
self.Number = Number
self.Colour = Colour
#Part A ii:
def GetNumber(self):
return self.Number
def GetColour(self):
return self.Colour
#Part A iii:
IRed = Card(1, "red")
IIRed = Card(2, "red")
IIIRed = Card(3, "red")
IVRed = Card(4, "red")
VRed = Card(5, "red")
IBlue = Card(1, "blue")
IIBlue = Card(2, "blue")
IIIBlue = Card(3, "blue")
IVBlue = Card(4, "blue")
VBlue = Card(5, "blue")
IYellow = Card(1, "yellow")
IIYellow = Card(2, "yellow")
IIIYellow = Card(3, "yellow")
IVYellow = Card(4, "yellow")
VYellow = Card(5, "yellow")
#Part B i:
class Hand:
# __Cards as Array of Card
# __FirstCard as Integer
# __NumberCards as Integer
def __init__(self, ICard, IICard, IIICard, IVCard, VCard):
self.Cards = []
self.Cards.append(ICard)
self.Cards.append(IICard)
self.Cards.append(IIICard)
self.Cards.append(IVCard)
self.Cards.append(VCard)
self.FirstCard = 0
self.NumberCards = 5
#Part b ii:
def GetCard(self, index):
return self.Cards[index]
#Part b iii:
Player_1 = Hand(IRed, IIRed, IIIRed, IVRed, IYellow)
Player_2 = Hand(IIYellow, IIIYellow, IVYellow, VYellow, IBlue)
#Part c i:
def CalculateValue(Player):
Score = 0
for index in range(0, 5):
Player_Hand = Player.GetCard(index)
Colour = Player_Hand.GetColour
Numbers = Player_Hand.GetNumber
if Numbers == 1:
Score = Score + 1
if Numbers == 2:
Score = Score + 2
if Numbers == 3:
Score = Score + 3
if Numbers == 4:
Score = Score + 4
if Numbers == 5:
Score = Score + 5
if Colour == "red":
Score = Score + 5
if Colour == "blue":
Score = Score + 10
if Colour == "Yellow":
Score = Score + 15
return Score
#Part c ii:
Player_1Score = CalculateValue(Player_1)
Player_2Score = CalculateValue(Player_2)
if Player_1Score > Player_2Score:
print("Player 1 Won!")
elif Player_1Score < Player_2Score:
print("Player 2 Won!")
else:
print("Draw")
I tried over writing builtin functions for repr and str it made it readable but wasn't able to get it to work
Problems:
-Used double underscore with attributes
*removed them
-for index in range(0, 4) should be for index in range(0, 5)
*fixed
-return self.__Number.__dict__ should be return self.__Number
*fixed
-GetNumber in function CalculateValue should be GetNumber()
*fixed it and now the program works!!
TYSM to all the comments
Related
Your team has been assigned to develop a console or GUI turn-based battle game. The game allows player setup his/her team which made up of a numbers of units (default is 3). Each unit has a name, health point (HP), attack point (ATK), defence point (DEF), experience (EXP) and a rank. On top of that, a unit can be either a Warrior or Tanker which having different strength in different range for ATK and DEF point. The initial value for each attribute point are describe in the details requirement in Part A – Table 1.
The game will then setup another team belongs to AI which made up of same number of unit as the player’s team. The type of unit will be assigned randomly by chances. The name of each unit will be specify by the player while the name of each unit for AI team will be defined with prefix with “AI” follow by 2 random digits i.e. AI87.
A player can select a unit from his/her team and attack the other unit (the target) in the opponent / AI team. Unit which are severely damaged (i.e. HP equals to less than 0) will be defeated and removed from the team. The team (player / AI) which destroy all the opponent units first will be declared as winner of the game.
enter code here
class GameCharacter:
char_name = ""
char_type = ""
__hp = 0
__atk = 0
__def = 0
__rank = 0
def __init__(self, char_type, char_name):
self.char_type: str = char_type
self.char_name: str = char_name
if char_type == "Warrior":
self.setup_warrior()
elif char_type == "Tanker":
self.setup_tanker()
def setup_warrior(self):
self.__hp = 100
self.__atk = 20
self.__def = 6
self.__rank = 1
return [self]
def setup_tanker(self):
self.__hp = 100
self.__atk = 8
self.__def = 9
self.__rank = 1
return [self]
def get_attack(self):
return self.__atk
def get_health(self):
return self.__hp
def __str__(self):
text = "Character type:{},name:{}".format(self.char_type, self.char_name)
return text
enter code here
import game_setting
import random
rounds = 1
count = 0
gs = game_setting.GameCharacter.__init__(char_type, char_name)
player_team = []
ai_bot = []
def detail_ai():
print(ai_bot)
def detail_player():
print(player_team)
def details_all():
print(player_team)
print(ai_bot)
def main():
get_name = ""
j = random.randint(1, 2)
ch = ""
i: int
types = ""
for i in range(1, 4):
get_name = (input("Choose character name:"))
ch = (input("Choose character type [w/t]:")).lower()
if ch == 'w' and get_name != "":
types: str = "Warrior"
player_team.append(types)
player_team.append(get_name)
print("character", i, ":", types, "Name:", get_name)
elif ch == 't':
types: str = "Tanker"
player_team.append(self.types)
print("character", i, ":", types, "Name:", get_name)
else:
print("Wrong value ")
# =======================================Ai Bot name=================================================
for i in range(1, 4):
if ch == "w" and j != j:
ch: str = "Warrior"
ai_bot.append(ch)
elif ch == "t" and j != j:
types: str = "Tanker"
player_team.append(types)
else:
print("Wrong value ")
k = str(random.randint(10, 99))
if get_name != get_name:
get_name: str = "AI" + k
ai_bot.append(get_name)
else:
print("Done setting.")
print("character", i, " : ", types, "Name:", get_name)
show_name: str = ""
show_type: str = ""
main()
I am trying to use minimax algo to find a best move for a game.
The game is 2 players take turns to pick a number from a pile [0,1,2,,,8]
Winning Condition: player wins the game if the player contains three numbers and their sum is 14.
The initial game state is given by the argument like:
4 1 2 3 4
The first number indicate the total length and the following numbers are the numbers taken by player each turn. In this example the player A has [1,3] and player B has [2,4]
My problem is the algo can't give the correct answer:
Like when the input is 4 4 1 7 8 my program cannot gives the correct move: it takes 0 not 3 for next move.
import sys
import math
totalMoves = int(sys.argv[1])
pile = [0, 1, 2, 3, 4, 5, 6, 7, 8]
# who are u
you = []
opponent = []
# cards in hand
playerA = []
playerB = []
# get all the cards into hand
for i in range(totalMoves):
# save card into playerB
if i % 2 != 0:
playerB.append(int(sys.argv[i+2]))
# save card into playerA
if i % 2 == 0:
playerA.append(int(sys.argv[i+2]))
# remove sent card in list
pile.remove(int(sys.argv[i+2]))
# identify which player you are
if totalMoves % 2 == 0:
you = playerA
opponent = playerB
else:
you = playerB
opponent = playerA
def find3Numbers(player): # calcluate the card in hand is equal to 14
arr_size = len(player)
if (len(player) >= 3):
for i in range(0, arr_size-2):
for j in range(i + 1, arr_size-1):
for k in range(j + 1, arr_size):
if (player[i] + player[j] + player[k] == 14):
return True
else:
return False
def isNumberLeft(board):
if (len(board) == 0):
return False
else:
return True
def evaluate(player, oppo):
if (find3Numbers(player) == True):
return 10
elif (find3Numbers(oppo) == True):
return -10
else:
return 0
def minimax(board, player, oppo, depth, isMax):
score = evaluate(player, oppo)
if (score == 10):
return score
if (score == -10):
return score
if (isNumberLeft(board) == False):
return 0
if (isMax):
best = -math.inf
for card in board:
player.append(card)
board.remove(card)
best = max(best, minimax(board, player, oppo, depth+1, not isMax))
board.append(card)
player.remove(card)
return best
else:
best = +math.inf
for card in board:
oppo.append(card)
board.remove(card)
best = min(best, minimax(board, player, oppo, depth+1, not isMax))
board.append(card)
oppo.remove(card)
return best
def bestMove():
bestScore = -math. inf
bestNum = -math.inf
for card in pile:
you.append(card)
pile.remove(card)
score = minimax(pile, you, opponent, 0, False)
pile.append(card)
you.remove(card)
if (bestScore < score):
bestNum = card
bestScore = score
return bestNum
you.append(bestMove())
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
So in my coding class we are required to make a "Dice Poker" game. We need to implement a scoring system, however, mine keeps returning a "None", therefore causing issues when I want to add the accumulated score to the base score of 100, since NoneTypes and integers can not be added. I'm aware that I need to fix whatever is causing the None, but I'm not sure how. I believe the problem could be in the "scoring" function, but perhaps it is more lurking in the later parts (After the #Choosing Last Roll or #Scoring output comments) of the function "diceGame". I'm very new to coding, and after hours of looking at this thing I'm not really sure what I'm looking at anymore. Thank you so much for your help!
Text-based dice game
from random import randint
def rollFiveDie():
allDie = []
for x in range(5):
allDie.append(randint(1,6))
return allDie
def outputUpdate(P, F):
print(P)
print(F)
def rollSelect():
rollSelected = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
selectList = rollSelected.split()
return selectList
def rollPicked(toRollList, diceList):
for i in toRollList:
diceList[int(i) - 1] = randint(1,6)
def scoring(dList):
counts = [0] * 7
for value in dList:
counts[value] = counts[value] + 1
if 5 in counts:
score = "Five of a Kind", 30
elif 4 in counts:
score = "Four of a Kind", 25
elif (3 in counts) and (2 in counts):
score = "Full House", 15
elif 3 in counts:
score = "Three of a Kind", 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
score = "Straight", 20
elif counts.count(2) == 2:
score = "Two Pair", 5
else:
score = "Lose", 0
return score
def numScore(diList):
counts = [0] * 7
for v in diList:
counts[v] = counts[v] + 1
if 5 in counts:
finScore = 30
elif 4 in counts:
finScore = 25
elif (3 in counts) and (2 in counts):
finScore = 15
elif 3 in counts:
finScore = 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
finScore = 20
elif counts.count(2) == 2:
finScore = 5
else:
finScore = 0
return finScore
def printScore(fscore):
print(fscore)
print(" ")
def diceGame():
contPlaying = True
while contPlaying:
playPoints = 30
if playPoints > 9:
playPoints -= 10
else:
print("No more points to spend. Game Over.")
contPlaying = False
playing = input("Would you like to play the Dice Game? (Answer 'y' or 'n'): ")
print(' ')
if playing == 'y':
#First Roll
fiveDie = rollFiveDie()
outputUpdate("Your roll is...", fiveDie)
#Choosing Second Roll/Second Roll execution
pickDie = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
pickDie = pickDie.split()
rollPicked(pickDie, fiveDie)
outputUpdate("Your next roll is...", fiveDie)
#Choosing Last Roll
pickDie = rollSelect()
rollPicked(pickDie, fiveDie)
outputUpdate("Your final roll is...", fiveDie)
#Scoring output
scoring(fiveDie)
finalScore = numScore(fiveDie)
playPoints += finalScore
print(playPoints)
else:
contPlaying = False
def main():
diceGame()
main()
Basically, I'm trying to test how the order of the cards in a players hand affects how often they win, but I run the program and the score will sometimes get stuck at player one alternating between 27 & 26 cards in hand, while player two alternates between 25 & 26 cards in hand and it just sticks like that.
import random
import sys
class Card:
def __init__(self, rank, suit, value):
self.rank = rank
self.suit = suit
self.value = value
self.name = str(self.rank) + " of " + self.suit
def create_deck():
suit = ['Spades', 'Hearts', 'Clubs', 'Diamonds']
rank = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
deck = []
num = 2
for i in suit:
for x in rank:
deck.append(Card(x, i, num))
num = num + 1
num = 2
return sorted(deck, key=lambda k: random.random())
def deal_cards(deck):
x = 0
i = 0
player1 = []
player2 = []
while i < len(deck):
if x == 0:
player1.append(deck[i])
x = 1
else:
player2.append(deck[i])
x = 0
i += 1
return player1, player2
def game():
pl1wins = 0
pl2wins = 0
while (pl1wins + pl2wins) <= 50:
deck = create_deck()
players = deal_cards(deck)
player1 = players[0]
player2 = players[1]
player1 = sorted(player1, key=lambda card: card.value)
war = []
turns = 0
while len(player1) > 0 and len(player2) > 0:
turns = turns + 1
#print turns
#print str(len(player1))+ " : " + str(len(player2))
if (len(player1) + len(player2)) > 52:
print "Oh NO!"
sys.exit()
war = []
war.append(player1[0])
war.append(player2[0])
player1.remove(player1[0])
player2.remove(player2[0])
if war[0].value > war[1].value:
#print "Player 1 wins the " + war[1].name
i = 0
n = len(war)
while i < n:
player1.append(war[0])
war.remove(war[0])
i = i + 1
elif war[0].value < war[1].value:
#print "Player 2 wins the " + war[0].name
i = 0
n = len(war)
while i < n:
player2.append(war[0])
war.remove(war[0])
i = i + 1
elif war[0].value == war[1].value:
if len(player1) == 0:
player1.append(war[0])
war.remove(war[0])
if player1[0].value == player2[0].value:
player1[0].value = 0
if len(player2) == 0:
player2.append(war[1])
war.remove(war[1])
if player1[0].value == player2[0].value:
player2[0].value = 0
while len(war) > 0:
#print "The cards have tied, war will commence"
i = 0
for i in range(3):
if len(player1) > 1:
war.append(player1[0])
player1.remove(player1[0])
if len(player2) > 1:
war.append(player2[0])
player2.remove(player2[0])
if player1[0].value > player2[0].value:
war.append(player1[0])
war.append(player2[0])
player1.remove(player1[0])
player2.remove(player2[0])
i = 0
n = len(war)
while i < n:
player1.append(war[0])
war.remove(war[0])
i = i + 1
elif player1[0].value < player2[0].value:
war.append(player1[0])
war.append(player2[0])
player1.remove(player1[0])
player2.remove(player2[0])
i = 0
n = len(war)
while i < n:
player2.append(war[0])
war.remove(war[0])
i = i + 1
#print turns
if len(player1) != 0:
print "Player1 wins!"
pl1wins = pl1wins + 1
elif len(player2) != 0:
print "Player2 wins!"
pl1wins = pl2wins + 1
print pl1wins + " versus " + pl2wins
game()
Thanks to #Engineero for your comment:
There are possible infinite games in War, provided you do not switch the order in which player's cards are added to the bottom of the winning player's deck (i.e. always opponent's card first, then yours or vice versa). See this MathOverflow discussion. Basically for some deals, the game never ends. You could add occasional switching to the order that cards are returned to the bottom of the deck to make it finite. – Engineero
That led me to this solution:
Basically, I randomized which card was put in the pile first as such:
if random.randint(1,2) == 1:
war.append(player2[0])
war.append(player1[0])
else:
war.append(player1[0])
war.append(player2[0])
And this fixed the problem perfectly.