Skip to content

Commit 3f469db

Browse files
committed
Added games (Python)
0 parents  commit 3f469db

File tree

5 files changed

+206
-0
lines changed

5 files changed

+206
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Use python to create mini games

rock&paper.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import random
2+
3+
def play():
4+
try:
5+
user = int(input("What's your choice? \n (1) Rock \n (2) Paper \n (3) Scissor \n" ))
6+
except ValueError as ve:
7+
print(ve)
8+
computer = random.randint(1, 3)
9+
print("Your opponent chose " + str(computer))
10+
11+
if user == computer:
12+
return 'Tie!'
13+
14+
"""
15+
(1)Rock
16+
(2)Paper
17+
(3)Scissor
18+
1 > 3, 2 > 1, 3 > 2
19+
"""
20+
if win(user, computer):
21+
return 'You Won!'
22+
23+
return 'You lost!'
24+
25+
def win(player1, player2):
26+
"""
27+
(1)Rock
28+
(2)Paper
29+
(3)Scissor
30+
1 > 3, 2 > 1, 3 > 2
31+
"""
32+
if(player1 == 1 and player2 == 3) or (player1 == 2 and player2 == 1) \
33+
or (player1 == 3 and player2 == 2):
34+
return True
35+
36+
print(play())
1.64 KB
Binary file not shown.

ticktactoe/game.py

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
from players import HumanPlayer, RandomComPlayer
2+
3+
4+
class TicTacToe:
5+
def __init__(self):
6+
7+
# use * to represent empty slot (3 x 3)
8+
self.board = ['*','*','*',
9+
'*','*','*',
10+
'*','*','*',]
11+
12+
# keep track of winner
13+
self.currentWinner = None
14+
15+
def printBoard(self):
16+
for row in [self.board[i*3: (i+1)*3] for i in range(3)]:
17+
print('| ' + ' |' .join(row) + ' |')
18+
19+
@staticmethod
20+
def printBoardNum():
21+
numberBoard = [[str(i) for i in range(j*3, (j+1)*3)] for j in range(3)]
22+
for row in numberBoard:
23+
print('| ' + ' |' .join(row) + ' |')
24+
25+
def availalbeMoves(self):
26+
return [i for i, spot in enumerate(self.board) if spot == '*']
27+
"""
28+
moves = []
29+
for (i, spot) in enumerate(self.board):
30+
if spot == '*':
31+
moves.append(i)
32+
return moves
33+
"""
34+
def emptySquares(self):
35+
return '*' in self.board
36+
37+
def numEmptySquares(self):
38+
return self.board.count('*')
39+
40+
def makeMove(self, square, letter):
41+
# if valid move, then make the move(assign square to letter)
42+
# then return true. if invalid, return false
43+
if self.board[square] == '*':
44+
self.board[square] = letter
45+
if self.winner(square, letter):
46+
self.currentWinner = letter
47+
return True
48+
return False
49+
50+
def winner(self, square, letter):
51+
# win = 3 in a row
52+
53+
# check row
54+
rowIndex = square // 3
55+
row = self.board[rowIndex*3 : (rowIndex+1)*3]
56+
if all([spot == letter for spot in row]):
57+
return True
58+
59+
# check col
60+
colIndex = square % 3
61+
col = [self.board[colIndex+i*3] for i in range(3)]
62+
if all([spot == letter for spot in col]):
63+
return True
64+
65+
# check diagonals
66+
# only check for even numbers
67+
# even numbers = possible move to win a diagonal
68+
if square % 2 == 0:
69+
diagonal1 = [self.board[i] for i in [0, 4, 8]] # left to right diagonal
70+
if all([spot == letter for spot in diagonal1]):
71+
return True
72+
diagonal2 = [self.board[i] for i in [2, 4, 6]] # right to left diagonal
73+
if all([spot == letter for spot in diagonal2]):
74+
return True
75+
76+
return False
77+
78+
79+
def play(game, xPlayer, oPlayer, printGame = True):
80+
# returns the winner of the game(letter) or None for a tie
81+
if printGame:
82+
game.printBoardNum()
83+
84+
letter = 'X' # starting letter
85+
# iterate while the game still has empty squares
86+
# (Don't have to worry about winner because it can easily breaks
87+
# the loop by return)
88+
while game.emptySquares():
89+
# get the move from the appropriate player
90+
if letter == 'O':
91+
square = oPlayer.getMove(game)
92+
else:
93+
square = xPlayer.getMove(game)
94+
95+
# make a move
96+
if game.makeMove(square, letter):
97+
if printGame:
98+
print(letter + f' makes a move to square {square}')
99+
game.printBoard()
100+
print('')
101+
102+
if game.currentWinner:
103+
if printGame:
104+
print(letter + 'wins!')
105+
return letter
106+
107+
#after made the move, we need to alternate letters
108+
#letter = 'O' if letter == 'X' else 'X' #switches player
109+
if letter == 'O':
110+
letter = 'X'
111+
else:
112+
letter = 'O'
113+
114+
# win condition
115+
116+
if printGame:
117+
print('It\'s a tie!')
118+
119+
if __name__ == '__main__':
120+
xPlayer = HumanPlayer('X')
121+
oPlayer = RandomComPlayer('O')
122+
t = TicTacToe()
123+
play(t, xPlayer, oPlayer, printGame=True)
124+

ticktactoe/players.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import math
2+
import random
3+
4+
class Player:
5+
def __init__(self, letter):
6+
# letter = x or o
7+
self.letter = letter
8+
9+
def getMove(self, game):
10+
pass
11+
12+
class RandomComPlayer(Player):
13+
def __init__(self, letter):
14+
super().__init__(letter)
15+
16+
def getMove(self, game):
17+
# get a random valid spot for the next move
18+
square = random.choice(game.availalbeMoves())
19+
return square
20+
21+
class HumanPlayer(Player):
22+
def __init__(self, letter):
23+
super().__init__(letter)
24+
25+
def getMove(self, game):
26+
validSquare = False
27+
val = None
28+
while not validSquare:
29+
square = input(self.letter + '\'s turn. Input move (0-9):')
30+
# we are going to check that this is a correct value by trying to cast
31+
# it to an integer, and if it's not, then we say its invalid
32+
# if that spot is not available on the board, we also say its invalid
33+
try:
34+
val = int(square)
35+
if val not in game.availalbeMoves():
36+
raise ValueError
37+
validSquare = True
38+
except ValueError:
39+
print('Invalid square. Try again.')
40+
41+
return val
42+
43+
44+
45+

0 commit comments

Comments
 (0)