Im currently trying to add a player to a board in python to be able to command the player but I cant seem to figure it out.
def GenPlayer(level):
player = {}
player['name'] = GenName()
player['history'] = GenHistory() #history
player['attack'] = DieRoller(3,6) + DieRoller(level,4)
player['defense'] = DieRoller(3,6) + DieRoller(level,4)
player['health'] = DieRoller(5,6) + DieRoller(level,4)
player['row'] = 0
player['col'] = 0
character =(player['name']) + ("Health: "+str(player['health'])) + (" Defense: "+str(player['defense'])) + (" Attack: "+str(player['attack']))
return character
def CreateBoard():
board = []
while True:
x = int(input("Number of Rows: "))
y = x
break
for row in range(0,x):
board.append(["()"]*y)
return board
def ShowBoard(board):
for row in board:
print(" ".join(row))
def PlacePlayer(board,player):
row = DieRoller(1,6)
col = DieRoller(1,6)
board[row][col] = 'player'
return board,player
print(PlacePlayer(ShowBoard(CreateBoard()),GenPlayer(1)))
I keep getting this error when trying this code:
Exception has occurred: TypeError
'NoneType' object is not subscriptable
If you want to place the player object at the selected position, remove the quote marks:
board[row][col] = player
Update:
A player object is a dictionary, so you need to place the player['name'] on the board to be able to print it in the ShowBoard() function you have, as the function uses .join() , which is a string method. I made a slight change to PlacePlayer(), and simplified the code to make it a bit easier to understand what's happening:
def PlacePlayer(board,player):
row = 5
col = 4
board[row][col] = player['name']
return board
newboard= CreateBoard()
characterDescripiton , playerobject = GenPlayer(1)
boardafterPlacePlayer = PlacePlayer(newboard,playerobject)
ShowBoard(boardafterPlacePlayer)
Related
I'm new to python and writing my first project. I'm trying to implement a check that if a space is already occupied, not to move there. I can't seem to figure out why my move_player method overwrites the index value of the board even though I am explicitly checking it (If it is O's turn and X has already been placed in the index O is trying to move to, it just overwrites it). I have tried hard coding the check for 'X' and 'O' instead of player.player as well but can't seem to figure it out. Does it have to do something with how Python works or am I implementing it wrong?
class Player:
def __init__(self, player):
self.player = player
class Board:
def __init__(self):
self.board = [[' ' for i in range(3)] for j in range(3)]
def display_board(self):
print('---------')
for row in self.board:
print('| ', end='')
for col in row:
print(f'{col} ', end='')
print('|')
print('---------')
def move_player(self, player):
try:
p1 = Player('X')
p2 = Player('O')
coordinates = [int(i) for i in input("Enter coordinates for move: ").split()]
xCoordinate = coordinates[0]
yCoordinate = coordinates[1]
if ((self.board[xCoordinate][yCoordinate] == p1.player) or
(self.board[xCoordinate][yCoordinate] == p2.player)):
print("That space is occupied, please choose another one.")
self.move_player(player)
else:
self.board[xCoordinate - 1][yCoordinate - 1] = player.player
except (ValueError, IndexError):
print("Please only enter numbers between 1 and 3.")
self.move_player(player)
def has_won(self, player):
if self.check_diagonal(player):
return True
elif self.check_across(player):
return True
elif self.check_down(player):
return True
return False
if __name__ == '__main__':
board = Board()
player1 = Player('X')
player2 = Player('O')
player = player1
while True:
board.display_board()
board.move_player(player)
if board.has_won(player):
board.display_board()
print(f'{player.player} wins!!!')
break
if player == player1:
player = player2
else:
player = player1
The code is very convoluted but from what I can see:
if ((self.board[xCoordinate][yCoordinate] == p1.player) or
(self.board[xCoordinate][yCoordinate] == p2.player)):
...
self.board[xCoordinate - 1][yCoordinate - 1] = player.player
You are checking [x,y] but assigning to [x-1,y-1].
The following is my code
n = int(input("please enter a value: "))
board = []
def make_board(n):
global board
max = n * n #the number of tiles in the board
count = 1 #a counter to change the value assigned to each tile
for i in range(n):
board.append([]) #appends a list inside the list of board. Essentially creates a row which is of type list.
for j in range(n):
num = max - count
if num == 0: #the 0 tile will display like a blank space
tile = ' '
elif num < 10: #adds a space to tile values less than 10 for formatting.
tile = ' ' + str(num)
else:
tile = str(num)
board[i].append(tile) #appends a tile value to each row, n number of times.
count += 1
if n%2 == 0:
tempvara = board[n-1][n-2]
tempvarb = board[n-1][n-3]
board[n-1][n-2]=tempvarb
board[n-1][n-3]=tempvara
#TODO
for row in board:
print(' '.join(row))
def find_blank(board):
global counterUNO
global counterDOS
global counterTRES
counterTRES = 0
#TODO
for i in range(n):
tempvari = board[i]
if ' ' in tempvari:
counterUNO = i
for z in board[counterUNO]:
counterTRES = counterTRES + 1
if ' ' in z:
counterDOS = counterTRES-1
break
tupleone = (counterUNO,counterDOS)
return(tupleone)
def find_tile(f):
counterfour = 0
tiles = str(input("tile BUBBER"))
if int(tiles)<10:
tiles = " "+tiles
counterfive = 0
countersixe = 0
countersixe = 0
for i in range(n):
chopstick = board[i]
if tiles in chopstick:
counterfour = i
for z in board[counterfour]:
countersixe = countersixe + 1
if tiles in z:
counterfive = countersixe-1
break
tupleDOS = (counterfour,counterfive)
return(tupleDOS)
def find_next_to_blank(board):
#print("here is the shit")
#print(find_tile(board))
vara = find_tile(board) #sets tile numb tuple to vara
varb = find_blank(board) #yeah
varc = int(tiles)
varaa = int(tiles[0])
varab = int(tiles[1])
varba = board[varaa+1][varab]
varbb = board[varaa][varab+1]
varbc = board[varaa-1][varab]
varbd = board[varaa][varab-1]
varbe = board[varaa+1][varab+1]
varbf = board[varaa-1][varab-1]
make_board(n)
#find_blank(board)
#find_tile(board)
find_next_to_blank(board)
Problem:
Right now I am trying to make a python Tile game where I can shift the numbers. the make board function obviously creates a board, i did it so that there are three lists in a big list and in the three list there are elements
and the find blank function identifies the coordinate of the non existing section of the board
and the find tile function is the function that the user inputs a value and the code identifies what is the coordinate of the tile that we want
So currently I am getting an error because when i am running the find next to blank function (the function is supposed to identify whether or not there is a blank spot next to the value which the user wants to input) i get the following error
Traceback (most recent call last):
File "python", line 149, in <module>
File "python", line 122, in find_next_to_blank
NameError: name 'tiles' is not defined
and i tried making "tiles" variable into a global one but it didn't work at all
The variable tiles is not defined in find_next_to_blank(board). I'd be remiss if I don't say this: consider restructuring your program to avoid using global variables.
Now that's out of the way, if you make tiles global, it ought to work.
Python beginner here--working on a Battleship project for a class. My program will loop through the first player to place their ships. The grid does successfully print the visual ships on the board, but once i get to player two, the ships are overlapping with player one. (also note there is some validation work that still needs to be done).
I think the issue is that maybe I'm storing both coordinates for each player in the same list. So my question is how do I store the values for each player so that I can get the board to print ships only applicable to each player?
Here are my classes:
BOARD_SIZE = 10
class Ship:
def __init__(self, ship_name, size, coords, player, direction):
self.ship_name = ship_name
self.size = size
self.player = player
self.coords = coords
self.direction = direction
class Board:
def __init__(self):
self.board = []
self.guesses = []
board = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)]
def add_ship(self, name, size, player, coords, direction):
for coord in coords:
# convert string like "a1" to x,y coordinates
y = ord(coord[0])-ord('a')
x = int(coord[1:])-1
# update the board at this position
self.board = board[x][y]
print(" " + " ".join([chr(c) for c in range(ord('A'), ord('A') + BOARD_SIZE)]))
row_num = 1
for row in board:
print(str(row_num).rjust(2) + " " + (" ".join(row)))
row_num += 1
self.board.append(Ship(coords,player,name,size,direction))
def print_board_heading(self):
print(" " + " ".join([chr(c) for c in range(ord('A'), ord('A') + BOARD_SIZE)]))
def print_board(self):
board = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)]
print_board_heading()
row_num = 1
for row in board:
print(str(row_num).rjust(2) + " " + (" ".join(row)))
row_num += 1
def print_updated_board(coords, direction, board, player):
for coord in coords:
# convert string like "a1" to x,y coordinates
y = ord(coord[0])-ord('a')
x = int(coord[1:])-1
# update the board at this position
board[x][y] = '|' if direction == 'v' else '-'
print(" " + " ".join([chr(c) for c in range(ord('A'), ord('A') + BOARD_SIZE)]))
row_num = 1
for row in board:
print(str(row_num).rjust(2) + " " + (" ".join(row)))
row_num += 1
class Player():
def __init__(self,name):
self.name = name
self.board = Board()
self.ships = []
self.guesses = []
And the battleship game file:
from ship import Ship, Player, Board
SHIP_INFO = [
("Aircraft Carrier", 5),
("Battleship", 4),
("Submarine", 3),
("Cruiser", 3),
("Patrol Boat", 2)
]
BOARD_SIZE = 10
VERTICAL_SHIP = '|'
HORIZONTAL_SHIP = '-'
EMPTY = 'O'
MISS = '.'
HIT = '*'
SUNK = '#'
board = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)]
def print_board_heading():
print(" " + " ".join([chr(c) for c in range(ord('A'), ord('A') + BOARD_SIZE)]))
def print_board():
board = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)]
print_board_heading()
row_num = 1
for row in board:
print(str(row_num).rjust(2) + " " + (" ".join(row)))
row_num += 1
def print_updated_board(coords, direction,board):
# create an empty board
# board = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)]
# at each coordinate, draw a ship
for coord in coords:
# convert string like "a1" to x,y coordinates
y = ord(coord[0])-ord('a')
x = int(coord[1:])-1
# update the board at this position
board[x][y] = '|' if direction == 'v' else '-'
print_board_heading()
row_num = 1
for row in board:
print(str(row_num).rjust(2) + " " + (" ".join(row)))
row_num += 1
def clear_screen():
print("\033c", end="")
def get_coordinates(ship):
while True:
print("\n")
coordinate = input("Where do you want the " + ship + "(example: A1)?: ")
coords_strip = coordinate.strip()
coords_lower = coords_strip.lower()
x = coords_lower[0]
y = coords_lower[1:]
if (len(x)+len(y)) in range(2,4):
if x not in 'abcdefghij' or y not in '1,2,3,4,5,6,7,8,9,10':
print("Oops! That was not a valid entry. Try again...")
continue
else:
return x, y
else:
if len(coords_lower) < 2 or len(coords_lower) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
def get_direction():
while True:
dir = input("[H]orizontal or [V]ertical?: ")
dir_strip = dir.strip()
direction = dir_strip.lower()
if direction not in 'hv':
print("Oops! That was not a valid entry. Try again...")
continue
else:
return direction
def create_ship_coordinates(x, y, size, direction):
ship_col = ord(x)
ship_row = int(y)
if direction == 'v':
# ship runs vertically DOWN from coordinate
coords = [chr(ship_col) + str(r) for r in range(ship_row, ship_row + size)]
return coords
else:
# ship runs horizontally RIGHT from coordinate
coords = [chr(col) + str(ship_row) for col in range(ship_col, ship_col + size)]
return coords
def place_user_ships(player):
ships = []
print_board()
print("\n")
print("Let's go " + player + " !")
for ship, size in SHIP_INFO:
while True:
# ask for starting coordinate
x, y = get_coordinates(ship)
# ask for vertical or horizontal direction
direction = get_direction()
# create the coordinates for the ship placement
coords = create_ship_coordinates(x, y, size, direction)
# validate the
# new_ship = Board().add_ship(ship, size, coords, direction, player)
# update = Board.print_updated_board(coords,direction,board,player)
break
# create ship from data
# add the ship from above to a player list
# player = Player(board)
# place the ship on the game board
# print out the board to reflect the shp placement
clear_screen()
print("\n")
input("All ships placed for {}. Please hit ENTER to continue....".format(player))
player1 = input("What's Player 1's Name? ")
player2 = input("What's Player 2's Name? ")
# define player one's fleet
place_user_ships(player1)
place_user_ships(player2)
IIRC, in battleship there are really four boards. One is managed by each player with their shots at the enemy, and the other is the player's own ships and incoming shots from the enemy.
The "shot" process is one of notifying the enemy where the shot was taken, the enemy responding with "hit" or "miss", and recording the result on the local player's outgoing-shots board.
The "notification" process is one of receiving a location where an enemy shot was made, looking up the result on the local-ships board, returning "hit" or "miss", and updating the local ships board to indicate the enemy shot.
So you have a Player, with a pair of Boards. You might also have a Game class to marry the two players.
Inputting the ships is going to depend a lot on your actual user interface. Are you doing graphics with a mouse? Are you doing text with a mouse? Text with arrow keys via curses or some such? Simple coordinate inputs?
If you're doing coordinates, you probably want something simple, like x,y,{up,down,left,right} to eliminate having to position every block of the ship.
Again, there is a Board method here - placing a ship. The board can enforce whatever rules you have about placement (ex: can two ships be directly adjacent? Or must there be a one-space gap between?) and reject the inappropriate attempts.
If you put all the wisdom in your Board class, then the Player classes can be simple, with just links to the boards. And the game can manage the players in turn:
def play(self):
p1 = self.player[0]
p2 = self.player[1]
try:
while True:
self.attack(p1, p2)
self.attack(p2, p1)
except Victory v:
print("The winner is", v.player.name)
I notice you doing things like player1 = input("What is player 1's name?"). This is something that should be pushed into the player classes.
Try to design from the top down: game, player, board. And try following the rule, "Tell, don't ask." That is, if something needs to be done, you tell a class to do it, instead of asking the class for data and doing it yourself.
Instead of this:
move = player1.get_move()
if valid_move(move):
...
Do this:
player1.make_move()
And push the logic downwards. Eventually, you get to the place where the knowledge "should be". The player "should" make moves. The board "should" know what is a valid move or not. And every method "should" be given enough data to do its job. ;-)
I am trying to write a program for connect 4 but am having a lot of trouble getting past the directions. Everything under the comment, "#everything works up to here" works but then it all explodes and I have no idea even where to start to fix it.
#connect 4
import random
#define global variables
X = "X"
O = "O"
EMPTY = "_"
TIE = "TIE"
NUM_ROWS = 6
NUM_COLS = 8
def display_instruct():
"""Display game instructions."""
print(
"""
Welcome to the second greatest intellectual challenge of all time: Connect4.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a column number, 1 - 7. Your move
(if that column isn't already filled) will move to the lowest available position.
Prepare yourself, human. May the Schwartz be with you! \n
"""
)
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question,low,high):
"""Ask for a number within range."""
#using range in Python sense-i.e., to ask for
#a number between 1 and 7, call ask_number with low=1, high=8
low=1
high=NUM_COLS
response = None
while response not in range (low,high):
response=int(input(question))
return response
def pieces():
"""Determine if player or computer goes first."""
go_first = ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print("\nThen take the first move. You will need it.")
human = X
computer = O
else:
print("\nYour bravery will be your undoing... I will go first.")
computer = X
human = O
return computer, human
def new_board():
board = []
for x in range (NUM_COLS):
board.append([" "]*NUM_ROWS)
return board
def display_board(board):
"""Display game board on screen."""
for r in range(NUM_ROWS):
print_row(board,r)
print("\n")
def print_row(board, num):
"""Print specified row from current board"""
this_row = board[num]
print("\n\t| ", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num],"|")
print("\t", "|---|---|---|---|---|---|---|")
# everything works up to here!
def legal_moves(board):
"""Create list of column numbers where a player can drop piece"""
legal=True
while not legal:
col = input("What column would you like to move into (1-7)?")
for row in range (6,0,1):
if (1 <= row <= 6) and (1 <= col <= 7) and (board[row][col]==" "):
board[row][col] = turn
legal = True
else:
print("Sorry, that is not a legal move.")
def human_move(board,human):
"""Get human move"""
try:
legals = legal_moves(board)
move = None
while move not in legals:
move = ask_number("Which column will you move to? (1-7):", 1, NUM_COLS)
if move not in legals:
print("\nThat column is already full, nerdling. Choose another.\n")
print("Human moving to column", move)
return move #return the column number chosen by user
except NameError:
print ("Only numbers are allowed.")
except IndexError:
print ("You can only select colums from 1-7.")
def get_move_row(turn,move):
for m in (NUM_COLS):
place_piece(turn,move)
display_board()
def computer_move ():
move= random.choice(legal)
return move
def place_piece(turn,move):
if this_row[m[move]]==" ":
this_row.append[m[move]]=turn
def winner(board):
# Check rows for winner
for row in range(6):
for col in range(3):
if (board[row][col] == board[row][col + 1] == board[row][col + 2] == board[row][col + 3]) and (board[row][col] != " "):
return [row][col]
# Check columns for winner
for col in range(6):
for row in range(3):
if (board[row][col] == board[row + 1][col] == board[row + 2][col] ==board[row + 3][col]) and (board[row][col] != " "):
return [row][col]
# Check diagonal (top-left to bottom-right) for winner
for row in range(3):
for col in range (4):
if (board[row][col] == board[row + 1][col + 1] == board[row + 2][col + 2] == board[row + 3][col + 3]) and (board[row][col] != " "):
return true
# Check diagonal (bottom-left to top-right) for winner
for row in range (5,2,-1):
for col in range (3):
if (board[row][col] == board[row - 1][col + 1] == board[row - 2][col + 2] == board[row - 3][col + 3]) and (board[row][col] != " "):
return [row][col]
# No winner
return False
def main():
display_instruct()
computer,human = pieces()
turn = X
board = new_board()
while not winner(board) and (" " not in board):
display_board(board)
if turn == human:
human_move(board,human)
get_move_row()
place_piece()
else:
computer_move(board,computer)
place_piece()
display_board(board)
turn = next_turn()
the_winner = winner(board)
congrat_winner(the_winner, computer, human)
#start the program
main ()
input ("\nPress the enter key to quit.")
For fun, here's an object-oriented refactorization. It's a bit long, but well documented and should be easy to understand.
I started with your code and split it into Board, Player, and Game classes, then derived Computer and Human classes from Player.
Board knows the shape and size of the rack, what moves are legal, and recognizes when wins and ties occur
Player has a name and knows how to choose (or prompt for) a legal move
Game has a Board and two Players and controls turn-taking and output
I'm not 100% happy with it - Board has a .board that is a list of list of string, but Game has a .board that is a Board; a bit of judicious renaming would be a good idea - but for an hour's work it's pretty solid.
Hope you find this educational:
# Connect-4
from itertools import cycle, groupby
from random import choice
from textwrap import dedent
import sys
# version compatibility shims
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
def get_yn(prompt, default=None, truthy={"y", "yes"}, falsy={"n", "no"}):
"""
Prompt for yes-or-no input
Return default if answer is blank and default is set
Return True if answer is in truthy
Return False if answer is in falsy
"""
while True:
yn = inp(prompt).strip().lower()
if not yn and default is not None:
return default
elif yn in truthy:
return True
elif yn in falsy:
return False
def get_int(prompt, lo=None, hi=None):
"""
Prompt for integer input
If lo is set, result must be >= lo
If hi is set, result must be <= hi
"""
while True:
try:
value = int(inp(prompt))
if (lo is None or lo <= value) and (hi is None or value <= hi):
return value
except ValueError:
pass
def four_in_a_row(tokens):
"""
If there are four identical tokens in a row, return True
"""
for val,iterable in groupby(tokens):
if sum(1 for i in iterable) >= 4:
return True
return False
class Board:
class BoardWon (BaseException): pass
class BoardTied(BaseException): pass
EMPTY = " . "
HOR = "---"
P1 = " X "
P2 = " O "
VER = "|"
def __init__(self, width=8, height=6):
self.width = width
self.height = height
self.board = [[Board.EMPTY] * width for h in rng(height)]
self.tokens = cycle([Board.P1, Board.P2])
self.rowfmt = Board.VER + Board.VER.join("{}" for col in rng(width)) + Board.VER
self.rule = Board.VER + Board.VER.join(Board.HOR for col in rng(width)) + Board.VER
def __str__(self):
lines = []
for row in self.board:
lines.append(self.rowfmt.format(*row))
lines.append(self.rule)
lines.append(self.rowfmt.format(*("{:^3d}".format(i) for i in rng(1, self.width+1))))
lines.append("")
return "\n".join(lines)
def is_board_full(self):
return not any(cell == Board.EMPTY for cell in self.board[0])
def is_win_through(self, row, col):
"""
Check for any winning sequences which pass through self.board[row][col]
(This is called every time a move is made;
thus any win must involve the last move,
and it is faster to check just a few cells
instead of the entire board each time)
"""
# check vertical
down = min(3, row)
up = min(3, self.height - row - 1)
tokens = [self.board[r][col] for r in rng(row - down, row + up + 1)]
if four_in_a_row(tokens):
return True
# check horizontal
left = min(3, col)
right = min(3, self.width - col - 1)
tokens = [self.board[row][c] for c in rng(col - left, col + right + 1)]
if four_in_a_row(tokens):
return True
# check upward diagonal
down = left = min(3, row, col)
up = right = min(3, self.height - row - 1, self.width - col - 1)
tokens = [self.board[r][c] for r,c in zip(rng(row - down, row + up + 1), rng(col - left, col + right + 1))]
if four_in_a_row(tokens):
return True
# check downward diagonal
down = right = min(3, row, self.width - col - 1)
up = left = min(3, self.height - row - 1, col)
tokens = [self.board[r][c] for r,c in zip(rng(row - down, row + up + 1), rng(col + right, col - left - 1, -1))]
if four_in_a_row(tokens):
return True
# none of the above
return False
def legal_moves(self):
"""
Return a list of columns which are not full
"""
return [col for col,val in enumerate(self.board[0], 1) if val == Board.EMPTY]
def do_move(self, column):
token = next(self.tokens)
col = column - 1
# column is full?
if self.board[0][col] != Board.EMPTY:
next(self.move) # reset player token
raise ValueError
# find lowest empty cell (guaranteed to find one)
for row in rng(self.height-1, -1, -1): # go from bottom to top
if self.board[row][col] == Board.EMPTY: # find first empty cell
# take cell
self.board[row][col] = token
# did that result in a win?
if self.is_win_through(row, col):
raise Board.BoardWon
# if not, did it result in a full board?
if self.is_board_full():
raise Board.BoardTied
# done
break
class Player:
def __init__(self, name):
self.name = name
def get_move(self, board):
"""
Given the current board state, return the row to which you want to add a token
"""
# you should derive from this class instead of using it directly
raise NotImplemented
class Computer(Player):
def get_move(self, board):
return choice(board.legal_moves())
class Human(Player):
def get_move(self, board):
legal_moves = board.legal_moves()
while True:
move = get_int("Which column? (1-{}) ".format(board.width), lo=1, hi=board.width)
if move in legal_moves:
return move
else:
print("Please pick a column that is not already full!")
class Game:
welcome = dedent("""
Welcome to the second greatest intellectual challenge of all time: Connect4.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a column number, 1 - 7. Your move
(if that column isn't already filled) will move to the lowest available position.
Prepare yourself, human. May the Schwartz be with you!
""")
def __init__(self):
print(Game.welcome)
# set up new board
self.board = Board()
# set up players
self.players = cycle([Human("Dave"), Computer("HAL")])
# who moves first?
if get_yn("Do you want the first move? (Y/n) ", True):
print("You will need it...\n")
# default order is correct
else:
print("Your rashness will be your downfall...\n")
next(self.players)
def play(self):
for player in self.players:
print(self.board)
while True:
col = player.get_move(self.board) # get desired column
try:
print("{} picked Column {}".format(player.name, col))
self.board.do_move(col) # make the move
break
except ValueError:
print("Bad column choice - you can't move there")
# try again
except Board.BoardWon:
print("{} won the game!".format(player.name))
return
except Board.BoardTied:
print("The game ended in a stalemate")
return
def main():
while True:
Game().play()
if not get_yn("Do you want to play again? (Y/n) ", True):
break
if __name__=="__main__":
main()
I'm getting a invalid syntax with def spread_row()
I have a text file and it works fine in that but when i copy it into the final coding, it won't work. Help?
What I'm trying to do is make a 3x3 grid of random 1's and 0's. The code is incomplete so some of the coding doesn't so anything yet.
##variables to control all the games
##number of games played and points collected in total
games_so_far = 0
total_points = 0
## FOR ONE GAME
## variables that will be used for one single game
max_change = 0
## SUBROUTINES AND FUNCTIONS
import random
def invite_to_play():
play = raw_input("Would you like to play " + ask_again + "? (y/n): ")
if play == "y" or play == "Y":
play_response = True
else:
play_response = False
return play_response
def computer_play():
computer = raw_input("Would you like that the computer also plays? (y/n): ")
if computer =="y" or computer =="Y":
computer_response = True
else:
computer_response = False
return computer_response
def ask_user_int(question):
response = raw_input(question)
while not (response.isdigit()):
print "Your input must be an integer number"
response = raw_input(question)
return int(response)
def generate_random_number(dim):
## Generate a board of 0's and 1's, up to the size set in "dim"
return [random.randint(0,1) for i in range(dim)
def spread_row():
## Spaces the numbers evenly
for dat in data:
print " ".join(map(str, dat))
return data
def stop_max_changes()
print "No more changes, the game is over!"
return
def program_evaluates_board(numbers):
## Evaluates the rows and cols to see if they are even or odd
row1 = sum(data[0])
col1 = sum(row[0] for row in data)
row2 = sum(data[1])
col2 = sum(row[1] for row in data)
row3 = sum(data[2])
col3 = sum(row[2] for row in data)
if row1%2 == 0:
print "False"
else:
print "True"
return
## TOP LEVEL
print 'Welcome to the "An odd matrix" game' + \
"====================================="
games_so_far = 0
wants_to play = invite_to_play("")
computer = computer_play()
## LOOP TO PLAY MORE GAMES
while wants_to_play:
games_so_far = games_so_far + 1
num = ask_user_int("Size of board (between 3 and 6 inclusive): ")
dim = int(num)
data = [random_row(dim) for i in range(dim)]
spread_row()
print "The board is"
print "-------------"
print "\n(initial board)"
print "\n Col 0 Col 1 Col 2"
max_changes = ask_user_int("How many changes would you like to do?" + \
"\n > 0 and <= 2: ")
changes_so_far = 0
first of all , you missing a ":"
def stop_max_changes(): # missing : there
second, why there is a space in this return value ?:
wants_to play = invite_to_play("") # why space here ?
third, you are missing a right bracket
def generate_random_number(dim):
## Generate a board of 0's and 1's, up to the size set in "dim"
return [random.randint(0,1) for i in range(dim)
pls past full code , I can make full diagnose here ..