Can someone please correct me on the mistake I have been having trouble with! The problem is that it is not generating a random integer in the Goalie nor Player class. This issue isn't allowing me to actually get both "players" to move.
Error:
import random
def main():
name = raw_input("Name: ")
kick = raw_input("\nWelcome " +name+ " to soccer shootout! Pick a corner to fire at! Type: TR, BR, TL, or BL! T = TOP B = BOTTOM L = LEFT R = RIGHT: ")
if Player.Shot == Goalie.Block:
print("\nThe goalie dives and blocks the shot!")
if Player.Shot != Goalie.Block:
print("\nThe ball spirals into the net!")
print(Player.Shot)
print(Goalie.Block)
class Player():
def __init__(self):
self.Shot()
def Shot(self):
shot = random.randint(0,3)
self.Shot = shot
class Goalie():
def __init__(self):
self.Block()
def Block(self):
block = random.randint(0,3)
self.Block = block
main()
you need to instantiate the class first::
try:
import random
def main():
name = raw_input("Name: ")
kick = raw_input("\nWelcome " +name+ " to soccer shootout! Pick a corner to fire at! Type: TR, BR, TL, or BL! T = TOP B = BOTTOM L = LEFT R = RIGHT: ")
player=Player() #error fixed:<-- called the class
goalie=Goalie() #error fixed:<-- called the class
if player.shot == goalie.block:#error fixed:<-- used that initiated class
print("\nThe goalie dives and blocks the shot!")
if player.shot != goalie.block:
print("\nThe ball spirals into the net!")
print(player.shot)
print(goalie.block)
class Player:
def __init__(self):
self.Shot()
def Shot(self):
shot = random.randint(0,3)
self.shot = shot #error fixed:<-- attribute and method are same
class Goalie:
def __init__(self):
self.Block()
def Block(self):
block = random.randint(0,3)
self.block = block #error fixed:<-- attribute and method are same
main()
Related
I have this code. [enemy.py].
# Enemy behaviour.
# Entities.
from ursina import Entity
# Colors.
from ursina.color import red
# 3D Vectors.
from ursina import Vec3
# Capsule model.
from ursina import Capsule
# Random.
from random import randint, choice
# Sequences and tools for it.
from ursina.sequence import Sequence, Wait, Func
# Some enemy constants.
ENEMY_MODEL = Capsule() # NOTE (TODO): Maybe later can be replaced on new enemy 3D model.
ENEMY_SCALE = (2, 2, 2)
ENEMY_COLLIDER = 'mesh'
ENEMY_COLLISION = True
ENEMY_COLOR = red
ENEMY_SPAWN_POS = (16.328, 1.500, 16.773) # XXX: Generated by console.
# Enemy class.
class Enemy(Entity):
def __init__(self) -> None:
"""Enemy class."""
super().__init__(
model=ENEMY_MODEL,
scale=Vec3(ENEMY_SCALE),
collider=ENEMY_COLLIDER,
collision=ENEMY_COLLISION,
color=ENEMY_COLOR,
position=ENEMY_SPAWN_POS
)
self.ai_enabled = False
self.friendly = False
self.move_every_secs = 5
self.sequences = [
Sequence(
Func(self.simulate_moving),
Wait(self.move_every_secs),
loop=True
)
]
self.sequences_started = False
# Enemy update function.
def update(self):
if self.ai_enabled:
if not self.sequences_started:
for sequence in self.sequences:
sequence.start()
self.sequences_started = True
elif not self.ai_enabled:
if self.sequences_started:
for sequence in self.sequences:
sequence.pause()
self.sequences_started = False
def simulate_moving(self):
"""Simulate enemy moving."""
move_by = ['x', 'z']
move_by_random = choice(move_by)
move_on = randint(5, 10)
if move_by_random == 'x':
for _ in range(int(self.position.x + move_on)):
self.position.x += 1
elif move_by_random == 'z':
for _ in range(int(self.position.z + move_on)):
self.position.z += 1
self.ai_log('Moved.')
def enable_ai(self) -> None:
"""Enable enemy AI."""
self.ai_enabled = True
def disable_ai(self) -> None:
"""Disable enemy AI."""
self.ai_enabled = False
def set_friendly(self) -> None:
"""Make enemy friendly."""
self.friendly = True
def set_not_friendly(self) -> None:
"""Make enemy not friendly."""
self.friendly = False
def update_moving_per_secs(self, new_val: int) -> None:
"""Update moving activity per seconds."""
self.move_every_secs = new_val
def ai_log(self, message) -> None:
"""Create AI log into console."""
print(f'AI (Core) : {message}')
[game.py] (Not full code, but anyway that's what we need to know).
from enemy import Enemy
enemy = Enemy()
enemy.enable_ai()
And every 5 seconds it must move, but it's doesn't move at all.
Note, that function get called.
What to do?
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
Oh, i solved it.
We need to use self.x, not self.position.x.
I want to know why State Machines use an intermediary "State" class at all (between the Concrete States and the Context). From the model below, this could be done with a simple variable.
For example, here's a simplified "containment" style state machine of sorts, which meets the same goal. What am I losing with this model, compared to using a traditional State Machine model?
Also, side question, these child classes are contained because they're indented and part of the parent (Lift) class. What is the difference to this style of inheritance vs un-indenting them and setting them to something like this: class FloorOne(Lift):
class Lift:
def __init__(self):
self.current_state = Lift.FloorOne(self)
def show_input_error(self):
print("Incorrect input")
class FloorOne:
def __init__(self, lift):
self.lift = lift
print("You are on Floor One")
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num == 2:
self.lift.current_state = Lift.FloorTwo(self.lift)
elif num == 3:
self.lift.current_state = Lift.FloorThree(self.lift)
else:
self.lift.show_input_error()
class FloorTwo:
def __init__(self, lift):
self.lift = lift
print("You are on Floor Two")
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num == 1:
self.lift.current_state = Lift.FloorOne(self.lift)
elif num == 3:
self.lift.current_state = Lift.FloorThree(self.lift)
else:
self.lift.show_input_error()
class FloorThree:
def __init__(self, lift):
self.lift = lift
print("You are on Floor Three")
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num == 1:
self.lift.current_state = Lift.FloorOne(self.lift)
elif num == 2:
self.lift.current_state = Lift.FloorTwo(self.lift)
else:
self.lift.show_input_error()
lift = Lift()
while True:
goto = input("What floor would you like to go to?")
lift.current_state.button_press(int(goto))
If you define all the floor classes as subclasses from a common class State, you gain:
It is clear, from the code, which is the common interface of the concrete states. Even you can enforce an interface adding abstract methods which have to be overriden in the concrete classes in order to be able to be instantiated
You have to code less, because you can define the methods which are equal for all states once, in the State class. For example the button_press method.
Makes code easier to change.
Look at this code:
class Lift:
def __init__(self):
self.current_state = Lift.FloorOne(self)
def show_input_error(self):
print("Incorrect input")
class State:
def __init__(self, lift):
self.lift = lift
print(f'You are on Floor {self.floor_name}')
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num != self.floor_num and num in [1,2,3]:
self.lift.current_state = [Lift.FloorOne,
Lift.FloorTwo,
Lift.FloorThree][num - 1](self.lift)
else:
self.lift.show_input_error()
class FloorOne(State):
floor_name = 'One'
floor_num = 1
class FloorTwo(State):
floor_name = 'Two'
floor_num = 2
class FloorThree(State):
floor_name = 'Three'
floor_num = 3
lift = Lift()
while True:
goto = input("What floor would you like to go to?")
lift.current_state.button_press(int(goto))
Now it is easier to add a floor.
If you want you can override any of the methods in a subclass for a different behavior:
class BrokenLift(State):
def transition(self, num):
print('broken lift!')
Im currently taking a python class and im new in programming. I have written the code below and want to write a code that tests if the ResilientPlayer actually does what it is supposed to. The code is from a chutes and ladders board game where the ResilientPlayer is a "special" type of player that gets a "superpower" in its next move afther falling down a chute. The next round afther he has fallen down a chute, he will add a given or a default number to the die_roll, and I want to test if my code actually does this! Hope someone can help me with this problem :)
class Player:
def __init__(self, board):
self.board = board
self.position = 0
self.n_steps = 0
def move(self):
die_roll = random.randint(1, 6)
self.position = self.get_position() + die_roll
self.board.position_adjustment(self.position)
self.n_steps += 1
def get_position(self):
return self.position
def get_steps(self):
return self.n_steps
class ResilientPlayer(Player):
default_extra_steps = 1
def __init__(self, board, extra_steps=None):
super().__init__(board)
self.extra_steps = extra_steps
if self.extra_steps is None:
self.extra_steps = self.default_extra_steps
def move(self):
if self.get_position() in self.board.chutes.values():
die_roll = random.randint(1, 6)
self.position = self.get_position() + die_roll + self.extra_steps
self.board.position_adjustment(self.position)
self.n_steps += 1
else:
super().move()
def get_position(self):
return self.position
def get_steps(self):
return self.n_steps
The best way to do this is using the unittest class, I do this as following:
import unittest
from .... import ResilientPlayer
class TestResilientPlayer(unittest.TestCase):
def setUp(self):
self.resilient_player = ResilientPlayer(....)
def test_move(self):
# Do stuff
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Here, unittest.main() will run all the tests in the file. setUp is run before each test (so you can have multiple tests with the same starting conditions).
This is an incredible useful module and I strongly suggest reading more on it, check the documentation
I want to write a multithreaded program for an elevator system.
The elevator system can only move if the state is running or wait state.
In the system, the instruction (which floor to go to) can be added in a multithreaded way. For managing the queue of instruction and getting the next stop for the lift, I have written a QueueManager class.
I am not able to figure out how to implement the QueueManager. The problem is I can't get my head around writing the QueueManager. Especially in figuring out how to get the next stop for the Lift from the queue.
Here's my implementation for the system in python3:
"""Implementation of a lift System"""
from enum import Enum
from typing import TypeVar
from threading import Thread
import queue
LiftType = TypeVar('LiftType', bound='Lift')
QueueManagerType = TypeVar('QueueManagerType', bound='QueueManager')
SensorNameType = TypeVar('SensorNameType', bound='SensorName')
DirectionType = TypeVar('DirectionType', bound='DirectionType')
class SensorName(Enum):
weight = 'weight'
smoke = 'smoke'
class Direction(Enum):
up = 1
down = -1
class State(Enum):
running = 'running'
wait = 'waiting'
stop = 'stop'
class Lift:
def __init__(self, num_floors: int, queue_manager: QueueManagerType):
"""
Contains all the properties of lift
"""
self.num_floors = num_floors
self.curr_direction = Direction.up
self.state = State.running
self.curr_floor = 0
self.queue_manager = queue_manager
def move(self):
"""
Moves the lift according to the instruction
"""
if self.state in [State.running, State.wait]:
if self.queue_manager.has_instruction():
self.state = State.running
stop = self.queue_manager.next_stop(self.curr_direction, self.curr_floor)
if stop:
print(stop)
else:
if self.curr_direction == Direction.up:
self.curr_direction = Direction.down
stop = self.queue_manager.next_stop(self.curr_direction,
self.curr_floor)
print(stop)
else:
self.curr_direction = Direction.up
else:
self.state = State.wait
def add_instruction(self, floor, direction=None):
"""Adds the instruction to the queue"""
if direction is None:
if self.curr_floor > floor:
direction = Direction.down
else:
direction = Direction.up
Thread(target=self.queue_manager.add_instruction, args=(floor, direction)).start()
self.move()
class QueueManager:
def __init__(self):
self.instruction_queue = queue.Queue()
def add_instruction(self, floor: int, direction: DirectionType):
"""Add an instruction to the queue. Direction is used """
self.instruction_queue.put([floor, direction])
def next_stop(self, direction: int, curr_floor: int):
"""Tells which is the next stop based on the direction provided."""
pass
def has_instruction(self):
"""If there are any instructions for the lift"""
pass
if __name__ == '__main__':
# weight_sensor = WeightSensor(SensorName.weight)
instruction_queue = QueueManager()
lift_1 = Lift(21, instruction_queue)
lift_1.add_instruction(floor=0, direction=Direction.up)
lift_1.add_instruction(floor=2)
Extension to the above program is writing a Sensor class which runs in background and sets lift to stop state if certain sensor is triggered. Which is also something I am unable to figure out.
Based on the feedback I got in the comments. Here's a multithreaded solution for an elevator system.
"""Implementation of a lift System"""
from enum import Enum
from typing import TypeVar
from threading import Lock, Thread
from heapq import heappush, heappop
import time
import random
LiftType = TypeVar('LiftType', bound='Lift')
QueueManagerType = TypeVar('QueueManagerType', bound='QueueManager')
SensorNameType = TypeVar('SensorNameType', bound='SensorName')
DirectionType = TypeVar('DirectionType', bound='DirectionType')
class SensorName(Enum):
weight = 'weight'
smoke = 'smoke'
class Direction(Enum):
up = 1
down = -1
class State(Enum):
running = 'running'
wait = 'waiting'
stop = 'stop'
class Lift:
def __init__(self, num_floors: int):
"""
Contains all the properties of lift
:param sensors: A list of sensor objects
"""
self.num_floors = num_floors
self.curr_direction = Direction.up
self.state = State.running
self.curr_floor = 0
self.instruction_queue = {Direction.up: [], Direction.down: []}
self.queue_lock = Lock()
def move(self):
"""
Moves the lift according to the instruction
"""
if self.state in [State.running, State.wait]:
if len(self.instruction_queue[Direction.up]) or len(self.instruction_queue[Direction.down]):
self.state = State.running
try:
stop = heappop(self.instruction_queue[Direction.up])
except IndexError:
stop = -1
if stop > -1:
self.curr_floor = stop
print(stop, Direction.up)
else:
if self.curr_direction == Direction.up:
self.curr_direction = Direction.down
if len(self.instruction_queue[Direction.down]):
stop = heappop(self.instruction_queue[Direction.down])
self.curr_floor = stop
print(stop, Direction.down)
else:
self.state = State.wait
else:
self.curr_direction = Direction.up
self.move()
else:
self.state = State.wait
def add_instruction(self, floor, direction=None):
if direction == Direction.up:
time.sleep(random.uniform(0,1))
else:
time.sleep(random.uniform(0,4))
if direction is None:
if self.curr_floor > floor:
direction = Direction.down
else:
direction = Direction.up
with self.queue_lock:
heappush(self.instruction_queue[direction], floor)
self.move()
if __name__ == '__main__':
lift_1 = Lift(21)
lift_1.add_instruction(0, Direction.up)
Thread(target=lift_1.add_instruction, args=(2,)).start()
Thread(target=lift_1.add_instruction, args=(5,)).start()
Thread(target=lift_1.add_instruction, args=(2,)).start()
Thread(target=lift_1.add_instruction, args=(18,)).start()
Thread(target=lift_1.add_instruction, args=(12,)).start()
Thread(target=lift_1.add_instruction, args=(21,)).start()
i'm new to OOP and I've been stuck in writing this for the past hour. I just don't understand how to assign the deck I created to 2 players !
Classes
class Card:
def __init__(self, faceNum, suitNum):
self.faceNum = faceNum
self.suitNum = suitNum
def getCardName(self):
nameSuit = ['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
nameFace = ['Coeur','Pique','Carreau','Trèfle']
return "%s of %s" % (nameFace[self.faceNum], nameSuit[self.suitNum])
def __str__(self):
carte_print1 = str(self.faceNum)
carte_print2 = str(self.suitNum)
return carte_print1 +('-')+ carte_print2
class Player:
def __init__(self,ID,Card):
self.PlayerID = ID
self.CardForPlayer = Card
Main code
import random
playerA = list()
playerB = list()
deck = list()
def deck():
deck = []
for suitNum in range(13):
for faceNum in range(4):
deck.append(Card(faceNum, suitNum))
return deck
deck = deck()
random.shuffle(deck)
for card in deck:
print(card.getCardName())
Now I just need to give 2 player an equal amount of cards how do I do this ?!
So there should be an attribute in the Player class with the name like deck. Modify your Player class like this.
class Player:
def __init__(self,ID,deck):
self.PlayerID = ID
self.deck = deck # this will hold a list of Card objects
Now in your main code, at the end of what you've written, add the following lines.
player1 = Player(1, deck())
player2 = Player(2, deck())