Python Forum
Something the code dont work
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Something the code dont work
#11
I would modify ships to be ["S", 3, 1] for [marker, length, level]. I find that the code, especially in Python, looks better if you use data instead of code. Sure you could write a bunch of if staetments:
level = 0
if ship[1] > 2:
    level = 1
if ship[1] > 3:
    level = 2
if ship[1] > 4:
    level=3
But this looks better and is easier to modify if I want to change how the ships are placed.
level = ship[2]
You should look at named tuples. ship.length is much easier to understand than ship[1].

https://docs.python.org/3/library/collec...med-fields
from collections import namedtuple
from random import randint, choice

Ship = namedtuple("Ship", ["marker", "length", "level"])


def print_level(level):
    """Print a level"""
    print("   A B C D E F G H I J")
    for index, row in enumerate(level, start=1):
        print(f"""{index:>2} {" ".join(row)}""")
    print()


def make_level():
    """Make an empty 10 x 10 level."""
    return [["-"] * 10 for _ in range(10)]


def place_ship(ship, level):
    """Add ship to level"""
    # Keep trying to add the ship until we find a position where it fits.
    while True:
        x = randint(0, 9)
        y = randint(0, 9)
        dx, dy = (1, 0) if choice([True, False]) else (0, 1) # horizontal or vertical

        try:
            # Can we put the ship at x, y?
            for i in range(ship.length):
                if level[y + dy*i][x + dx*i] != '-':
                    raise IndexError()  # Collision with other ship

            # The ship fits.  Add it to the board.
            for i in range(ship.length):
                level[y + dy*i][x + dx*i] = ship.marker
            return
        except IndexError:
            pass


# Divide ships among boards
board = [make_level() for _ in range(3)]
ships = (Ship("D", 2, 0), Ship("C", 3, 1), Ship("S", 3, 1), Ship("B", 4, 2), Ship("A", 5, 2))
for ship in ships:
    place_ship(ship, board[ship.level])
for level in board:
    print_level(level)

# Put all the ships on the same board
board = make_level()
ships = (Ship("A", 5, 0), Ship("B", 4, 0), Ship("S", 3, 0), Ship("C", 3, 0), Ship("D", 2, 0))
for ship in ships:
    place_ship(ship, board)
print_level(board)
AlexPython likes this post
Reply
#12
(Oct-17-2022, 06:09 PM)deanhystad Wrote: I would modify ships to be ["S", 3, 1] for [marker, length, level]. I find that the code, especially in Python, looks better if you data instead of code. Sure you could write a bunch of if staetments:
level = 0
if ship[1] > 2:
    level = 1
if ship[1] > 3:
    level = 2
if ship[1] > 4:
    level=3
But this looks better and is easier to modify if I want to change how the ships are placed,
level = ship[2]
You should look at named tuples. ship.length is much easier to understand than ship[1].

https://docs.python.org/3/library/collec...med-fields
from collections import namedtuple
from random import randint, choice

Ship = namedtuple("Ship", ["marker", "length", "level"])


def print_level(level):
    """Print a level"""
    print("   A B C D E F G H I J")
    for index, row in enumerate(level, start=1):
        print(f"""{index:>2} {" ".join(row)}""")
    print()


def make_level():
    """Make an empty 10 x 10 level."""
    return [["-"] * 10 for _ in range(10)]


def place_ship(ship, level):
    """Add ship to level"""
    # Keep trying to add the ship until we find a position where it fits.
    while True:
        x = randint(0, 9)
        y = randint(0, 9)
        dx, dy = (1, 0) if choice([True, False]) else (0, 1) # horizontal or vertical

        try:
            # Can we put the ship at x, y?
            for i in range(ship.length):
                if level[y + dy*i][x + dx*i] != '-':
                    raise IndexError()  # Collision with other ship

            # The ship fits.  Add it to the board.
            for i in range(ship.length):
                level[y + dy*i][x + dx*i] = ship.marker
            return
        except IndexError:
            pass


# Divide ships among boards
board = [make_level() for _ in range(3)]
ships = (Ship("D", 2, 0), Ship("C", 3, 1), Ship("S", 3, 1), Ship("B", 4, 2), Ship("A", 5, 2))
for ship in ships:
    place_ship(ship, board[ship.level])
for level in board:
    print_level(level)

# Put all the ships on the same board
board = make_level()
ships = (Ship("A", 5, 0), Ship("B", 4, 0), Ship("S", 3, 0), Ship("C", 3, 0), Ship("D", 2, 0))
for ship in ships:
    place_ship(ship, board)
print_level(board)

Thank you so much dude. You are like a cheat code for this stuff Big Grin
Reply
#13
That's not a compliment. If you aren't learning something I'm doing you no favor.
Reply
#14
(Oct-17-2022, 06:19 PM)deanhystad Wrote: That's not a compliment. If you aren't learning something I'm doing you no favor.

I say that in a good way. You explain everything, so if I'm not learning that's on me, not you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  hi need help to make this code work correctly atulkul1985 5 702 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 626 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Beginner: Code not work when longer list raiviscoding 2 765 May-19-2023, 11:19 AM
Last Post: deanhystad
  Why doesn't this code work? What is wrong with path? Melcu54 7 1,681 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  Code used to work 100%, now sometimes works! muzicman0 5 1,383 Jan-13-2023, 05:09 PM
Last Post: muzicman0
  color code doesn't work harryvl 1 842 Dec-29-2022, 08:59 PM
Last Post: deanhystad
  I dont know why my function won't work? MehHz2526 3 1,150 Nov-28-2022, 09:32 PM
Last Post: deanhystad
  cannot get code to work Led_Zeppelin 10 2,312 Jun-30-2022, 06:28 PM
Last Post: deanhystad
  why I dont get any output from this code William369 2 1,084 Jun-23-2022, 09:18 PM
Last Post: William369
  How does this code work? pd_minh12 3 1,295 Apr-15-2022, 02:50 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020