Join our Slack Channel
Slack: https://bit.ly/uwcoffeencodeslack
Channel Name: #war-game
#space-comp for JavaScript
Algorithmic War Game
An introduction to intermediate-level Python
Introductions
Personal Introduction
Hi, my name is Kevin Bacabac.
Who is in this Room? “So tell me about yourself”
Why Python?
Project Information
^ We’ll review all of these in the first 20 minutes
Project Information
Project Information (Why?)
Project Information
Project Schedule
Project Schedule
We’ll end off spending almost all time programming since writing code is the best way to learn.
Let’s get started
Python Installation
Pygame Installation
Good luck...
Use this to practice code snippets if you don’t have Python.
Git Install (Optional) for Windows
https://git-scm.com/downloads
Introduction to Git
Let’s get started
Intro to the War Game
War Game Bots
def action(self, country_status: dict, world_state: dict):
weapon = choice(list(Weapons))
if world_state["alive_players"]:
target = choice(tuple(world_state["alive_players"]))
return {
"Weapon": weapon,
"Target": target
}
return {}
War Game Bots Continued
Bot | Wins | Perc
None | 695 | 33%
Smart Bot | 534 | 25%
Lazy Bot | 289 | 14%
Ping Bot | 280 | 13%
Sample Bot | 112 | 5%
Greedy Bot | 98 | 5%
Class Bot | 92 | 4%
The War Game
Reviewing our Python
Table of Contents�- Variables and types
- If, else if, else syntax
- Operations, + - / * %
- Boolean operations, and, or, not
- Avoiding nested ifs
- For / while loops
- Functions
Variables
>>> a = 3
>>> b = "3"
>>> c = 3.0
IDLE Output
>>> a
3
>>> b
'3'
>>> c
3.0
Variables
>>> a = 3
>>> b = "3"
>>> c = 3.0
Addition
>>> a + a
6
>>> c + c
6.0
>>> b + b
'33'
Variables
>>> a = 3
>>> b = "3"
>>> c = 3.0
Guess the output
>>> a * a
9
>>> b * b
Traceback (most recent call last):
b * b
TypeError: can't multiply sequence by non-int of type 'str'
Preview to Casting
>>> d = int(b)
>>> d
3
>>> d * d
9
str(x), float(x), list(x), tuple(x), int(x), etc
Guess the output
>>> a * a
9
>>> b * b
Traceback (most recent call last):
b * b
TypeError: can't multiply sequence by non-int of type 'str'
Conditions
>>> if True:
print("A")
else:
print("B")
>>> if False:
print("A")
else:
print("B")
>>> if True:
print("A")
elif True:
print("B")
else:
print("C")
Answers: A, B, A
Conditions Summary
Operations
Modulo Examples��>>> 7 % 2
1
>>> -7 % 3
2
Equality + Conditions
>>> if 1 == 1:
print("nothing")
elif True:
print("interview")
>>> if 1 == “1”:
print("snowday")
elif True:
print("midterm")
>>> if 1 == 2:
print("marks")
elif 1 == “1”:
print("passing")
Answers: nothing, midterm, [literally nothing]
Boolean Operations (Case sensitive!)
Boolean Operations
What do we do with a nested if?
if handwashing:
if sleeping_well:
print("no corona")
Try boolean operations
if handwashing and sleeping_well:
print("no corona")
Loops - While
A = 0
if A < 2:
A = A + 1
if A < 2:
A = A + 1
if A < 2:
A = A + 1
...
A = 0
while A < 2:
A = A + 1
Loops - While
while True:
time.sleep(1)
if condition:
pass # Do something useful
Conditions (surprise review)
>>> if 2 < 3:
print("A")
elif 4 > 3:
print("B")
>>> if False:
print("hm")
elif "Python" > "JS":
print("not wrong")
>>> if False:
print("cold")
elif False:
print("flu")
elif True:
print("coronavirus")
Answers: A, not wrong, coronavirus
Loops - For
>>> for i in range(3):
print(i)
0
1
2
Take a variable and change its value each time we enter the loop.
Functions
def count_down():
print(“3…”)
time.sleep(1)
print(“2…”)
time.sleep(1)
print(“1…”)
time.sleep(1)
print(“I’ve literally frozen the entire game while my bot runs”)
count_down()
print(“And done!”)
Functions
def count_down():
for i in range(3):
print(i)
time.sleep(1)
This isn’t the exact same yet!
How can we clean up the count_down function using a for loop?
Functions - Arguments
def count_down(delay):
for i in range(delay):
print(i)
time.sleep(1)
Still not the same but it works.
How can we clean up the count_down function using a for loop?
Can we make the count_down more customizable?
How about count_down(3) or count_down(5)?
count_down(delay=5) is also valid!
Intermediate Python
Table of Contents�- Augmented assignment operators
- Casting
- Practice: Vertex formula
- return
- Lists, "append", "in"
- Dictionaries
- Multiple assignment
Augmented Assignment Operators
Replace, a = a + 3
With, a += 3
Similarly
*=, -=, /=, %=
Augmented Assignment Operators
Replace, a = a + 3
With, a += 3
Similarly
*=, -=, /=, %=
def get_negative(num):
result = 0
result -= num
print(result)
More Function Practice
Let’s make a function that gives the vertex of a quadratic.
f(x) = ax^2 + bx + c
The formula is x = -b / 2a.
get_vertex(1, 2, 3)
e.g. x^2 + 2x + 3
def get_vertex(a, b, c):
result = -b / (2 * a)
print(result)
More Casting Practice
What if we accidentally pass an str instead of a float?
get_vertex(“1”, “2”, “3”)
Crashes!
def get_vertex(a, b, c):
result = -float(b) / (2 * float(a))
print(result)
Looks messier but still works.
Returning to Functions
What if we want to store the result in a variable?
a = get_vertex(1, 2, 3)
Doesn’t crash but returns a special “None” value (like null).
def get_vertex(a, b, c):
result = -b / (2 * a)
return result
The function is evaluated and the returned variable becomes the value.
Returning to Functions
a = get_vertex(1, 2, 3)
What value is printed?
What does “a” become?
def get_vertex(a, b, c):
result = -b / (2 * a)
print(result)
return 1
Why return?
Helper functions
Intro to lists
>>> stones = []
>>> stones.append("time")
>>> stones.append("space")
>>> stones.append("reality")
>>> stones
['time', 'space', 'reality']
>>> stones[0]
'time'
>>> stones[1]
'space'
>>> stones[2]
'reality'
Intro to lists
>>> stones
['time', 'space', 'reality']
>>> del stones[0]
>>> stones
['space', 'reality']
>>> stones[3]
Traceback (most recent call last):
IndexError: list index out of range
>>> stones[-1]
'reality'
>>> stones[-2]
'space'
Why lists?
>>> stones
['space', 'reality']
>>> "space" in stones
True
>>> "uw" in stones
False
Intro to Dictionaries
>>> classes = {}
>>> classes["ECON212"] = "PHYS"
>>> classes["PHYS124"] = "M3"
>>> classes
{'ECON212': 'PHYS', 'PHYS124': 'M3'}
>>> classes["ECON212"]
'PHYS'
>>> classes["PHYS467"]
Traceback (most recent call last):
classes["PHYS467"]
KeyError: 'PHYS467'
Intro to Dictionaries
>>> classes
{'ECON212': 'PHYS', 'PHYS124': 'M3'}
>>> del classes["ECON212"]
>>> classes
{'PHYS124': 'M3'}
>>> classes
{'PHYS124': 'M3'}
>>> "PHYS124" in classes
True
>>> "M3" in classes
False
Intro to Dictionaries
What kind of keys are possible?
Anything that’s hashable.
>>> classes
{'PHYS124': 'M3'}
>>> classes[314] = "pi"
>>> classes
{'PHYS124': 'M3', 314: 'pi'}
Can mix types of keys!
Multiple assignment
How do you swap two variables?
And that is all.
def bad_pi():
return 3, 1, 4
a, b, c = bad_pi()
print(a)
print(b)
print(c)
Guess the data structure
Guess the data type
country_status
Contains
"Alive":
"Filename":
"Health":
…
What data type is country_status?
"Alive":
"Filename":
"Health":
"ID": [A unique integer]
"Kills":
"Name":
"Nukes":
Intermediate Python 2
Table of Contents�- for loops revisited
- Nested data types
- Lists #2, "extend", "remove"
- break
- for else
- Sets
- Lists vs sets, performance
- Tuples
For loop
>>> stones
['space', 'reality', 'time']
>>> for i in stones:
print(i)
space
reality
time
The variable becomes each element in the list in sorted order.
>>> for i in range(3):
print(i)
0
1
2
Nested data types
>>> nested = []
>>> nested.append([])
>>> nested.append(not True)
>>> nested
[[], False]
>>> nested[0]
[]
>>> nested[0].append("hidden")
>>> nested[0]
['hidden']
>>> nested[0][0]
'hidden'
>>> nested
[['hidden'], False]
More List Operations
>>> nested = {}
>>> nested["one"] = ["a", "b"]
>>> nested["two"] = ["c", "d"]
>>> nested
{'one': ['a', 'b'], 'two': ['c', 'd']}
>>> nested["one"].extend(nested["two"])
>>> nested
{'one': ['a', 'b', 'c', 'd'], 'two': ['c', 'd']}
>>> nested["one"].remove("b")
>>> nested
{'one': ['a', 'c', 'd'], 'two': ['c', 'd']}
Break
>>> nested
{'one': ['a', 'c', 'd'], 'two': ['c', 'd']}
>>> for i in nested["one"]:
print(i)
a
c
d
>>> for i in nested["one"]:
if i == "c":
break
print(i)
a
Break
>>> while True:
count += 1
print(count)
1
2
3…
Program never ends.
>>> while True:
count += 1
print(count)
if count > 3:
break
1… 2…. 3… 4.
and then we stop.
While-else, for-else?
while [code]:
[code]
break
else:
[code]
Likely Python exclusive.
for [code]:
[code]
break
else:
[code]
Sets
Remember lists are ordered
>>> earth = ["a", "b"]
>>> L3 = ["b", "a"]
>>> earth == L3
False
>>> earth == ["a", "b"]
True
>>> rocket = ["r", "a", "c", "c", "o", "o", "n"]
>>> rocket
['r', 'a', 'c', 'c', 'o', 'o', 'n']
>>> set(rocket)
{'o', 'n', 'a', 'c', 'r'}
What happened?
Sets
Why sets?
>>> mush = set(rocket)
>>> mush
{'o', 'n', 'a', 'c', 'r'}
>>> mush.remove("o")
>>> mush.add("hmm")
>>> mush
{'n', 'a', 'c', 'hmm', 'r'}
Tuples
>>> earth = ["rocks", "ice"]
>>> mars = tuple(earth)
>>> mars
('rocks', 'ice')
Tuples use ( ) instead of [ ].
>>> mars.append("people")
Traceback (most recent call last):
mars.append("people")
AttributeError: 'tuple' object has no attribute 'append'
People don’t go to Mars. Tuples are immutable.
Tuples
Why tuples?
>>> mars + mars
('rocks', 'ice', 'rocks', 'ice')
>>> earth + earth
['rocks', 'ice', 'rocks', 'ice']
Why does this work?
We can still build new tuples (and lists) from old ones.
Back to the Game
Running the Game
API
Bots Directory
Sample Bot
Next Time
Good luck with interviews / midterms. Ask me anything.