Connect 4 Like Game - python-3.x

I am making a connect four like game in python, what I have so far is creating the board and implementing game play against the computer. I am running into the issue that does not allow me to play past the second row. Any ideas on why?
#Define the board
row = int(input("Please enter # of rows: ")) #User input Rows
column = int(input("Please enter # of columns: ")) #User input Columns
board = [] #empty board
space = ' '
p1 = 'x'
p2 = 'o'
#create board based on user input
for i in range(0,row):
board.append([])
for j in range(0, column):
board[i].append(space)
print(board)
#print board with character decorations
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
print(len(board))
while True:
#User input column
myC = int(input("Player 1, choose your column: "))
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][myC] == space:
i = i+1
board[x][myC] = 'x'
break
elif board[x][myC] == p1 or p2:
i = i+1
x = x - 1
print(x)
board[x][myC] = 'x'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
#Computer input column
from random import randint
theC = randint(0, len(board)-1)
print("Computer's Turn: Column " , theC)
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][theC] == space:
board[x][theC] = 'o'
i = i+1
break
elif board[x][theC] == p1 or p2:
i = i+1
x = x - 1
print(x)
board[x][theC] = 'o'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))

I believe I figured out what's going on. Your x is always initialized to len(board)-1 and then if the space is occupied it is reduced by one. If you make a (>2)x(>2) board and row 0 is occupied then this will always force x = 2.
This is close to correct, but what you actually need is to iterate through all rows until you find the first unoccupied row. I created a loop that will find the first row and assign that to the value of x. I tested it out and I'm now able to play passed 2 rows.
#Define the board
row = int(input("Please enter # of rows: ")) #User input Rows
column = int(input("Please enter # of columns: ")) #User input Columns
board = [] #empty board
space = ' '
p1 = 'x'
p2 = 'o'
#create board based on user input
for i in range(0,row):
board.append([])
for j in range(0, column):
board[i].append(space)
print(board)
#print board with character decorations
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
print(len(board))
while True:
#User input column
myC = int(input("Player 1, choose your column: "))
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][myC] == space:
i = i+1
board[x][myC] = 'x'
break
# Find last empty row for new piece
elif board[x][myC] == p1 or p2:
for j in range(x-1,-1,-1):
if board[j][myC] == space:
x = j
break
i = i+1
#x = x - 1
print(x)
board[x][myC] = 'x'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
#Computer input column
from random import randint
theC = randint(0, len(board)-1)
print("Computer's Turn: Column " , theC)
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][theC] == space:
board[x][theC] = 'o'
i = i+1
break
# Find last empty row for new piece
elif board[x][theC] == p1 or p2:
for j in range(x-1,-1,-1):
if board[j][theC] == space:
x =j
break
i = i+1
#x = x - 1
print(x)
board[x][theC] = 'o'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))

Related

How can I update my number in while loop? (Number guessing game)

I am going to write a guessing game with the computer.
I choose one number in my head and the Computer is going to find it out, and it can guess between a range.
The problem is I don’t know how can I update this range during the program run.
import random
x = 1
y = 99
guess= random.randint(x,y)
print(guess)
play='true'
while play=='true':
a=x
b=y
results = input()
if results == 'd':
play='false'
else:
if results == 'b':
a=guess
print('My number is bigger!')
newguess= random.randint(a,b)
print (newguess)
elif results == 'k':
b=guess
print('My number is smaller!')
newguess= random.randint(a,b)
print (newguess)
print ('Wooow , computer you did it! ')
Sorry about all the explanations in the code but this is a version of the game that I did a while ago. What I did was I wanted to shrink the guessing range each time the user said high or low. e.g. if the computer chooses 50, and the user says 'High' then the program will not chose a number greater than 50, the same applies for 'Low". Enjoy
import random
count = 0 #Number of attemps. how many times while loop runs.
guess = random.randint(1,100)#The guess generator
(l,u) = (0,100)
lower_guess = l
upper_guess = u
n = 0
print('Chose a number between ', l, ' and ', u , '.' )
#The game. These are outside the function so that they don't print in every loop because they are unwanted for some Y inputs.
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')#User states
#The function
while n != 'guess':
count +=1 #adds 1 to count each time loop runs
if Y == 'L':
lower_guess = guess+1
guess = random.randint(lower_guess , upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'H':
upper_guess = guess - 1
guess = random.randint(lower_guess, upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'Y':
print('I guessed it in ' + str(count) + ' attempts')
break
else:
count = 0
lower_guess = l
upper_guess = u
guess = random.randint(1,100)
print('That input was invalid. The game has restarted.')
print('You can chose a new number or keep your old one.')
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')

python accumulating while loop keeps repeating what did i do wrong?

I can't figure out what I am doing wrong. I have tried using a break, and tried setting what the variable !=, I am doing this on cengage and it is very finnicky.
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
while leftOrRight != "X":
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
your input() is outside the while loop, so leftOrRight never changes, never get to X so it will not exit the loop:
leftOrRight = None
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
According to your code you are not changing the value for leftOrRight after entering the loop so the condition for your while loop is never false I would suggest the following edit:
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = '' #anything random
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
so that you get a prompt every time the loop is executed and you can click X to exit
Your program just got the character that had the largest id in the ascii table.
And only doing the first string as the longString = max(n) wasn't even in the while loop.
also max returns the largest value, so in this case it was just converting the text into an ascii number.
instead you should use len(string) which returns the length of the string.
Unlike max() which is used like:
11 == max(11,10,1,2) as 11 is the largest character.
n = (input("Input: ")) #get initial input
longest = 0 #define the varible which we will keep the length of the longest string in
longest_str = "" #define the varible which stores the value of the longest string.
while n: #you don't need that other stuff, while n does the same as while n != ''
n = str(input("Input: ")) #get input
length = len(n) #gets the length of the input
if length > longest: #if the length of our input is larger than the last largest string
longest = length #set the longest length to current string length
longest_str = n #set the longest string to current string
#once the user hits enter (typing "") we exit the while loop, and this code runs afterwards.
print("Longest input was", longest_str, "at", longest, "characters long")
Because there are two specific counts we are accumulating for, and the outlying char is at the end of our input, we can set our while to True to break when we hit a char other that "L" or "R".
leftOrRight = ""
# Write your loop here.
while True:
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
if leftOrRight == "L":
leftTotal = leftTotal + 1
elif leftOrRight == "R":
rightTotal = rightTotal + 1
else:
break
# Output number of left or right-handed students.
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))

Caesar Cipher shift on new lines

I am having a problem with my code trying to do an advanced caesar cipher shift. I changed a certain letter to another, and then added a string to certain parts of a file before encoding, but am having problems doing the shifting now. This is my code:
import string
import sys
count = 1
cont_cipher = "Y"
#User inputs text
while cont_cipher == "Y":
if count == 1:
file = str(input("Enter input file:" ""))
k = str(input("Enter shift amount: "))
purpose = str(input("Encode (E) or Decode (D) ?: "))
#Steps to encode the message, replace words/letter then shift
if purpose == "E":
my_file = open(file, "r")
file_contents = my_file.read()
#change all "e"s to "zw"s
for letter in file_contents:
if letter == "e":
file_contents = file_contents.replace(letter, "zw")
#add "hokie" to beginning, middle, and end of each line
lines = file_contents.split('\n')
def middle_message(lines, position, word_to_insert):
lines = lines[:position] + word_to_insert + lines[position:]
return lines
new_lines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))]
#math to do the actual encryption
def caesar(word, shifts):
word_list = list(new_lines)
result = []
s = 0
for c in word_list:
next_ord = ord(c) + s + 2
if next_ord > 122:
next_ord = 97
result.append(chr(next_ord))
s = (s + 1) % shifts
return "".join(result)
if __name__ == "__main__":
print(caesar(my_file, 5))
#close file and add to count
my_file.close()
count = count + 1
The error I am getting is:
TypeError: ord() expected a character, but string of length 58 found
I know that I need to split it into individual characters, but am not sure how to do this. I need to use the updated message and not the original file in this step...

Why aren't the negative numbers being counted properly?

import time
total = 0
pos = 0
zeroes = 0
neg = 0
print('This program will add any seven numbers for you')
time.sleep(2)
print()
a = int(input('Please enter the first number: '))
total = total + a
if a > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
c = int(input('Please enter the third number: '))
total = total + c
if c > 0:
pos = pos + 1
elif c == 0:
zeroes = zeroes + 1
elif c < 0:
neg = neg + 1
time.sleep(2)
d = int(input('Please enter the fourth number: '))
total = total + d
if d > 0:
pos = pos + 1
elif d == 0:
zeroes = zeroes + 1
elif d < 0:
neg = neg + 1
time.sleep(2)
e = int(input('Please enter the fifth number: '))
total =total + e
if e > 0:
pos = pos + 1
elif e == 0:
zeroes = zeroes + 1
elif e < 0:
neg = neg + 1
time.sleep(2)
f = int(input('Please enter the sixth number: '))
total = total + f
if f > 0:
pos = pos + 1
elif f == 0:
zeroes = zeroes + 1
elif f < 0:
neg = neg + 1
time.sleep(2)
g = int(input('Please enter the seventh number: '))
total = total + g
if g > 0:
pos = pos + 1
elif g == 0:
zeroes = zeroes + 1
elif g < 0:
neg = neg + 1
time.sleep(2)
print()
print('The sum of your entries is: ', + total)
time.sleep(2)
print()
print('You entered', + pos, 'positive numbers')
time.sleep(2)
print()
print('You entered', + zeroes, 'zeroes')
time.sleep(2)
print()
print('You entered', + neg, 'negative numbers')
print()
time.sleep(3)
Hello! I have the variable 'neg' keeping a running total of all of the negative numbers that the user enters. It seems as if the negative numbers aren't always being added to the 'neg' running total at the end of the code.
I've been working with Python 3x for about a week now, so be gentle :)
Thanks in advance for the help!
Edit: I have reworked this into a (working) loop per the advice of Kevin, is this a good loop? It seems to work, I'm just looking for pointers as I'm kind of struggling with Python logic. Big thanks to Kevin, wish I could upvote you!
New code posted below:
import time
sums = 0
pos = 0
neg = 0
zero = 0
numb = 0
user_numb = 0
running = True
print('This program will add any 7 numbers for you')
time.sleep(.5)
print()
while running:
user_numb = int(input('Please enter a number: '))
sums = user_numb + sums
numb = numb + 1
print()
if user_numb > 0:
pos = pos + 1
elif user_numb < 0:
neg = neg + 1
elif user_numb == 0:
zero = zero + 1
if numb == 7:
running = False
print()
time.sleep(2)
print('The sum of the numbers entered was: ', + sums)
print()
time.sleep(2)
print('You entered', + pos, 'positive numbers')
print()
time.sleep(2)
print('You entered', + neg, 'negative numbers')
print()
time.sleep(2)
print('You entered', + zero, 'zeroes')
print()
print()
time.sleep(3)
In the section with b you forgot in the copy/pasted code to change all 'a' into 'b' and have still twice an 'a' there:
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0: # CHANGE TO 'b'
zeroes = zeroes + 1
elif a < 0: # CHANGE TO 'b'
neg = neg + 1
so you see wrong results only in case the second number is a 0 or negative.

Sort a user input list of numbers using python bubble sort

I've just started to learn python and I've decided to try and do a bubble sort. I've used the code below which works ok if the numbers to be sorted are 0 to 9. After that, it doesn't sort them correctly. I think, in my limited knowledge that this is because it is a 'list'.
I would like the user to be able to input the numbers but for the program to sort them regardless of the length of the number. Any help would be appreciated.
def bubble_sort(items):
changes=0
for i in range(len(items)):
for j in range(len(items)-1-i):#-i = optimised??
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j] # Swap
changes=changes+1
print(items)
print("Number of passes =",i)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers=input()
items=numbers.split()
Try this:
print('welcome to the automatic bubble sorter')
inputted_list = input('please enter a list of numbers seperated by commas: ')
list = inputted_list.split(',')
number_of_items = int(len(list))
sorting_method = input('if you would like your list to be sorted in ascending order, press 1, if you would like it to be sorted in descending order, press 2')
print(list)
if sorting_method == '1':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
counter2 = 0
permanent_numbers = []
while number_of_swaps > 0:
counter2 = counter2 + 1
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
permanent_numbers.append(list[number_of_items - counter2])
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
elif sorting_method == '2':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
while number_of_swaps > 0:
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
try map:
I suggested using map before, but I just remembered that map in python 3.x* yields a generator rather than a list, so that is why you cannot take the length of it. The updated answer is below
numbers = input("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
items = [int(num) for num in numbers.split()]
Modified existing code:
#!/usr/bin
def bubble_sort(items):
changes = passes = 0
last = len(items)
swapped = True
while swapped:
swapped = False
passes += 1
for j in range(1, last):
if items[j - 1] > items[j]:
items[j], items[j - 1] = items[j - 1], items[j] # Swap
changes += 1
swapped = True
last = j
print(items)
print("Number of passes =",passes)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers = input()
items = [int(num) for num in numbers.split() if num.isdigit()]
if items: bubble_sort(items)
def b_sort(list):
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx] > list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
str_input= input("Enter numbers: ")
list = [int(x) for x in str_input.split()]
b_sort(list)
print('sorted elements are: ')
print(list)
def sort():
try:
n = [1,8,6]
l = len(n)
print("Original list:", n)
for i in range(l - 1):
for j in range(0,l - i - 1):
if n[j] > n[j + 1]:
n[j], n[j + 1] = n[j + 1], n[j]
print("List after sorting is:", n)
except:
print("Error in inputing values")
sort()

Resources