Game neustarten im battleship Game
Verfasst: Freitag 2. Oktober 2020, 13:04
Ich brauche Hilfe mit meinem Code. Sobald man das Schiff im Feld gefunden hat und noch weiterspielen will, wird das vorherige Feld wieder ausgedruckt (Das mit den Sternen und dem X, das Schiff behält auch die gleiche Position). Ich will aber, dass ein komplett neues Feld ausgedruckt wird, sodass das Schiff eine neue Position bekommt und die Sterne und das X entfernt wird.
Code: Alles auswählen
from random import randint
NUM_SHIPS = 4
def createBoard(x,y):
board = []
for i in range(y):
row = []
for j in range(x):
row.append("O")
board.append(row)
return board
def printBoard(board):
numbers = []
for i in range(1,len(board[0])+ 1 ):
numbers.append(str(i))
print(" ", " ".join(numbers))
counter = 1
for row in board:
print(str(counter)," ".join(row))
counter +=1
#Spiel anfangen
def main():
Points = 0
name_player = input("Wie heisst du?: ")
print("Ok, los gehts", name_player, "!")
board = createBoard(9, 9)
printBoard(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
#Spiel entgültig starten
for turn in range(40):
try:
row_guess = int(input("Rate die Reihe (1-9): "))-1
if row_guess in range(len(board)):
pass
except ValueError:
print("Bitte eine Nummer eingeben: ")
try:
col_guess = int(input("Rate die Kolone (1-9): "))-1
if col_guess not in range(len(board)):
pass
except ValueError:
print("Bitte eine Nummer eingeben: ")
#Wenn Spieler das richtige Feld getroffen hat
if ship_row == row_guess and ship_col == col_guess:
board[row_guess][col_guess] = "X"
print("Glückwunsch, du hast das Battleship gesenkt! ")
Points += 1
print("Du hast", Points , "Punkte")
restart = input("Willst du nochmal spielen ?: ")
if restart == "ja" or "Ja":
main()
elif restart == "Nein" or "nein":
print("Du hattest", Points, "Punkte\nGame Over")
__name__ == '__main__'
# den spieler warnen falls er ausserhalb des Spielfeldes geraten hat
else:
if (row_guess < 0 or row_guess > 9 ) or (col_guess < 0 or col_guess > 9):
print("Oops, das ist leider nicht im Spielfeld.")
# warnen falls gleich geraten wurde wie vorher
elif board[row_guess][col_guess] == "*":
print("Da hast du schonmal geraten.")
#Wenn die Rate falsch ist, dann das Feld mit * markieren
else:
print("Du hast nicht getrofen!")
board[row_guess][row_guess] = "*"
#Turn und board nochmals hier ausdrucken nach jeder Rate
print("Runde", str(turn + 1 ), "von 40.")
printBoard(board)
#Spiel beenden
if __name__ == '__main__' :
main()