8 Replies - 503 Views - Last Post: 11 February 2014 - 04:56 PM Rate Topic: -----

#1 J-Whit  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 05-February 14

Battleship

Posted 09 February 2014 - 06:18 PM

Hello,
So I would like to create a battleship program with Python. I have some of it finished already but I would like to create a nice graphical interface for it. This would show the user the board and they would be able to select a grid. I was wondering if anyone could recommend a good library for this. It will be in Python 3.
Here is what I have so far by the way.

import random

board = []

for x in range(0,5):

        board.append(["O"] * 5)

def print_board(board):

        for row in board:

                print (" ".join(row))

print ("Let's play Battleship!")

print_board(board)

def random_row(board):

        return random.randint(0,len(board)-1)

def random_col(board):

        return random.randint(0,len(board[0])-1)



ship_row = random_row(board)

ship_col = random_col(board)

print (ship_row)

print (ship_col)

for turn in range(4):

guess_row = int(input("Guess Row:"))

        guess_col = int(input("Guess Col:"))

if guess_row == ship_row and guess_col == ship_col:

                print ("Congratulations! You sunk my battleship!")

                break

        else:



                if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):

                        print ("Oops, that's not even in the ocean.")

                elif (board[guess_row] and board[guess_col] == "X"):

                        print ("You guessed that one already.")

                else:

                        print ("You missed my battleship!")

   board[guess_row][guess_col] = "X"



                        if turn == 4:

                                print ("Game Over")

                        else:
                                continue



        print (turn + 1)

print_board(board)



Is This A Good Question/Topic? 0
  • +

Replies To: Battleship

#2 project21124  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 34
  • Joined: 02-February 14

Re: Battleship

Posted 09 February 2014 - 09:44 PM

Pygame Pygame Pygame.
You can see part of a program I'm making currently to see about what it looks like. http://www.dreaminco...sition-of-rect/
I'm still learning too, but this should give you an idea of the kind of code you use for it.
I've heard of using turtle as well, but I have no personal experience.
Here's some links:
http://www.pygame.org/wiki/about
Turtle may be TOO basic though...
http://pythonturtle.org/
Was This Post Helpful? 1
  • +
  • -

#3 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 86
  • View blog
  • Posts: 538
  • Joined: 26-June 13

Re: Battleship

Posted 10 February 2014 - 01:03 AM

You should try implementing this using OOP.
Was This Post Helpful? 1
  • +
  • -

#4 project21124  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 34
  • Joined: 02-February 14

Re: Battleship

Posted 10 February 2014 - 09:59 AM

View Postsalazar, on 10 February 2014 - 08:03 AM, said:

You should try implementing this using OOP.

That's not important for him now, seeing stuff on the screen is important to him right now.
While he SHOULD be using OOP, he shouldn't start until he's ready, and can see stuff on the screen.
Was This Post Helpful? 0
  • +
  • -

#5 Black_Epiphany  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 60
  • Joined: 02-February 14

Re: Battleship

Posted 10 February 2014 - 07:23 PM

View Postproject21124, on 10 February 2014 - 04:59 PM, said:

View Postsalazar, on 10 February 2014 - 08:03 AM, said:

You should try implementing this using OOP.

That's not important for him now, seeing stuff on the screen is important to him right now.
While he SHOULD be using OOP, he shouldn't start until he's ready, and can see stuff on the screen.


In my opinion, it's more important to get basic OOP concepts down before trying to make a game with a GUI. Helps a lot.
Was This Post Helpful? 2
  • +
  • -

#6 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7291
  • View blog
  • Posts: 12,093
  • Joined: 19-March 11

Re: Battleship

Posted 10 February 2014 - 08:42 PM

View Postsalazar, on 10 February 2014 - 03:03 AM, said:

You should try implementing this using OOP.



I agree with this. GUI programming is a major use case for OO programming. The big-blob-o-code architecture works for a while, but when you start trying to bring it to the gui, the pain begins in earnest. It will definitely make your life easier if you simplify things with an OO approach before attempting to create a GUI for this.

View Postproject21124, on 10 February 2014 - 11:59 AM, said:

That's not important for him now, seeing stuff on the screen is important to him right now.
While he SHOULD be using OOP, he shouldn't start until he's ready, and can see stuff on the screen.


If you're ready to start writing a GUI, and you're not ready to deal with objects, you're not ready to start writing a GUI.
Was This Post Helpful? 4
  • +
  • -

#7 project21124  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 34
  • Joined: 02-February 14

Re: Battleship

Posted 11 February 2014 - 09:46 AM

View Postjon.kiparsky, on 11 February 2014 - 03:42 AM, said:

View Postproject21124, on 10 February 2014 - 11:59 AM, said:

That's not important for him now, seeing stuff on the screen is important to him right now.
While he SHOULD be using OOP, he shouldn't start until he's ready, and can see stuff on the screen.


If you're ready to start writing a GUI, and you're not ready to deal with objects, you're not ready to start writing a GUI.

Alright, I'm quite new to this as well, so I'll take your word for it.

This post has been edited by andrewsw: 11 February 2014 - 04:58 PM
Reason for edit:: Reduced quote

Was This Post Helpful? 0
  • +
  • -

#8 woooee  Icon User is offline

  • D.I.C Head

Reputation: 15
  • View blog
  • Posts: 66
  • Joined: 21-November 12

Re: Battleship

Posted 11 February 2014 - 04:45 PM

Typically, a group of buttons is used which you can click individually. This example uses a class, since that is the way that I do it and am not willing to try to cram it into something unstructured. It also uses a dictionary to keep track of where the ships are located. Note that it is a simple example of a GUI and does not exit the game when the Battleship is sunk, or when all ships are sunk. Nor does it limit the number of moves or display a message when a button is pushed more than once. That is left to anyone else who wants to use this. There are many Tkinter tutorials like http://tkinter.unpyt.../wiki/FrontPage
and http://tkinter.unpyt.../Widgets/Button for button callbacks.
try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

import random
from functools import partial

class Battleship():
    def __init__(self):
        self.top = tk.Tk()
        self.initial_board()
        self.add_ships()
        self.top.mainloop()

    def add_ships(self):
        """ add ships to a random square number
            use random.shuffle as randint can return the same number
            when called multiple times

            add location to a dictionary whose key is the 
            button number pointing to the description
        """
        choices = range(25)
        random.shuffle(choices)
        self.locations_dict={}
        for ctr, lit in enumerate(("Battleship", "Destroyer", "Row Boat")):
            key=choices[ctr]
            self.locations_dict[key]=lit
            print lit, key     ## for testing

    def button_pushed(self, button_num):
        self.buttons_list[button_num].config(bg="lightgray")
        if button_num in self.locations_dict:
            self.description.set("You sunk my "+self.locations_dict[button_num])
        else:
            self.description.set("You hit nothing")

    def initial_board(self):
        """  25 buttons numbered 0-->24
             each button object saved in the list, buttons_list
             creates a 5X5 matrix of buttons
        """
        self.buttons_list = []
        but_num=0
        for row_num in range(5):
            for col_num in range(5):
                b=tk.Button(self.top, text=str(but_num),
                            bg="white", width=3, 
                            command=partial(self.button_pushed, but_num))
                self.buttons_list.append(B)/>#editor adds crap here
                ##              should be append(lower case B)/>
                b.grid(row=row_num, column=col_num)
                but_num += 1

        ## label to say what has happened
        self.description = tk.StringVar()
        tk.Label(self.top, textvariable=self.description,
                 fg="red").grid(row=9, column=0,
                 columnspan=5, sticky="ew")

        ## exit button
        tk.Button(text="Exit", bg="yellow",
                  command=self.top.quit).grid(row=10, column=1,
                  columnspan=3, sticky="ew")

BS=Battleship() 

This post has been edited by woooee: 11 February 2014 - 04:59 PM

Was This Post Helpful? 1
  • +
  • -

#9 J-Whit  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 05-February 14

Re: Battleship

Posted 11 February 2014 - 04:56 PM

Thank you all for the quick responses. I will improve my code with OOP and hope to make a more structured program by doing this. I will definately look into pygame and tkinter. Thank you again everyone.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1