Battleship Game.. a few issues with database and storing players Data












-2















I am trying to create a game of battleship in python that has the following:




  • an SQLite database

  • a user login and password, games won and highscore stored in the db

  • display games won and highscore on login


So far I am having issues with storing the data in the database if anyone has any help or guidance on what direction I should go next I would greatly appreciate it!



from random import randint
import getpass
import sqlite3

#creating the database using SQLite
def createTable():
db = sqlite3.connect(':memory:')
db = sqlite3.connect('MyBSdb') #this folder was created
cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS BSTable(name TEXT, password TEXT, wins INT, highscore INT)''')
db.commit()
db.close()

def save(name,password):
db = sqlite3.connect(':memory:')
db = sqlite3.connect('MyBSdb')
cursor = db.cursor()
cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?)''', (name,password,wins,highscore))
db.commit()
db.close()

def get():
db = sqlite3.connect(':memory:')
db = sqlite3.connect('MyBSdb')
cursor = db.cursor()
cursor.execute('''SELECT name,password,wins,highscore from myTable''')
results = cursor.fetchall()
for result in results:
print (result)


if __name__ == '__main__':
createTable()
save('users','passw')
get()

def writeFile():
#create file handle, open file for append
file = open('Battleship.txt', 'a')
text = 'Bob,hello'
#write string s to file
file.write(text + 'n')
#close file handle after write operation
file.close()

def readFile():
#create file handle, open file for append
file = open('Battleship.txt', 'r')
text = file.readlines()
for line in text:
print(line.split(",")[0])
print(line.split(",")[1])
#close file handle after write operation
file.close()

if __name__ == '__main__':
writeFile()
readFile()

#creating a login and password
users = {}
status = ""

def displayMenu():
status = input("Are you registered user? y/n? ")
if status == "y":
oldUser()
elif status == "n":
newUser()

def newUser():
createLogin = input("Create login name: ")

if createLogin in users:
print("nLogin name already exist!n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw
print("nUser createdn")

def oldUser():
login = input("Enter login name: ")
passw = input("Enter password: ")

if login in users and users[login] == passw:
print("nLogin successful!n")
else:
print("nUser doesn't exist or wrong password!n")

while status != "q":
displayMenu() #cant stop the loop here or figure out why it wont move on

#building the gameboard
board =

for x in range(5):
board.append(["-"] * 5)

def print_board(board):
print(" ", " ".join("12345"))
for letter, row in zip("ABCDE", board):
print(letter, " ".join(row))

#beginning the game
print("Let's play Battleship!")
print("Find and sink the ship!")
print_board(board)

score = 0 #using this to keep a score to store in the database
win = True

def wins():
if win == True:
win = score + 1

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)

#the numbers and letters in this section are not aligning with the grid I created
for turn in range(9):
print ("Turn"), turn
guess_row = int(input("Guess Row:"))
guess_col = int(
input("Guess Col:"))

if guess_row == ship_row and guess_col == ship_col:
win == True
print("Congratulations! You sunk my battleship!")
print("Your score is " + score ) #keeping score but how to save in db?
break
else:
if (guess_row < 0 or guess_row > 5) or (guess_col < 0 or guess_col > 5):
print("Oops, that's not even in the ocean.")
elif(board[guess_row][guess_col] == "X"):
print("You guessed that one already.")
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
if turn == 8:
print("Game Over")
print("Your final score is " + score )
turn =+ 1
print_board(board)
#how to display games won and high score when user logs in?









share|improve this question



























    -2















    I am trying to create a game of battleship in python that has the following:




    • an SQLite database

    • a user login and password, games won and highscore stored in the db

    • display games won and highscore on login


    So far I am having issues with storing the data in the database if anyone has any help or guidance on what direction I should go next I would greatly appreciate it!



    from random import randint
    import getpass
    import sqlite3

    #creating the database using SQLite
    def createTable():
    db = sqlite3.connect(':memory:')
    db = sqlite3.connect('MyBSdb') #this folder was created
    cursor = db.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS BSTable(name TEXT, password TEXT, wins INT, highscore INT)''')
    db.commit()
    db.close()

    def save(name,password):
    db = sqlite3.connect(':memory:')
    db = sqlite3.connect('MyBSdb')
    cursor = db.cursor()
    cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?)''', (name,password,wins,highscore))
    db.commit()
    db.close()

    def get():
    db = sqlite3.connect(':memory:')
    db = sqlite3.connect('MyBSdb')
    cursor = db.cursor()
    cursor.execute('''SELECT name,password,wins,highscore from myTable''')
    results = cursor.fetchall()
    for result in results:
    print (result)


    if __name__ == '__main__':
    createTable()
    save('users','passw')
    get()

    def writeFile():
    #create file handle, open file for append
    file = open('Battleship.txt', 'a')
    text = 'Bob,hello'
    #write string s to file
    file.write(text + 'n')
    #close file handle after write operation
    file.close()

    def readFile():
    #create file handle, open file for append
    file = open('Battleship.txt', 'r')
    text = file.readlines()
    for line in text:
    print(line.split(",")[0])
    print(line.split(",")[1])
    #close file handle after write operation
    file.close()

    if __name__ == '__main__':
    writeFile()
    readFile()

    #creating a login and password
    users = {}
    status = ""

    def displayMenu():
    status = input("Are you registered user? y/n? ")
    if status == "y":
    oldUser()
    elif status == "n":
    newUser()

    def newUser():
    createLogin = input("Create login name: ")

    if createLogin in users:
    print("nLogin name already exist!n")
    else:
    createPassw = input("Create password: ")
    users[createLogin] = createPassw
    print("nUser createdn")

    def oldUser():
    login = input("Enter login name: ")
    passw = input("Enter password: ")

    if login in users and users[login] == passw:
    print("nLogin successful!n")
    else:
    print("nUser doesn't exist or wrong password!n")

    while status != "q":
    displayMenu() #cant stop the loop here or figure out why it wont move on

    #building the gameboard
    board =

    for x in range(5):
    board.append(["-"] * 5)

    def print_board(board):
    print(" ", " ".join("12345"))
    for letter, row in zip("ABCDE", board):
    print(letter, " ".join(row))

    #beginning the game
    print("Let's play Battleship!")
    print("Find and sink the ship!")
    print_board(board)

    score = 0 #using this to keep a score to store in the database
    win = True

    def wins():
    if win == True:
    win = score + 1

    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)

    #the numbers and letters in this section are not aligning with the grid I created
    for turn in range(9):
    print ("Turn"), turn
    guess_row = int(input("Guess Row:"))
    guess_col = int(
    input("Guess Col:"))

    if guess_row == ship_row and guess_col == ship_col:
    win == True
    print("Congratulations! You sunk my battleship!")
    print("Your score is " + score ) #keeping score but how to save in db?
    break
    else:
    if (guess_row < 0 or guess_row > 5) or (guess_col < 0 or guess_col > 5):
    print("Oops, that's not even in the ocean.")
    elif(board[guess_row][guess_col] == "X"):
    print("You guessed that one already.")
    else:
    print("You missed my battleship!")
    board[guess_row][guess_col] = "X"
    if turn == 8:
    print("Game Over")
    print("Your final score is " + score )
    turn =+ 1
    print_board(board)
    #how to display games won and high score when user logs in?









    share|improve this question

























      -2












      -2








      -2








      I am trying to create a game of battleship in python that has the following:




      • an SQLite database

      • a user login and password, games won and highscore stored in the db

      • display games won and highscore on login


      So far I am having issues with storing the data in the database if anyone has any help or guidance on what direction I should go next I would greatly appreciate it!



      from random import randint
      import getpass
      import sqlite3

      #creating the database using SQLite
      def createTable():
      db = sqlite3.connect(':memory:')
      db = sqlite3.connect('MyBSdb') #this folder was created
      cursor = db.cursor()
      cursor.execute('''CREATE TABLE IF NOT EXISTS BSTable(name TEXT, password TEXT, wins INT, highscore INT)''')
      db.commit()
      db.close()

      def save(name,password):
      db = sqlite3.connect(':memory:')
      db = sqlite3.connect('MyBSdb')
      cursor = db.cursor()
      cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?)''', (name,password,wins,highscore))
      db.commit()
      db.close()

      def get():
      db = sqlite3.connect(':memory:')
      db = sqlite3.connect('MyBSdb')
      cursor = db.cursor()
      cursor.execute('''SELECT name,password,wins,highscore from myTable''')
      results = cursor.fetchall()
      for result in results:
      print (result)


      if __name__ == '__main__':
      createTable()
      save('users','passw')
      get()

      def writeFile():
      #create file handle, open file for append
      file = open('Battleship.txt', 'a')
      text = 'Bob,hello'
      #write string s to file
      file.write(text + 'n')
      #close file handle after write operation
      file.close()

      def readFile():
      #create file handle, open file for append
      file = open('Battleship.txt', 'r')
      text = file.readlines()
      for line in text:
      print(line.split(",")[0])
      print(line.split(",")[1])
      #close file handle after write operation
      file.close()

      if __name__ == '__main__':
      writeFile()
      readFile()

      #creating a login and password
      users = {}
      status = ""

      def displayMenu():
      status = input("Are you registered user? y/n? ")
      if status == "y":
      oldUser()
      elif status == "n":
      newUser()

      def newUser():
      createLogin = input("Create login name: ")

      if createLogin in users:
      print("nLogin name already exist!n")
      else:
      createPassw = input("Create password: ")
      users[createLogin] = createPassw
      print("nUser createdn")

      def oldUser():
      login = input("Enter login name: ")
      passw = input("Enter password: ")

      if login in users and users[login] == passw:
      print("nLogin successful!n")
      else:
      print("nUser doesn't exist or wrong password!n")

      while status != "q":
      displayMenu() #cant stop the loop here or figure out why it wont move on

      #building the gameboard
      board =

      for x in range(5):
      board.append(["-"] * 5)

      def print_board(board):
      print(" ", " ".join("12345"))
      for letter, row in zip("ABCDE", board):
      print(letter, " ".join(row))

      #beginning the game
      print("Let's play Battleship!")
      print("Find and sink the ship!")
      print_board(board)

      score = 0 #using this to keep a score to store in the database
      win = True

      def wins():
      if win == True:
      win = score + 1

      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)

      #the numbers and letters in this section are not aligning with the grid I created
      for turn in range(9):
      print ("Turn"), turn
      guess_row = int(input("Guess Row:"))
      guess_col = int(
      input("Guess Col:"))

      if guess_row == ship_row and guess_col == ship_col:
      win == True
      print("Congratulations! You sunk my battleship!")
      print("Your score is " + score ) #keeping score but how to save in db?
      break
      else:
      if (guess_row < 0 or guess_row > 5) or (guess_col < 0 or guess_col > 5):
      print("Oops, that's not even in the ocean.")
      elif(board[guess_row][guess_col] == "X"):
      print("You guessed that one already.")
      else:
      print("You missed my battleship!")
      board[guess_row][guess_col] = "X"
      if turn == 8:
      print("Game Over")
      print("Your final score is " + score )
      turn =+ 1
      print_board(board)
      #how to display games won and high score when user logs in?









      share|improve this question














      I am trying to create a game of battleship in python that has the following:




      • an SQLite database

      • a user login and password, games won and highscore stored in the db

      • display games won and highscore on login


      So far I am having issues with storing the data in the database if anyone has any help or guidance on what direction I should go next I would greatly appreciate it!



      from random import randint
      import getpass
      import sqlite3

      #creating the database using SQLite
      def createTable():
      db = sqlite3.connect(':memory:')
      db = sqlite3.connect('MyBSdb') #this folder was created
      cursor = db.cursor()
      cursor.execute('''CREATE TABLE IF NOT EXISTS BSTable(name TEXT, password TEXT, wins INT, highscore INT)''')
      db.commit()
      db.close()

      def save(name,password):
      db = sqlite3.connect(':memory:')
      db = sqlite3.connect('MyBSdb')
      cursor = db.cursor()
      cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?)''', (name,password,wins,highscore))
      db.commit()
      db.close()

      def get():
      db = sqlite3.connect(':memory:')
      db = sqlite3.connect('MyBSdb')
      cursor = db.cursor()
      cursor.execute('''SELECT name,password,wins,highscore from myTable''')
      results = cursor.fetchall()
      for result in results:
      print (result)


      if __name__ == '__main__':
      createTable()
      save('users','passw')
      get()

      def writeFile():
      #create file handle, open file for append
      file = open('Battleship.txt', 'a')
      text = 'Bob,hello'
      #write string s to file
      file.write(text + 'n')
      #close file handle after write operation
      file.close()

      def readFile():
      #create file handle, open file for append
      file = open('Battleship.txt', 'r')
      text = file.readlines()
      for line in text:
      print(line.split(",")[0])
      print(line.split(",")[1])
      #close file handle after write operation
      file.close()

      if __name__ == '__main__':
      writeFile()
      readFile()

      #creating a login and password
      users = {}
      status = ""

      def displayMenu():
      status = input("Are you registered user? y/n? ")
      if status == "y":
      oldUser()
      elif status == "n":
      newUser()

      def newUser():
      createLogin = input("Create login name: ")

      if createLogin in users:
      print("nLogin name already exist!n")
      else:
      createPassw = input("Create password: ")
      users[createLogin] = createPassw
      print("nUser createdn")

      def oldUser():
      login = input("Enter login name: ")
      passw = input("Enter password: ")

      if login in users and users[login] == passw:
      print("nLogin successful!n")
      else:
      print("nUser doesn't exist or wrong password!n")

      while status != "q":
      displayMenu() #cant stop the loop here or figure out why it wont move on

      #building the gameboard
      board =

      for x in range(5):
      board.append(["-"] * 5)

      def print_board(board):
      print(" ", " ".join("12345"))
      for letter, row in zip("ABCDE", board):
      print(letter, " ".join(row))

      #beginning the game
      print("Let's play Battleship!")
      print("Find and sink the ship!")
      print_board(board)

      score = 0 #using this to keep a score to store in the database
      win = True

      def wins():
      if win == True:
      win = score + 1

      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)

      #the numbers and letters in this section are not aligning with the grid I created
      for turn in range(9):
      print ("Turn"), turn
      guess_row = int(input("Guess Row:"))
      guess_col = int(
      input("Guess Col:"))

      if guess_row == ship_row and guess_col == ship_col:
      win == True
      print("Congratulations! You sunk my battleship!")
      print("Your score is " + score ) #keeping score but how to save in db?
      break
      else:
      if (guess_row < 0 or guess_row > 5) or (guess_col < 0 or guess_col > 5):
      print("Oops, that's not even in the ocean.")
      elif(board[guess_row][guess_col] == "X"):
      print("You guessed that one already.")
      else:
      print("You missed my battleship!")
      board[guess_row][guess_col] = "X"
      if turn == 8:
      print("Game Over")
      print("Your final score is " + score )
      turn =+ 1
      print_board(board)
      #how to display games won and high score when user logs in?






      python database sqlite sqlite3






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '18 at 18:01









      Aoife Ellen RyanAoife Ellen Ryan

      63




      63
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I believe that your issue is that the number of values to parse is 2 whilst you give 4 values and expect 4 values for the 4 columns.



          Try using :-



          cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?,?,?)''', (name,password,wins,highscore))





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53451184%2fbattleship-game-a-few-issues-with-database-and-storing-players-data%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I believe that your issue is that the number of values to parse is 2 whilst you give 4 values and expect 4 values for the 4 columns.



            Try using :-



            cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?,?,?)''', (name,password,wins,highscore))





            share|improve this answer




























              0














              I believe that your issue is that the number of values to parse is 2 whilst you give 4 values and expect 4 values for the 4 columns.



              Try using :-



              cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?,?,?)''', (name,password,wins,highscore))





              share|improve this answer


























                0












                0








                0







                I believe that your issue is that the number of values to parse is 2 whilst you give 4 values and expect 4 values for the 4 columns.



                Try using :-



                cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?,?,?)''', (name,password,wins,highscore))





                share|improve this answer













                I believe that your issue is that the number of values to parse is 2 whilst you give 4 values and expect 4 values for the 4 columns.



                Try using :-



                cursor.execute('''INSERT INTO BSTable(name,password,wins,highscore) values(?,?,?,?)''', (name,password,wins,highscore))






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 20:49









                MikeTMikeT

                16.2k112642




                16.2k112642
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53451184%2fbattleship-game-a-few-issues-with-database-and-storing-players-data%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    TypeError: fit_transform() missing 1 required positional argument: 'X'