jeudi 28 mai 2015

Why isn't Pythons randint Function actually Random?

I've been coding in python for awhile, and I happened to stumble upon Codecademys exercises and one of the projects was to create a battleship game that randomely places a 2x1 battle ship in a 5x5 grid. I noticed a pattern after my girlfriend correctly guess where the ship was 3 times in a row. the randint for the col and randint for the row started at 0,1. then the program termintates. After launching the program again the answer was 1,2. the next three answers were 2,3 , 3,4 , 4,0. Why does this happen instead of truely being random?

Code is below:

import os, sys
from random import randint
os.system("cls")
board = []
for x in range(0, 5):
    board.append(["O"] * 5)
def print_board(board):
    for row in board:
        print " ".join(row)
print_board(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)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Write your code below!
while guess_row!=ship_row and guess_col!=ship_col:
    print"You missed my battleship!"
    for i in range(len(board)):
        if i==guess_col:
            board[guess_row][i]="X"
    print_board(board)
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))
print"Congratulations! You sank my Battleship!"




Aucun commentaire:

Enregistrer un commentaire