Recent Entries 6
- pattern minor 112d agoBattleship coordinate pickerI present to you... my battleship location picker! This will be part of a larger battleship program. The coordinates that are important are `finalcoords`. ``` from operator import itemgetter import getch import skilstak.colors as c #colors BOARDLENGTH = 10 BOARDHEIGHT = 10 board = [['_'] * BOARDLENGTH for _ in range(BOARDHEIGHT)] class Ship(): def __init__(self, size, symbol): self.size = size self.symbol = symbol self.coords = [(x,0) for x in range(size)] self.previous_coords = [(None,None) for _ in range(size)] def shift(self,direction): x_values = list(map(itemgetter(0), self.coords)) y_values = list(map(itemgetter(1), self.coords)) if direction == 'R' and 0 not in x_values: change = (-1,0) elif direction == 'D' and BOARDHEIGHT-1 not in y_values: change = (0,1) elif direction == 'U' and 0 not in y_values: change = (0,-1) elif direction == 'L' and BOARDLENGTH-1 not in x_values: change = (1,0) else: change = (0,0) for i, coord in enumerate(self.coords): self.previous_coords[i] = self.coords[i] self.coords[i] = (coord[0] + change[0], coord[1] + change[1]) def rotate(self): a, b = self.coords[0][0], self.coords[0][1] x, y = self.coords[-1][0], self.coords[-1][1] newx, newy = -(y-b)+a, (x-a)+b if newy >= 0 and newx >= 0 and newy <= BOARDHEIGHT-1 and newx <= BOARDLENGTH-1: for i, coord in enumerate(self.coords): self.previous_coords[i] = self.coords[i] self.coords[i] = (-(self.coords[i][1]-b)+a, (self.coords[i][0]-a)+b) def show(self, board, hasprevious=True): if hasprevious: for pcoord in self.previous_coords: board[pcoord[1]][pcoord[0]] = '_' for coord in self.coords: board[coord[1]][coord[0]] = self.symbol display_board = '\n'
- pattern minor 112d agoBattleship homeworkIt's a few weeks old homework, and it's already graded. How can I improve my code? Write function `empty(n)`, which gets the board size as an argument, and returns an empty board with the given size. For instance, empty(4) must return `['', '', '', '']`. Write function `isEmpty(board)` returns `True` if the given board is empty and `False` if it's not. Write function `inSeries(board)` that returns a string representation of the given board. Call `inSeries([' ', 'a', '', '', '', 'x', 'x', 'x', '', 'y', 'y', '', ''])` must return `' a xxx yy '`. Write function `space(board, position, length)`, which returns `True` if a ship of the given length can be put (starting) at the position on the given (possibly already non-empty) board. If not, the function returns `False`. Ships must not touch each other (but the can touch the border of the board). Write function `placed(board, position, length, label)`, which puts the ship with the given label and the given length at the given position on the board -- if this is possible -- and returns `True`. If putting the ship at this position is illegal, the function returns `False`. Write function `exists(board, label)` that return `True` if there is a ship with the given label on the board, and `False` if there's not. Write function `allTags(board)` that return a list of labels of all ships on the board. The labels can be in arbitrary order. Call `allTags(['a', '', 'x', 'x', 'x', '', 'y', 'y', '', ''])` can return, for instance, `['y', 'a', 'x']`. Write function `shot(board, position)`, which simulates targeting the given position on the board. The function returns `0`, in case of a miss, `1`, if a ship is hit, but not yet completely sunk, `2`, if the ship is sunk (e.g. the player hit the last piece of the ship), but the game is not over yet, `3`, if the last piece of the last ship is sunk and the game is over. Besides, the function must of course update the state of the board.
- pattern minor 112d agoBattleship GameInspired by this question, I went on with the following version. My goal was to focus on pure functions, to avoid mutable variables and to be strictly functional. I have ignored the computer player part - as it will not change the overall design. An issue may be that an unchanged player survives from one game state to the next. That's maybe not a good idea, but will it work here because game states are not used anywhere else? ``` module BattleShipGame open System let boardSize = 10 type Direction = Horz | Vert type ShipType = | AircraftCarrier | BattleShip | Frigate | Submarine | Minesweeper type Point(x : int, y : int) = struct member this.X = x member this.Y = y end type Ship(position : Point, shipType : ShipType, direction : Direction, hits : Point list) = member this.Position = position member this.Type = shipType member this.Direction = direction member this.Hits = hits member this.Length = match this.Type with | AircraftCarrier -> 5 | BattleShip -> 4 | Frigate | Submarine -> 3 | Minesweeper -> 2 member this.IsFinished = this.Hits.Length >= this.Length member this.HitTest(pos : Point) = let offset, dirValid = if this.Direction = Horz then pos.X - this.Position.X, pos.Y = this.Position.Y else pos.Y - this.Position.Y, pos.X = this.Position.X if not dirValid then false else offset >= 0 && offset List.tryFind (fun sh -> sh.IsFinished = false) ).IsNone member this.Print() = let shipHits = this.Ships |> List.collect (fun sh -> sh.Hits) printf "y\x" for x in 1 .. boardSize do printf " %d " x printfn "" for y in 1 .. boardSize do for x in 0 .. boardSize do let hit = shipHits |> List.tryFind (fun pt -> pt.X = x && pt.Y = y) if x = 0 && y > 0 then printf "%3d" y elif hit.IsSome then printf " X " else let pt = this.EnemyHits |> List.tryFind (fun pt -> pt.X = x && pt.Y = y)
- pattern minor 112d agoPython simple battleship gameI'm relatively new to Python, I decided to make a simple battleship game. Is there anything I should do to make it shorter, or in practice, "better"? ``` from pprint import pprint as pp import random Rows = 0 Columns = 0 turns = 0 Answer = "NaN" print("Welcome to battleship!") while (Rows > 10) or (Columns > 10) or (Rows Rows) or (GuessColumn Columns): #Warning if the guess is out of the board print("Outside the set grid. Please pick a number within it your Rows and Columns.") elif (grid[GuessRow-1][GuessColumn-1] == "X"): #If "X" is there than print that it missed print("You guessed that already.") else: #Updates the grid with an "X" saying that you missed the ship turns += 1 print("You missed the ship.") update_gridMiss(grid, GuessRow, GuessColumn) display_grid(grid, Columns) if (turns >= 5): print("Game over! You ran out of tries") ```
- pattern moderate 112d agoMaking a Battleship gameI'm making a Battleship game using python 2.7. However, how to make it is not currently my issue. The main aspect that I'm asking about is the style and method of making the code. Am I following best (or even good) practice? Are the comments too much, too little, unclear? If someone could give me some pointers based on my code on how to make it more readable and standard, it would be highly appreciated. ``` from random import randint # Adds the board to use as a list later board = [] # Numbering my rows and columns row_num = ["0", "1", "2", "3", "4"] # "0" string begins a space as the row numbering pushed in the output text. Could the space be better implemented in print board? columns = [" 0", "1", "2", "3", "4"] for x in range(5): board.append(["-"] * 5) # Function for making the board. Added tabs to make it more in the middle and clearer. def print_board(board): row_num = 0 print "\t\t", " ".join(columns) for row in board: print "\t\t", row_num, " ".join(row) row_num += 1 print "Let's play Battleship!" print_board(board) # Functions for playing agasint the computer def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) print "Would you like to play agasint the computer or against a friend?" # Choosing the location of the battleship and data validation of raw_input def game_type(game_input): global ship_row global ship_col if game_input == 1: ship_row = random_row(board) ship_col = random_col(board) elif game_input == 2: ship_row = int(raw_input("Choose a Row to place your battleship:")) ship_col = int(raw_input("Choose a Column to place your battleship:")) else: print "That is not a valid input. Please try again" game_type(int(raw_input("To play against the computer press 1, to play against a friend press 2: \n"))) game_type(int(raw_input("To play against the computer press
- pattern minor 112d agoDesigning a simple Battleship game in PythonI am trying to code Battleship. It should be a text one-player game against computer where computer and human player take turns in shooting at opponent's ships. I decided to start implementation with this part: A human types target coordinates and computer answers if a ship has been hit or even if it has been sunk. Ship positions are fixed (predefined in the program). For some time I wondered how to represent game plan and ships to get this working as smoothly as possible. This is what I have put together: ``` class GamePlan: DIMX = 10 DIMY = 10 SHIP_MISS = 0 SHIP_HIT = 1 SHIP_DEAD = 2 SHIP_COUNTS = { 2: 1, 3: 1, } def __init__(self): self.ships = [ [(1,1), (1,2)], [(5,6), (5,7), (5,8)], ] def hit(self, target): hit_ship = None hit_ship_index = None for i, ship in enumerate(self.ships): if target in ship: ship.pop(ship.index(target)) hit_ship = ship hit_ship_index = i if hit_ship == []: self.ships.pop(hit_ship_index) return self.SHIP_DEAD if hit_ship: return self.SHIP_HIT return self.SHIP_MISS def main(): game_plan = GamePlan() while True: raw_coords = raw_input('Enter coords: ') str_coords = raw_coords.split() coords = tuple([int(c) for c in str_coords]) if len(coords) != 2: print 'Bad input' continue result = game_plan.hit(coords) if result == GamePlan.SHIP_DEAD: print 'Ship dead' if result == GamePlan.SHIP_HIT: print 'Ship hit' if result == GamePlan.SHIP_MISS: print 'Missed' if __name__ == "__main__": main() ``` EDIT: `GamePlan` should be probably called `Board` as answer of Janne Karila suggests. Just to clarify what I meant by that name with my flawed English. There are a few things I a