Python Code Connect-N Game.
Hi there, I need help with detecting the winner for the 8 directions in Connect N. The game is like Connect 4, but the user inputs N to whatever they want it to be. So could be Connect 5, or 6, etc. However, at the moment, my code is not detecting the 8 directions. I really am struggling with this function. Can someone show me how some code that would work to apply into my def have_winner function.
Thank you!
Instructions for the game
# GLOBAL VARIABLES
N = 5
num_row = N + 3
num_col = N + 2
disk = ['\u2B1C', '\u26AA', '\u26AB']
board = []
def init_board(n):
'''initialise the board'''
global N, num_row, num_col
N = n
num_row = n + 3
num_col = n + 2
for c in range(num_col):
board.append([0]*num_row)
def display():
'''print the board'''
to_print = " "
for i in range(num_col):
to_print = to_print + f'[{i}]'
print(to_print)
for i in range(num_row):
to_print = f'[{i:2}]'
for j in range(num_col):
to_print = f'{to_print}{disk[board[j][i]]:2}'
print(to_print)
def game():
'''play the game'''
n = input('Please input N:')
init_board(int(n))
p = 0
while True:
c = input(f'Player {p} select colomn:')
if c == 'q': # quit the game
print(f'Player {p} resigned')
break
# drop disk
f = drop_disk(int(c), p+1)
if f == 0: # illegal move
print(f'Column {c} is an illegal move')
continue
display()
# check winner and switch side
w = have_winner()
if w == 1:
print(f'Player {p} won')
break
elif w == 2:
print('draw')
break
else:
p = (p + 1)%2
def drop_disk(c, player):
"""player drop a disk at ch colomn. Return 1 if successfully drop the disk, return 0 if this is a illegal move, e.g. the colomn is full."""
if board[c][0] != 0:
return 0
for r in range(num_row -1, -1, -1):
if board[c][r] == 0:
board[c][r] = player
return 1
return 0
def have_winner():
"""return 1 if there is a winner, return 2 if the board is full, return 0 otherwise"""
for c in range(num_col):
for r in range(num_row):
if board[c][r] == 0:
return 0
return 2
# MAIN CODE
game()
I'm working on an assignment that books seats on a flight, the code I have so far works for everything besides the part for resetting all the seats to available when the flight is fully booked.
NUM_ROWS = 2
NUM_COLS = 1
AVAIL = '-'
BOOKED = 'X'
seatTable = []
for i in range(NUM_ROWS):
column = []
for j in range(NUM_COLS):
column.append(AVAIL)
seatTable.append(column)
def resetTable(seats): ##<--need to fix
seatTable = []
for i in range(NUM_ROWS):
column = []
for j in range(NUM_COLS):
column.append(AVAIL)
seatTable.append(column)
resetTable(printTable(seatTable)) ##<-- not correct
print()
def printTable(seats):
i=1
alpha = 'abcdefghijklmnopqrstuvwxyz'
print('Row', end=' ')
for num in range(NUM_COLS):
print(f'{alpha[num]:2s}'.format(alpha),end='')
print()
for num in seats:
print(f'{str(i):3s}'.format(str(i)), end=' ')
i+=1
for j in num:
print(j,end=' ')
print()
def full(seats):
for row in seats:
for seat in row:
if seat == AVAIL:
return False
return True
def getRes():
alpha = 'abcdefghijklmnopqrstuvwxyz'
while True:
try:
rowNum = input(f'Enter a row number (1 to {NUM_ROWS}): ')
seatLetter = input(f'Enter a seat letter (A to {(alpha[NUM_COLS-1]).upper()}): ')
reserve(seatTable,rowNum,seatLetter)
break
except:
pass
print('Error, Please choose another seat')
print(f'Seat {rowNum}{seatLetter.upper()} has been booked\n')
def reserve(seats,resR,resC):
alpha = 'abcdefghijklmnopqrstuvwxyz'
column = 0
p = 0
for i in alpha:
if i.lower() == resC.lower():
column = p
p+=1
row = int(resR)-1
seats[row][column] = BOOKED
def main():
printTable(seatTable)
while not full(seatTable):
getRes()
printTable(seatTable)
print('Plane is booked')
next = input('\nWould you like to check the next flight? (Y/N): ')
if next == 'y': ##<---problem
resetTable(printTable(seatTable))
return main()
else:
exit()
main()
When I run the code to check for the "next flight" the seats reset, but then gets stuck on an infinite loop, followed by an error:
line 23, in resetTable
resetTable(printTable(seatTable)) ##<-- not correct
[Previous line repeated 992 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
How can I fix the resetTable() function to work?
Try this
NUM_ROWS = 2
NUM_COLS = 1
AVAIL = '-'
BOOKED = 'X'
seatTable = []
for i in range(NUM_ROWS):
column = []
for j in range(NUM_COLS):
column.append(AVAIL)
seatTable.append(column)
def resetTable(seats):
for i in range(NUM_ROWS):
column = []
for j in range(NUM_COLS):
seatTable[i][j] = AVAIL
def printTable(seats):
i=1
alpha = 'abcdefghijklmnopqrstuvwxyz'
print('Row', end=' ')
for num in range(NUM_COLS):
print(f'{alpha[num]:2s}'.format(alpha),end='')
print()
for num in seats:
print(f'{str(i):3s}'.format(str(i)), end=' ')
i+=1
for j in num:
print(j,end=' ')
print()
def full(seats):
for row in seats:
for seat in row:
if seat == AVAIL:
return False
return True
def getRes():
alpha = 'abcdefghijklmnopqrstuvwxyz'
while True:
try:
rowNum = input(f'Enter a row number (1 to {NUM_ROWS}): ')
seatLetter = input(f'Enter a seat letter (A to {(alpha[NUM_COLS-1]).upper()}): ')
reserve(seatTable,rowNum,seatLetter)
break
except:
pass
print('Error, Please choose another seat')
print(f'Seat {rowNum}{seatLetter.upper()} has been booked\n')
def reserve(seats,resR,resC):
alpha = 'abcdefghijklmnopqrstuvwxyz'
column = 0
p = 0
for i in alpha:
if i.lower() == resC.lower():
column = p
p+=1
row = int(resR)-1
seats[row][column] = BOOKED
def main():
printTable(seatTable)
while not full(seatTable):
getRes()
printTable(seatTable)
print('Plane is booked')
next = input('\nWould you like to check the next flight? (Y/N): ')
if next == 'y':
resetTable(seatTable)
return main()
else:
exit()
main()
I am currently trying to make a Tic Tac Toe game with minimax implemented in Python. Another feature that I'm trying to implement is different board sizes. But overall, unfortunately, the algorithm is not working.
As a beginner, this is not a surprise for me, but this case seems hopeless. I tried tweaking quite a lot of things (may seem like a lot just to me) just to end up with the same result - the computer filling up the fields from top left to bottom right.
#Sprawdzenie czy ktos wygral w poziomie lub pionie / straight line check
def winLine(line, letter):
return all(n == letter for n in line)
#Utworzenie nowej listy z elementow przekatnych / diagonal check
def winDiagonal(board, letter):
arr = []
tArr = []
for n in range(boardSize):
arr.append(board[n][n])
tArr.append(board[n][boardSize-n-1])
if winLine(arr, letter):
return True
elif winLine(tArr, letter):
return True
else:
return False
def checkWinner (board):
#Liczenie wolnych pol / checking the available fields
openSpots = 9
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
openSpots += 1
#Transpozycja planszy, by mozna bylo latwo zastosowac winLine na kolumach / transposition of the board
for letter in (person, ai):
transPos = list(zip(*board))
#Sprawdzanie w poziomie / horizontal check
if any(winLine(row, letter) for row in board):
#print('winline horizontal')
return letter
#Sprawdzanie w pionie / vertical check
elif any (winLine(col, letter) for col in transPos):
#print('winline vertical')
return letter
#Sprawdzanie po przekatnych / diagonal check
elif winDiagonal(board, letter):
return letter
elif openSpots == 0: return 'tie'
else: return 'none'
#Funkcja sprawdzajaca czy dane pole jest wolne / checks whether the field is available
def available (row, col):
global board
#Sprawdzenie czy pole jest wolne
if board[row][col] == '0':
return True
else:
return False
#Stale dla algorytmu minimax / minimax initial scores to compare against
minTarget = float('inf')
maxTarget = float('-inf')
#Slownik z wartosciami liczbowi dla wynikow, komputer maksymalizuje / a dictionary with scores for particular results
scores = {
'X': 10,
'O': -10,
'tie': 0
}
#Algorytm minimax
def minimax(myBoard, depth, maximizes):
#Sprawdzenie czy zaszla wygrana lub remis / Checking whether there is a win or tie
res = checkWinner(myBoard)
if (res != 'none'):
return scores[res]
#Gracz maksymalizujacy/ Maximizing player
elif maximizes == True:
bestScoreMax = maxTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = person
score = minimax(board, depth + 1, False)
board[n][m] = '0'
bestScoreMax = max([score, bestScoreMax])
return bestScoreMax
#Gracz minimalizujacy / minimizing player
elif maximizes == False:
bestScoreMin = minTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = ai
score = minimax(board, depth + 1, True)
board[n][m] = '0'
bestScoreMin = min([score, bestScoreMin])
return bestScoreMin
def makeMove(row, col):
global board
board[row][col] = ai
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
#print(str(move.x) + ' ' + str(move.y))
# Funkcja pobierajaca ruch uzytkownika / player input for the move
def getPlayerMove():
global board
res = input('Please type in your move on the form \"x y\", x being the number of the row and y the number of the column of your choosing.\n')
col, row = res.split(" ")
row = int(row)
col = int(col)
if available(row-1, col-1):
board[row-1][col-1] = person
else:
print('You cannot make that move')
getPlayerMove()
def drawBoard():
global board
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
print(' - ', end='')
else:
print(' '+board[n][m]+' ', end='')
print('\n')
#Zmienna powiadamiajaca o stanie rozgrywki / variable indicating the state of the game
playing = False
# initializing the variable
boardSize = 0
# initializing the players
person = 'X'
ai = 'O'
#Gracz posiadajacy ruch (a takze rozpoczynajacy) / player who is playing at the moment
currentPlayer = ''
while True:
currentPlayer = person
boardSize = int(input("Please enter the size of the board. (one side)\n"))
global board
board = [['0' for i in range(boardSize)] for i in range(boardSize)]
print("You go first.")
playing = True
while playing:
if currentPlayer == person:
drawBoard()
getPlayerMove()
if checkWinner(board) == person:
drawBoard()
print("Yaay, you won!")
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = ai
elif currentPlayer == ai:
computedMove()
if checkWinner(board) == ai:
drawBoard()
print('You lose!')
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = person
if not input('Do you want to play again?').lower().startswith('y'):
break
In computedMove, you should first play the ai move then check the scores.
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
myBoard[n][m] = ai #This is added
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
Also in minimax function, you should use same variable for myBoard and board.
Morning all,
I'm an A level computer science teacher, and with their pre-release material exam coming up they're busy beavering away trying to make things work.
I don't teach the programming side of the course, focusing on the theory, and their programming teacher has been off ill for a while so I'm doing what I can but running out of time to support the top end.
Their pre-release material in Python is based on a foxes and rabbits game, and one of the pupils is trying to make a class called 'GiantWarren' that inherits the properties and functions of warren, but is a larger instance.
His code is below, and he's using 'super' to try and inherit the functions of warren, but it won't work unless he copy and pastes the functions. Any help on how to get super working would be greatly appreciated, not just by me, but my pupils as well:
Note - Warren is line 228, GiantWarren is line 351
#Skeleton Program code for the AQA A Level Paper 1 2017 examination
#this code should be used in conjunction with the Preliminary Material
#written by the AQA Programmer Team
#developed in the Python 3.4.1 programming environment
import enum
import random
import math
class Location:
def __init__(self):
self.Fox = None
self.Warren = None
class Simulation:
def __init__(self, LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations):
self.__ViewRabbits = ""
self.__TimePeriod = 0
self.__WarrenCount = 0
self.__FoxCount = 0
self.__ShowDetail = False
self.__LandscapeSize = LandscapeSize
self.__Variability = Variability
self.__FixedInitialLocations = FixedInitialLocations
self.__Landscape = []
for Count1 in range (self.__LandscapeSize):
LandscapeRow = []
for Count2 in range (self.__LandscapeSize):
LandscapeLocation = None
LandscapeRow.append(LandscapeLocation)
self.__Landscape.append(LandscapeRow)
self.__CreateLandscapeAndAnimals(InitialWarrenCount, InitialFoxCount, self.__FixedInitialLocations)
self.__DrawLandscape()
MenuOption = 0
while (self.__WarrenCount > 0 or self.__FoxCount > 0) and MenuOption != 5:
print()
print("0. Advance 10 time periods hiding detail")
print("1. Advance to next time period showing detail")
print("2. Advance to next time period hiding detail")
print("3. Inspect fox")
print("4. Inspect warren")
print("5. Exit")
print()
try:
MenuOption = int(input("Select option: "))
except:
print("What you have entered is not an integer. Try again")
if MenuOption == 0:
for a in range(1, 11):
self.__TimePeriod += 1
self.__ShowDetail = False
self.__AdvanceTimePeriod()
if MenuOption == 1:
self.__TimePeriod += 1
self.__ShowDetail = True
self.__AdvanceTimePeriod()
if MenuOption == 2:
self.__TimePeriod += 1
self.__ShowDetail = False
self.__AdvanceTimePeriod()
if MenuOption == 3:
x = self.__InputCoordinate("x")
y = self.__InputCoordinate("y")
if not self.__Landscape[x][y].Fox is None:
self.__Landscape[x][y].Fox.Inspect()
if MenuOption == 4:
x = self.__InputCoordinate("x")
y = self.__InputCoordinate("y")
if not self.__Landscape[x][y].Warren is None:
self.__Landscape[x][y].Warren.Inspect()
self.__ViewRabbits = input("View individual rabbits (y/n)? ")
if self.__ViewRabbits == "y":
self.__Landscape[x][y].Warren.ListRabbits()
input()
def __InputCoordinate(self, CoordinateName):
Coordinate = int(input(" Input " + CoordinateName + " coordinate:"))
return Coordinate
def __AdvanceTimePeriod(self):
NewFoxCount = 0
if self.__ShowDetail:
print()
for x in range (0, self.__LandscapeSize):
for y in range (0, self.__LandscapeSize):
if not self.__Landscape[x][y].Warren is None:
if self.__ShowDetail:
print("Warren at (", x, ",", y, "):", sep = "")
print(" Period Start: ", end = "")
self.__Landscape[x][y].Warren.Inspect()
if self.__FoxCount > 0:
self.__FoxesEatRabbitsInWarren(x, y)
if self.__Landscape[x][y].Warren.NeedToCreateNewWarren():
self.__CreateNewWarren()
self.__Landscape[x][y].Warren.AdvanceGeneration(self.__ShowDetail)
if self.__ShowDetail:
print(" Period End: ", end = "")
self.__Landscape[x][y].Warren.Inspect()
input()
if self.__Landscape[x][y].Warren.WarrenHasDiedOut():
self.__Landscape[x][y].Warren = None
self.__WarrenCount -= 1
for x in range (0, self.__LandscapeSize):
for y in range (0, self.__LandscapeSize):
if not self.__Landscape[x][y].Fox is None:
if self.__ShowDetail:
print("Fox at (", x, ",", y, "): ", sep = "")
self.__Landscape[x][y].Fox.AdvanceGeneration(self.__ShowDetail)
if self.__Landscape[x][y].Fox.CheckIfDead():
self.__Landscape[x][y].Fox = None
self.__FoxCount -= 1
else:
if self.__Landscape[x][y].Fox.ReproduceThisPeriod():
if self.__ShowDetail:
print(" Fox has reproduced. ")
NewFoxCount += 1
if self.__ShowDetail:
self.__Landscape[x][y].Fox.Inspect()
self.__Landscape[x][y].Fox.ResetFoodConsumed()
if NewFoxCount > 0:
if self.__ShowDetail:
print("New foxes born: ")
for f in range (0, NewFoxCount):
self.__CreateNewFox()
if self.__ShowDetail:
input()
self.__DrawLandscape()
print()
def __CreateLandscapeAndAnimals(self, InitialWarrenCount, InitialFoxCount, FixedInitialLocations):
for x in range (0, self.__LandscapeSize):
for y in range (0, self.__LandscapeSize):
self.__Landscape[x][y] = Location()
if FixedInitialLocations:
self.__Landscape[1][1].Warren = Warren(self.__Variability, 38)
self.__Landscape[2][8].Warren = Warren(self.__Variability, 80)
self.__Landscape[9][7].Warren = Warren(self.__Variability, 20)
self.__Landscape[10][3].Warren = Warren(self.__Variability, 52)
self.__Landscape[13][4].Warren = Warren(self.__Variability, 67)
self.__Landscape[11][4].Warren = GiantWarren(self.__Variability, 115)
self.__WarrenCount = 6
self.__Landscape[2][10].Fox = Fox(self.__Variability)
self.__Landscape[6][1].Fox = Fox(self.__Variability)
self.__Landscape[8][6].Fox = Fox(self.__Variability)
self.__Landscape[11][13].Fox = Fox(self.__Variability)
self.__Landscape[12][4].Fox = Fox(self.__Variability)
self.__FoxCount = 5
else:
for w in range (0, InitialWarrenCount):
self.__CreateNewWarren()
for f in range (0, InitialFoxCount):
self.__CreateNewFox()
def __CreateNewWarren(self):
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
while not self.__Landscape[x][y].Warren is None:
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
if self.__ShowDetail:
print("New Warren at (", x, ",", y, ")", sep = "")
self.__Landscape[x][y].Warren = Warren(self.__Variability)
self.__WarrenCount += 1
def __CreateNewFox(self):
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
while not self.__Landscape[x][y].Fox is None:
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
if self.__ShowDetail:
print(" New Fox at (", x, ",", y, ")", sep = "")
self.__Landscape[x][y].Fox = Fox(self.__Variability)
self.__FoxCount += 1
def __FoxesEatRabbitsInWarren(self, WarrenX, WarrenY):
RabbitCountAtStartOfPeriod = self.__Landscape[WarrenX][WarrenY].Warren.GetRabbitCount()
for FoxX in range(0, self.__LandscapeSize):
for FoxY in range (0, self.__LandscapeSize):
if not self.__Landscape[FoxX][FoxY].Fox is None:
Dist = self.__DistanceBetween(FoxX, FoxY, WarrenX, WarrenY)
if Dist <= 3.5:
PercentToEat = 20
elif Dist <= 7:
PercentToEat = 10
else:
PercentToEat = 0
RabbitsToEat = int(round(float(PercentToEat * RabbitCountAtStartOfPeriod / 100)))
FoodConsumed = self.__Landscape[WarrenX][WarrenY].Warren.EatRabbits(RabbitsToEat)
self.__Landscape[FoxX][FoxY].Fox.GiveFood(FoodConsumed)
if self.__ShowDetail:
print(" ", FoodConsumed, " rabbits eaten by fox at (", FoxX, ",", FoxY, ").", sep = "")
def __DistanceBetween(self, x1, y1, x2, y2):
return math.sqrt((pow(x1 - x2, 2) + pow(y1 - y2, 2)))
def __DrawLandscape(self):
print()
print("TIME PERIOD:", self.__TimePeriod)
print()
print(" ", end = "")
for x in range (0, self.__LandscapeSize):
if x < 10:
print(" ", end = "")
print(x, "|", end = "")
print()
for x in range (0, self.__LandscapeSize * 4 + 3):
print("-", end = "")
print()
for y in range (0, self.__LandscapeSize):
if y < 10:
print(" ", end = "")
print("", y, "|", sep = "", end = "")
for x in range (0, self.__LandscapeSize):
if not self.__Landscape[x][y].Warren is None:
if self.__Landscape[x][y].Warren.GetRabbitCount() < 10:
print(" ", end = "")
print(self.__Landscape[x][y].Warren.GetRabbitCount(), end = "")
else:
print(" ", end = "")
if not self.__Landscape[x][y].Fox is None:
print("F", end = "")
else:
print(" ", end = "")
print("|", end = "")
print()
class Warren:
def __init__(self, Variability, RabbitCount = 0):
self.__MAX_RABBITS_IN_WARREN = 99
self.__RabbitCount = RabbitCount
self.__PeriodsRun = 0
self.__AlreadySpread = False
self.__Variability = Variability
self.__Rabbits = []
for Count in range(0, self.__MAX_RABBITS_IN_WARREN):
self.__Rabbits.append(None)
if self.__RabbitCount == 0:
self.__RabbitCount = int(self.__CalculateRandomValue(int(self.__MAX_RABBITS_IN_WARREN / 4), self.__Variability))
for r in range (0, self.__RabbitCount):
self.__Rabbits[r] = Rabbit(self.__Variability)
def __CalculateRandomValue(self, BaseValue, Variability):
return BaseValue - (BaseValue * Variability / 100) + (BaseValue * random.randint(0, Variability * 2) / 100)
def GetRabbitCount(self):
return self.__RabbitCount
def NeedToCreateNewWarren(self):
if self.__RabbitCount == self.__MAX_RABBITS_IN_WARREN and not self.__AlreadySpread:
self.__AlreadySpread = True
return True
else:
return False
def WarrenHasDiedOut(self):
if self.__RabbitCount == 0:
return True
else:
return False
def AdvanceGeneration(self, ShowDetail):
self.__PeriodsRun += 1
if self.__RabbitCount > 0:
self.__KillByOtherFactors(ShowDetail)
if self.__RabbitCount > 0:
self.__AgeRabbits(ShowDetail)
if self.__RabbitCount > 0 and self.__RabbitCount <= self.__MAX_RABBITS_IN_WARREN:
if self.__ContainsMales():
self.__MateRabbits(ShowDetail)
if self.__RabbitCount == 0 and ShowDetail:
print(" All rabbits in warren are dead")
def EatRabbits(self, RabbitsToEat):
DeathCount = 0
if RabbitsToEat > self.__RabbitCount:
RabbitsToEat = self.__RabbitCount
while DeathCount < RabbitsToEat:
RabbitNumber = random.randint(0, self.__RabbitCount - 1)
if not self.__Rabbits[RabbitNumber] is None:
self.__Rabbits[RabbitNumber] = None
DeathCount += 1
self.__CompressRabbitList(DeathCount)
return RabbitsToEat
def __KillByOtherFactors(self, ShowDetail):
DeathCount = 0
for r in range (0, self.__RabbitCount):
if self.__Rabbits[r].CheckIfKilledByOtherFactor():
self.__Rabbits[r] = None
DeathCount += 1
self.__CompressRabbitList(DeathCount)
if ShowDetail:
print(" ", DeathCount, "rabbits killed by other factors.")
def __AgeRabbits(self, ShowDetail):
DeathCount = 0
for r in range (0, self.__RabbitCount):
self.__Rabbits[r].CalculateNewAge()
if self.__Rabbits[r].CheckIfDead():
self.__Rabbits[r] = None
DeathCount += 1
self.__CompressRabbitList(DeathCount)
if ShowDetail:
print(" ", DeathCount, "rabbits die of old age.")
def __MateRabbits(self, ShowDetail):
Mate = 0
Babies = 0
for r in range (0, self.__RabbitCount):
if self.__Rabbits[r].IsFemale() and self.__RabbitCount + Babies < self.__MAX_RABBITS_IN_WARREN:
Mate = random.randint(0, self.__RabbitCount - 1)
while Mate == r or self.__Rabbits[Mate].IsFemale():
Mate = random.randint(0, self.__RabbitCount - 1)
CombinedReproductionRate = (self.__Rabbits[r].GetReproductionRate() + self.__Rabbits[Mate].GetReproductionRate()) / 2
if CombinedReproductionRate >= 1:
self.__Rabbits[self.__RabbitCount + Babies] = Rabbit(self.__Variability, CombinedReproductionRate)
Babies += 1
self.__RabbitCount = self.__RabbitCount + Babies
if ShowDetail:
print(" ", Babies, "baby rabbits born.")
def __CompressRabbitList(self, DeathCount):
if DeathCount > 0:
ShiftTo = 0
ShiftFrom = 0
while ShiftTo < self.__RabbitCount - DeathCount:
while self.__Rabbits[ShiftFrom] is None:
ShiftFrom += 1
if ShiftTo != ShiftFrom:
self.__Rabbits[ShiftTo] = self.__Rabbits[ShiftFrom]
ShiftTo += 1
ShiftFrom += 1
self.__RabbitCount = self.__RabbitCount - DeathCount
def __ContainsMales(self):
Males = False
for r in range (0, self.__RabbitCount):
if not self.__Rabbits[r].IsFemale():
Males = True
return Males
def Inspect(self):
print("Periods Run", self.__PeriodsRun, "Size", self.__RabbitCount)
def ListRabbits(self):
if self.__RabbitCount > 0:
for r in range (0, self.__RabbitCount):
self.__Rabbits[r].Inspect()
class GiantWarren(Warren):
def __init__(self, Variability, RabbitCount = 1):
super(GiantWarren, self).__init__(self.__RabbitCount, Variability)
self.__MAX_RABBITS_IN_WARREN = 200
self.__RabbitCount = RabbitCount
self.__PeriodsRun = 0
self.__Variability = Variability
self.__Rabbits = []
for Count in range(0, self.__MAX_RABBITS_IN_WARREN):
self.__Rabbits.append(None)
if self.__RabbitCount == 1:
self.__RabbitCount = int(self.__CalculateRandomValue(int(self.__MAX_RABBITS_IN_WARREN / 4), self.__Variability))
for r in range (0, self.__RabbitCount):
self.__Rabbits[r] = Rabbit(self.__Variability)
class Animal:
_ID = 1
def __init__(self, AvgLifespan, AvgProbabilityOfDeathOtherCauses, Variability):
self._NaturalLifespan = int(AvgLifespan * self._CalculateRandomValue(100, Variability) / 100)
self._ProbabilityOfDeathOtherCauses = AvgProbabilityOfDeathOtherCauses * self._CalculateRandomValue(100, Variability) / 100
self._IsAlive = True
self._ID = Animal._ID
self._Age = 0
Animal._ID += 1
def CalculateNewAge(self):
self._Age += 1
if self._Age >= self._NaturalLifespan:
self._IsAlive = False
def CheckIfDead(self):
return not self._IsAlive
def Inspect(self):
print(" ID", self._ID, "", end = "")
print("Age", self._Age, "", end = "")
print("LS", self._NaturalLifespan, "", end = "")
print("Pr dth", round(self._ProbabilityOfDeathOtherCauses, 2), "", end = "")
def CheckIfKilledByOtherFactor(self):
if random.randint(0, 100) < self._ProbabilityOfDeathOtherCauses * 100:
self._IsAlive = False
return True
else:
return False
def _CalculateRandomValue(self, BaseValue, Variability):
return BaseValue - (BaseValue * Variability / 100) + (BaseValue * random.randint(0, Variability * 2) / 100)
class Fox(Animal):
def __init__(self, Variability, genderRatio = 33):
self.__DEFAULT_LIFE_SPAN = 7
self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES = 0.1
super(Fox, self).__init__(self.__DEFAULT_LIFE_SPAN, self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES, Variability)
self.__FoodUnitsNeeded = int(10 * self._CalculateRandomValue(100, Variability) / 100)
self.__FoodUnitsConsumedThisPeriod = 0
if random.randint(0, 100) < genderRatio:
self.__Gender = Genders.Male
else:
self.__Gender = Genders.Female
def AdvanceGeneration(self, ShowDetail):
if self.__FoodUnitsConsumedThisPeriod == 0:
self._IsAlive = False
if ShowDetail:
print(" Fox dies as has eaten no food this period.")
else:
if self.CheckIfKilledByOtherFactor():
self._IsAlive = False
if ShowDetail:
print(" Fox killed by other factor.")
else:
if self.__FoodUnitsConsumedThisPeriod < self.__FoodUnitsNeeded:
self.CalculateNewAge()
if ShowDetail:
print(" Fox ages further due to lack of food.")
self.CalculateNewAge()
if not self._IsAlive:
if ShowDetail:
print(" Fox has died of old age.")
def ResetFoodConsumed(self):
self.__FoodUnitsConsumedThisPeriod = 0
def ReproduceThisPeriod(self):
REPRODUCTION_PROBABILITY = 0.25
if self.__Gender == Genders.Female:
if random.randint(0, 100) < REPRODUCTION_PROBABILITY * 100:
return True
else:
return False
def GiveFood(self, FoodUnits):
self.__FoodUnitsConsumedThisPeriod = self.__FoodUnitsConsumedThisPeriod + FoodUnits
def IsFemale(self):
if self.__Gender == Genders.Female:
return True
else:
return False
def Inspect(self):
super(Fox, self).Inspect()
print("Food needed", self.__FoodUnitsNeeded, "", end = "")
print("Food eaten", self.__FoodUnitsConsumedThisPeriod, "", end = "")
if self.__Gender == Genders.Male:
gender = "Male"
else:
gender = "Female"
print("Gender", gender, "", end="")
print()
class Genders(enum.Enum):
Male = 1
Female = 2
class Rabbit(Animal):
def __init__(self, Variability, ParentsReproductionRate = 1.2, genderRatio=50):
self.__DEFAULT_LIFE_SPAN = 4
self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES = 0.05
super(Rabbit, self).__init__(self.__DEFAULT_LIFE_SPAN, self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES, Variability)
self.__ReproductionRate = ParentsReproductionRate * self._CalculateRandomValue(100, Variability) / 100
if random.randint(0, 100) < genderRatio:
self.__Gender = Genders.Male
else:
self.__Gender = Genders.Female
def Inspect(self):
super(Rabbit, self).Inspect()
print("Rep rate", round(self.__ReproductionRate, 1), "", end = "")
if self.__Gender == Genders.Female:
print("Gender Female")
else:
print("Gender Male")
def IsFemale(self):
if self.__Gender == Genders.Female:
return True
else:
return False
def GetReproductionRate(self):
return self.__ReproductionRate
def Main():
MenuOption = 0
while MenuOption != 3:
print("Predator Prey Simulation Main Menu")
print()
print("1. Run simulation with default settings")
print("2. Run simulation with custom settings")
print("3. Rabbit Paradise")
print("4. Exit")
print()
try:
MenuOption = int(input("Select option: "))
except:
print("What you have entered is not an integer. Try again")
if MenuOption == 1 or MenuOption == 2 or MenuOption == 3:
if MenuOption == 1:
LandscapeSize = 15
InitialWarrenCount = 5
InitialFoxCount = 5
Variability = 0
FixedInitialLocations = True
elif MenuOption == 3:
LandscapeSize = 20
InitialWarrenCount = 20
InitialFoxCount = 0
Variability = 1
FixedInitialLocations = False
else:
LandscapeSize = int(input("Landscape Size: "))
InitialWarrenCount = int(input("Initial number of warrens: "))
InitialFoxCount = int(input("Initial number of foxes: "))
Variability = int(input("Randomness variability (percent): "))
FixedInitialLocations = False
Sim = Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations)
input()
if __name__ == "__main__":
Main()
The problem is the indiscriminate use of double-underscore prefixes on the method and attribute names. That's used to invoke name mangling and is specifically intended to prevent inheritance; it provides the closest thing to "private" variables that Python has.
The student definitely does not want to use it anywhere here; generally, I recommend never using it at all. Just give everything normal names.
(Note also, since they're programming Python, they should use Python conventions for naming: variables, attributes and methods should have lower_case_with_underscore names, not CamelCase which is intended for class names.)
I am not sure why do i get this error from the console:
<<
print stirngp[state[i][j]]
^
SyntaxError: invalid syntax
<<
Furthermore it seems that the IDE put a red close on the following code line
line = raw_input("Enter:")
I am not sure what did i do wrong, the following code is as shown below
def isTerminal(state):
stateT = zip(*state)
for i in range(3):
if all(state[i][0] == j for j in state[i]) and state[i][0] != 0:
return state[i][0]
if all(stateT[i][0] == j for j in stateT[i]) and stateT[i][0] != 0:
return stateT[i][0]
if (state[0][0] == state[1][1] == state[2][2]) or \
(state[0][2] == state[1][1] == state[2][0]):
if state[1][1] != 0:
return state[1][1]
for i in range(3):
if 0 in state[i]:
return None
return 0
def succ(state):
# print state
countX = 0
countO = 0
for i in range(3):
for j in range(3):
if state[i][j] == 1: countX = countX + 1
if state[i][j] == -1: countO = countO + 1
if countX > countO:
player = "MIN"
else:
player = "MAX"
succList = []
v = {"MIN":-1,"MAX":1}
for i in range(3):
for j in range(3):
if state[i][j] == 0:
succ = [k[:] for k in state]
succ[i][j] = v[player]
succList = succList + [succ]
# print succList
return succList
def nextplay(player):
if player == "MIN":
return "MAX"
else:
return "MIN"
def minimax(state,alpha,beta,player):
value = isTerminal(state)
if value != None:
# print "TERMINAL:", state, value, player
return value
if player == "MIN":
for y in succ(state):
beta = min(beta, minimax(y,alpha,beta,"MAX"))
if beta <= alpha: return alpha
return beta
if player == "MAX":
for y in succ(state):
alpha = max(alpha, minimax(y,alpha,beta,"MIN"))
if alpha >= beta: return beta
return alpha
def printing(state):
p = {-1:"O",0:".",1:"X"}
for i in range(3):
for j in range(3):
print p[state[i][j]],
print ""
print ""
def main():
state = [[0,0,0],
[0,0,0],
[0,0,0]]
val = isTerminal(state)
while val == None:
line = raw_input("Enter:")
x = line.split(",")
a = int(x[0]); b = int(x[1])
state[a][b] = 1
if isTerminal(state) != None:
printing(state)
return
# determine which successive state is better
succList = succ(state)
succValList = []
for i in succList:
succValList = succValList + [(minimax(i,-1,1,"MAX"),i)]
succValList.sort(key=lambda x:x[0])
state = succValList[0][1] # can also randomly choose other states of the same minimax value
printing(state)
val = isTerminal(state)
if __name__ == '__main__':
main()
As far as i know you can't use raw_input() in Python 3. It's been changed to just input()
http://docs.python.org/dev/whatsnew/3.0.html
also what is stringp? is it an existing list?
if so then state[i][j] MUST return an integer so you can retrieve the item at that index of stringp[]